// node_modules/orderedmap/dist/index.js
function OrderedMap(content) {
  this.content = content;
}
OrderedMap.prototype = {
  constructor: OrderedMap,
  find: function(key) {
    for (var i = 0; i < this.content.length; i += 2)
      if (this.content[i] === key) return i;
    return -1;
  },
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: function(key) {
    var found2 = this.find(key);
    return found2 == -1 ? void 0 : this.content[found2 + 1];
  },
  // :: (string, any, ?string) → OrderedMap
  // Create a new map by replacing the value of `key` with a new
  // value, or adding a binding to the end of the map. If `newKey` is
  // given, the key of the binding will be replaced with that key.
  update: function(key, value, newKey) {
    var self2 = newKey && newKey != key ? this.remove(newKey) : this;
    var found2 = self2.find(key), content = self2.content.slice();
    if (found2 == -1) {
      content.push(newKey || key, value);
    } else {
      content[found2 + 1] = value;
      if (newKey) content[found2] = newKey;
    }
    return new OrderedMap(content);
  },
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: function(key) {
    var found2 = this.find(key);
    if (found2 == -1) return this;
    var content = this.content.slice();
    content.splice(found2, 2);
    return new OrderedMap(content);
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: function(key, value) {
    return new OrderedMap([key, value].concat(this.remove(key).content));
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: function(key, value) {
    var content = this.remove(key).content.slice();
    content.push(key, value);
    return new OrderedMap(content);
  },
  // :: (string, string, any) → OrderedMap
  // Add a key after the given key. If `place` is not found, the new
  // key is added to the end.
  addBefore: function(place, key, value) {
    var without = this.remove(key), content = without.content.slice();
    var found2 = without.find(place);
    content.splice(found2 == -1 ? content.length : found2, 0, key, value);
    return new OrderedMap(content);
  },
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: function(f) {
    for (var i = 0; i < this.content.length; i += 2)
      f(this.content[i], this.content[i + 1]);
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by prepending the keys in this map that don't
  // appear in `map` before the keys in `map`.
  prepend: function(map3) {
    map3 = OrderedMap.from(map3);
    if (!map3.size) return this;
    return new OrderedMap(map3.content.concat(this.subtract(map3).content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by appending the keys in this map that don't
  // appear in `map` after the keys in `map`.
  append: function(map3) {
    map3 = OrderedMap.from(map3);
    if (!map3.size) return this;
    return new OrderedMap(this.subtract(map3).content.concat(map3.content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: function(map3) {
    var result = this;
    map3 = OrderedMap.from(map3);
    for (var i = 0; i < map3.content.length; i += 2)
      result = result.remove(map3.content[i]);
    return result;
  },
  // :: () → Object
  // Turn ordered map into a plain object.
  toObject: function() {
    var result = {};
    this.forEach(function(key, value) {
      result[key] = value;
    });
    return result;
  },
  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }
};
OrderedMap.from = function(value) {
  if (value instanceof OrderedMap) return value;
  var content = [];
  if (value) for (var prop2 in value) content.push(prop2, value[prop2]);
  return new OrderedMap(content);
};
var dist_default = OrderedMap;

// node_modules/prosemirror-model/dist/index.js
function findDiffStart(a, b, pos) {
  for (let i = 0; ; i++) {
    if (i == a.childCount || i == b.childCount)
      return a.childCount == b.childCount ? null : pos;
    let childA = a.child(i), childB = b.child(i);
    if (childA == childB) {
      pos += childA.nodeSize;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return pos;
    if (childA.isText && childA.text != childB.text) {
      for (let j = 0; childA.text[j] == childB.text[j]; j++)
        pos++;
      return pos;
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffStart(childA.content, childB.content, pos + 1);
      if (inner != null)
        return inner;
    }
    pos += childA.nodeSize;
  }
}
function findDiffEnd(a, b, posA, posB) {
  for (let iA = a.childCount, iB = b.childCount; ; ) {
    if (iA == 0 || iB == 0)
      return iA == iB ? null : { a: posA, b: posB };
    let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
    if (childA == childB) {
      posA -= size;
      posB -= size;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return { a: posA, b: posB };
    if (childA.isText && childA.text != childB.text) {
      let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
      while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
        same++;
        posA--;
        posB--;
      }
      return { a: posA, b: posB };
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
      if (inner)
        return inner;
    }
    posA -= size;
    posB -= size;
  }
}
var Fragment = class _Fragment {
  /**
  @internal
  */
  constructor(content, size) {
    this.content = content;
    this.size = size || 0;
    if (size == null)
      for (let i = 0; i < content.length; i++)
        this.size += content[i].nodeSize;
  }
  /**
  Invoke a callback for all descendant nodes between the given two
  positions (relative to start of this fragment). Doesn't descend
  into a node when the callback returns `false`.
  */
  nodesBetween(from2, to, f, nodeStart = 0, parent) {
    for (let i = 0, pos = 0; pos < to; i++) {
      let child = this.content[i], end = pos + child.nodeSize;
      if (end > from2 && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
        let start = pos + 1;
        child.nodesBetween(Math.max(0, from2 - start), Math.min(child.content.size, to - start), f, nodeStart + start);
      }
      pos = end;
    }
  }
  /**
  Call the given callback for every descendant node. `pos` will be
  relative to the start of the fragment. The callback may return
  `false` to prevent traversal of a given node's children.
  */
  descendants(f) {
    this.nodesBetween(0, this.size, f);
  }
  /**
  Extract the text between `from` and `to`. See the same method on
  [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  */
  textBetween(from2, to, blockSeparator, leafText) {
    let text2 = "", first = true;
    this.nodesBetween(from2, to, (node, pos) => {
      let nodeText = node.isText ? node.text.slice(Math.max(from2, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : "";
      if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
        if (first)
          first = false;
        else
          text2 += blockSeparator;
      }
      text2 += nodeText;
    }, 0);
    return text2;
  }
  /**
  Create a new fragment containing the combined content of this
  fragment and the other.
  */
  append(other) {
    if (!other.size)
      return this;
    if (!this.size)
      return other;
    let last2 = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;
    if (last2.isText && last2.sameMarkup(first)) {
      content[content.length - 1] = last2.withText(last2.text + first.text);
      i = 1;
    }
    for (; i < other.content.length; i++)
      content.push(other.content[i]);
    return new _Fragment(content, this.size + other.size);
  }
  /**
  Cut out the sub-fragment between the two given positions.
  */
  cut(from2, to = this.size) {
    if (from2 == 0 && to == this.size)
      return this;
    let result = [], size = 0;
    if (to > from2)
      for (let i = 0, pos = 0; pos < to; i++) {
        let child = this.content[i], end = pos + child.nodeSize;
        if (end > from2) {
          if (pos < from2 || end > to) {
            if (child.isText)
              child = child.cut(Math.max(0, from2 - pos), Math.min(child.text.length, to - pos));
            else
              child = child.cut(Math.max(0, from2 - pos - 1), Math.min(child.content.size, to - pos - 1));
          }
          result.push(child);
          size += child.nodeSize;
        }
        pos = end;
      }
    return new _Fragment(result, size);
  }
  /**
  @internal
  */
  cutByIndex(from2, to) {
    if (from2 == to)
      return _Fragment.empty;
    if (from2 == 0 && to == this.content.length)
      return this;
    return new _Fragment(this.content.slice(from2, to));
  }
  /**
  Create a new fragment in which the node at the given index is
  replaced by the given node.
  */
  replaceChild(index2, node) {
    let current = this.content[index2];
    if (current == node)
      return this;
    let copy3 = this.content.slice();
    let size = this.size + node.nodeSize - current.nodeSize;
    copy3[index2] = node;
    return new _Fragment(copy3, size);
  }
  /**
  Create a new fragment by prepending the given node to this
  fragment.
  */
  addToStart(node) {
    return new _Fragment([node].concat(this.content), this.size + node.nodeSize);
  }
  /**
  Create a new fragment by appending the given node to this
  fragment.
  */
  addToEnd(node) {
    return new _Fragment(this.content.concat(node), this.size + node.nodeSize);
  }
  /**
  Compare this fragment to another one.
  */
  eq(other) {
    if (this.content.length != other.content.length)
      return false;
    for (let i = 0; i < this.content.length; i++)
      if (!this.content[i].eq(other.content[i]))
        return false;
    return true;
  }
  /**
  The first child of the fragment, or `null` if it is empty.
  */
  get firstChild() {
    return this.content.length ? this.content[0] : null;
  }
  /**
  The last child of the fragment, or `null` if it is empty.
  */
  get lastChild() {
    return this.content.length ? this.content[this.content.length - 1] : null;
  }
  /**
  The number of child nodes in this fragment.
  */
  get childCount() {
    return this.content.length;
  }
  /**
  Get the child node at the given index. Raise an error when the
  index is out of range.
  */
  child(index2) {
    let found2 = this.content[index2];
    if (!found2)
      throw new RangeError("Index " + index2 + " out of range for " + this);
    return found2;
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index2) {
    return this.content[index2] || null;
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f) {
    for (let i = 0, p = 0; i < this.content.length; i++) {
      let child = this.content[i];
      f(child, p, i);
      p += child.nodeSize;
    }
  }
  /**
  Find the first position at which this fragment and another
  fragment differ, or `null` if they are the same.
  */
  findDiffStart(other, pos = 0) {
    return findDiffStart(this, other, pos);
  }
  /**
  Find the first position, searching from the end, at which this
  fragment and the given fragment differ, or `null` if they are
  the same. Since this position will not be the same in both
  nodes, an object with two separate positions is returned.
  */
  findDiffEnd(other, pos = this.size, otherPos = other.size) {
    return findDiffEnd(this, other, pos, otherPos);
  }
  /**
  Find the index and inner offset corresponding to a given relative
  position in this fragment. The result object will be reused
  (overwritten) the next time the function is called. @internal
  */
  findIndex(pos) {
    if (pos == 0)
      return retIndex(0, pos);
    if (pos == this.size)
      return retIndex(this.content.length, pos);
    if (pos > this.size || pos < 0)
      throw new RangeError(`Position ${pos} outside of fragment (${this})`);
    for (let i = 0, curPos = 0; ; i++) {
      let cur = this.child(i), end = curPos + cur.nodeSize;
      if (end >= pos) {
        if (end == pos)
          return retIndex(i + 1, end);
        return retIndex(i, curPos);
      }
      curPos = end;
    }
  }
  /**
  Return a debugging string that describes this fragment.
  */
  toString() {
    return "<" + this.toStringInner() + ">";
  }
  /**
  @internal
  */
  toStringInner() {
    return this.content.join(", ");
  }
  /**
  Create a JSON-serializeable representation of this fragment.
  */
  toJSON() {
    return this.content.length ? this.content.map((n) => n.toJSON()) : null;
  }
  /**
  Deserialize a fragment from its JSON representation.
  */
  static fromJSON(schema, value) {
    if (!value)
      return _Fragment.empty;
    if (!Array.isArray(value))
      throw new RangeError("Invalid input for Fragment.fromJSON");
    return new _Fragment(value.map(schema.nodeFromJSON));
  }
  /**
  Build a fragment from an array of nodes. Ensures that adjacent
  text nodes with the same marks are joined together.
  */
  static fromArray(array) {
    if (!array.length)
      return _Fragment.empty;
    let joined, size = 0;
    for (let i = 0; i < array.length; i++) {
      let node = array[i];
      size += node.nodeSize;
      if (i && node.isText && array[i - 1].sameMarkup(node)) {
        if (!joined)
          joined = array.slice(0, i);
        joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
      } else if (joined) {
        joined.push(node);
      }
    }
    return new _Fragment(joined || array, size);
  }
  /**
  Create a fragment from something that can be interpreted as a
  set of nodes. For `null`, it returns the empty fragment. For a
  fragment, the fragment itself. For a node or array of nodes, a
  fragment containing those nodes.
  */
  static from(nodes) {
    if (!nodes)
      return _Fragment.empty;
    if (nodes instanceof _Fragment)
      return nodes;
    if (Array.isArray(nodes))
      return this.fromArray(nodes);
    if (nodes.attrs)
      return new _Fragment([nodes], nodes.nodeSize);
    throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  }
};
Fragment.empty = new Fragment([], 0);
var found = { index: 0, offset: 0 };
function retIndex(index2, offset) {
  found.index = index2;
  found.offset = offset;
  return found;
}
function compareDeep(a, b) {
  if (a === b)
    return true;
  if (!(a && typeof a == "object") || !(b && typeof b == "object"))
    return false;
  let array = Array.isArray(a);
  if (Array.isArray(b) != array)
    return false;
  if (array) {
    if (a.length != b.length)
      return false;
    for (let i = 0; i < a.length; i++)
      if (!compareDeep(a[i], b[i]))
        return false;
  } else {
    for (let p in a)
      if (!(p in b) || !compareDeep(a[p], b[p]))
        return false;
    for (let p in b)
      if (!(p in a))
        return false;
  }
  return true;
}
var Mark = class _Mark {
  /**
  @internal
  */
  constructor(type, attrs) {
    this.type = type;
    this.attrs = attrs;
  }
  /**
  Given a set of marks, create a new set which contains this one as
  well, in the right position. If this mark is already in the set,
  the set itself is returned. If any marks that are set to be
  [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
  those are replaced by this one.
  */
  addToSet(set) {
    let copy3, placed = false;
    for (let i = 0; i < set.length; i++) {
      let other = set[i];
      if (this.eq(other))
        return set;
      if (this.type.excludes(other.type)) {
        if (!copy3)
          copy3 = set.slice(0, i);
      } else if (other.type.excludes(this.type)) {
        return set;
      } else {
        if (!placed && other.type.rank > this.type.rank) {
          if (!copy3)
            copy3 = set.slice(0, i);
          copy3.push(this);
          placed = true;
        }
        if (copy3)
          copy3.push(other);
      }
    }
    if (!copy3)
      copy3 = set.slice();
    if (!placed)
      copy3.push(this);
    return copy3;
  }
  /**
  Remove this mark from the given set, returning a new set. If this
  mark is not in the set, the set itself is returned.
  */
  removeFromSet(set) {
    for (let i = 0; i < set.length; i++)
      if (this.eq(set[i]))
        return set.slice(0, i).concat(set.slice(i + 1));
    return set;
  }
  /**
  Test whether this mark is in the given set of marks.
  */
  isInSet(set) {
    for (let i = 0; i < set.length; i++)
      if (this.eq(set[i]))
        return true;
    return false;
  }
  /**
  Test whether this mark has the same type and attributes as
  another mark.
  */
  eq(other) {
    return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
  }
  /**
  Convert this mark to a JSON-serializeable representation.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _ in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    return obj;
  }
  /**
  Deserialize a mark from JSON.
  */
  static fromJSON(schema, json) {
    if (!json)
      throw new RangeError("Invalid input for Mark.fromJSON");
    let type = schema.marks[json.type];
    if (!type)
      throw new RangeError(`There is no mark type ${json.type} in this schema`);
    let mark = type.create(json.attrs);
    type.checkAttrs(mark.attrs);
    return mark;
  }
  /**
  Test whether two sets of marks are identical.
  */
  static sameSet(a, b) {
    if (a == b)
      return true;
    if (a.length != b.length)
      return false;
    for (let i = 0; i < a.length; i++)
      if (!a[i].eq(b[i]))
        return false;
    return true;
  }
  /**
  Create a properly sorted mark set from null, a single mark, or an
  unsorted array of marks.
  */
  static setFrom(marks) {
    if (!marks || Array.isArray(marks) && marks.length == 0)
      return _Mark.none;
    if (marks instanceof _Mark)
      return [marks];
    let copy3 = marks.slice();
    copy3.sort((a, b) => a.type.rank - b.type.rank);
    return copy3;
  }
};
Mark.none = [];
var ReplaceError = class extends Error {
};
var Slice = class _Slice {
  /**
  Create a slice. When specifying a non-zero open depth, you must
  make sure that there are nodes of at least that depth at the
  appropriate side of the fragment—i.e. if the fragment is an
  empty paragraph node, `openStart` and `openEnd` can't be greater
  than 1.
  
  It is not necessary for the content of open nodes to conform to
  the schema's content constraints, though it should be a valid
  start/end/middle for such a node, depending on which sides are
  open.
  */
  constructor(content, openStart, openEnd) {
    this.content = content;
    this.openStart = openStart;
    this.openEnd = openEnd;
  }
  /**
  The size this slice would add when inserted into a document.
  */
  get size() {
    return this.content.size - this.openStart - this.openEnd;
  }
  /**
  @internal
  */
  insertAt(pos, fragment) {
    let content = insertInto(this.content, pos + this.openStart, fragment);
    return content && new _Slice(content, this.openStart, this.openEnd);
  }
  /**
  @internal
  */
  removeBetween(from2, to) {
    return new _Slice(removeRange(this.content, from2 + this.openStart, to + this.openStart), this.openStart, this.openEnd);
  }
  /**
  Tests whether this slice is equal to another slice.
  */
  eq(other) {
    return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
  }
  /**
  @internal
  */
  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")";
  }
  /**
  Convert a slice to a JSON-serializable representation.
  */
  toJSON() {
    if (!this.content.size)
      return null;
    let json = { content: this.content.toJSON() };
    if (this.openStart > 0)
      json.openStart = this.openStart;
    if (this.openEnd > 0)
      json.openEnd = this.openEnd;
    return json;
  }
  /**
  Deserialize a slice from its JSON representation.
  */
  static fromJSON(schema, json) {
    if (!json)
      return _Slice.empty;
    let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
    if (typeof openStart != "number" || typeof openEnd != "number")
      throw new RangeError("Invalid input for Slice.fromJSON");
    return new _Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
  }
  /**
  Create a slice from a fragment by taking the maximum possible
  open value on both side of the fragment.
  */
  static maxOpen(fragment, openIsolating = true) {
    let openStart = 0, openEnd = 0;
    for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
      openStart++;
    for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
      openEnd++;
    return new _Slice(fragment, openStart, openEnd);
  }
};
Slice.empty = new Slice(Fragment.empty, 0, 0);
function removeRange(content, from2, to) {
  let { index: index2, offset } = content.findIndex(from2), child = content.maybeChild(index2);
  let { index: indexTo, offset: offsetTo } = content.findIndex(to);
  if (offset == from2 || child.isText) {
    if (offsetTo != to && !content.child(indexTo).isText)
      throw new RangeError("Removing non-flat range");
    return content.cut(0, from2).append(content.cut(to));
  }
  if (index2 != indexTo)
    throw new RangeError("Removing non-flat range");
  return content.replaceChild(index2, child.copy(removeRange(child.content, from2 - offset - 1, to - offset - 1)));
}
function insertInto(content, dist, insert, parent) {
  let { index: index2, offset } = content.findIndex(dist), child = content.maybeChild(index2);
  if (offset == dist || child.isText) {
    if (parent && !parent.canReplace(index2, index2, insert))
      return null;
    return content.cut(0, dist).append(insert).append(content.cut(dist));
  }
  let inner = insertInto(child.content, dist - offset - 1, insert, child);
  return inner && content.replaceChild(index2, child.copy(inner));
}
function replace($from, $to, slice2) {
  if (slice2.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position");
  if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd)
    throw new ReplaceError("Inconsistent open depths");
  return replaceOuter($from, $to, slice2, 0);
}
function replaceOuter($from, $to, slice2, depth) {
  let index2 = $from.index(depth), node = $from.node(depth);
  if (index2 == $to.index(depth) && depth < $from.depth - slice2.openStart) {
    let inner = replaceOuter($from, $to, slice2, depth + 1);
    return node.copy(node.content.replaceChild(index2, inner));
  } else if (!slice2.content.size) {
    return close(node, replaceTwoWay($from, $to, depth));
  } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) {
    let parent = $from.parent, content = parent.content;
    return close(parent, content.cut(0, $from.parentOffset).append(slice2.content).append(content.cut($to.parentOffset)));
  } else {
    let { start, end } = prepareSliceForReplace(slice2, $from);
    return close(node, replaceThreeWay($from, start, end, $to, depth));
  }
}
function checkJoin(main, sub2) {
  if (!sub2.type.compatibleContent(main.type))
    throw new ReplaceError("Cannot join " + sub2.type.name + " onto " + main.type.name);
}
function joinable($before, $after, depth) {
  let node = $before.node(depth);
  checkJoin(node, $after.node(depth));
  return node;
}
function addNode(child, target2) {
  let last2 = target2.length - 1;
  if (last2 >= 0 && child.isText && child.sameMarkup(target2[last2]))
    target2[last2] = child.withText(target2[last2].text + child.text);
  else
    target2.push(child);
}
function addRange($start, $end, depth, target2) {
  let node = ($end || $start).node(depth);
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
  if ($start) {
    startIndex = $start.index(depth);
    if ($start.depth > depth) {
      startIndex++;
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target2);
      startIndex++;
    }
  }
  for (let i = startIndex; i < endIndex; i++)
    addNode(node.child(i), target2);
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target2);
}
function close(node, content) {
  node.type.checkContent(content);
  return node.copy(content);
}
function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
  let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
  let content = [];
  addRange(null, $from, depth, content);
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd);
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
    addRange($start, $end, depth, content);
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
function replaceTwoWay($from, $to, depth) {
  let content = [];
  addRange(null, $from, depth, content);
  if ($from.depth > depth) {
    let type = joinable($from, $to, depth + 1);
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
function prepareSliceForReplace(slice2, $along) {
  let extra = $along.depth - slice2.openStart, parent = $along.node(extra);
  let node = parent.copy(slice2.content);
  for (let i = extra - 1; i >= 0; i--)
    node = $along.node(i).copy(Fragment.from(node));
  return {
    start: node.resolveNoCache(slice2.openStart + extra),
    end: node.resolveNoCache(node.content.size - slice2.openEnd - extra)
  };
}
var ResolvedPos = class _ResolvedPos {
  /**
  @internal
  */
  constructor(pos, path, parentOffset) {
    this.pos = pos;
    this.path = path;
    this.parentOffset = parentOffset;
    this.depth = path.length / 3 - 1;
  }
  /**
  @internal
  */
  resolveDepth(val) {
    if (val == null)
      return this.depth;
    if (val < 0)
      return this.depth + val;
    return val;
  }
  /**
  The parent node that the position points into. Note that even if
  a position points into a text node, that node is not considered
  the parent—text nodes are ‘flat’ in this model, and have no content.
  */
  get parent() {
    return this.node(this.depth);
  }
  /**
  The root node in which the position was resolved.
  */
  get doc() {
    return this.node(0);
  }
  /**
  The ancestor node at the given level. `p.node(p.depth)` is the
  same as `p.parent`.
  */
  node(depth) {
    return this.path[this.resolveDepth(depth) * 3];
  }
  /**
  The index into the ancestor at the given level. If this points
  at the 3rd node in the 2nd paragraph on the top level, for
  example, `p.index(0)` is 1 and `p.index(1)` is 2.
  */
  index(depth) {
    return this.path[this.resolveDepth(depth) * 3 + 1];
  }
  /**
  The index pointing after this position into the ancestor at the
  given level.
  */
  indexAfter(depth) {
    depth = this.resolveDepth(depth);
    return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
  }
  /**
  The (absolute) position at the start of the node at the given
  level.
  */
  start(depth) {
    depth = this.resolveDepth(depth);
    return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  }
  /**
  The (absolute) position at the end of the node at the given
  level.
  */
  end(depth) {
    depth = this.resolveDepth(depth);
    return this.start(depth) + this.node(depth).content.size;
  }
  /**
  The (absolute) position directly before the wrapping node at the
  given level, or, when `depth` is `this.depth + 1`, the original
  position.
  */
  before(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position before the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
  }
  /**
  The (absolute) position directly after the wrapping node at the
  given level, or the original position when `depth` is `this.depth + 1`.
  */
  after(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position after the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
  }
  /**
  When this position points into a text node, this returns the
  distance between the position and the start of the text node.
  Will be zero for positions that point between nodes.
  */
  get textOffset() {
    return this.pos - this.path[this.path.length - 1];
  }
  /**
  Get the node directly after the position, if any. If the position
  points into a text node, only the part of that node after the
  position is returned.
  */
  get nodeAfter() {
    let parent = this.parent, index2 = this.index(this.depth);
    if (index2 == parent.childCount)
      return null;
    let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index2);
    return dOff ? parent.child(index2).cut(dOff) : child;
  }
  /**
  Get the node directly before the position, if any. If the
  position points into a text node, only the part of that node
  before the position is returned.
  */
  get nodeBefore() {
    let index2 = this.index(this.depth);
    let dOff = this.pos - this.path[this.path.length - 1];
    if (dOff)
      return this.parent.child(index2).cut(0, dOff);
    return index2 == 0 ? null : this.parent.child(index2 - 1);
  }
  /**
  Get the position at the given index in the parent node at the
  given depth (which defaults to `this.depth`).
  */
  posAtIndex(index2, depth) {
    depth = this.resolveDepth(depth);
    let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
    for (let i = 0; i < index2; i++)
      pos += node.child(i).nodeSize;
    return pos;
  }
  /**
  Get the marks at this position, factoring in the surrounding
  marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
  position is at the start of a non-empty node, the marks of the
  node after it (if any) are returned.
  */
  marks() {
    let parent = this.parent, index2 = this.index();
    if (parent.content.size == 0)
      return Mark.none;
    if (this.textOffset)
      return parent.child(index2).marks;
    let main = parent.maybeChild(index2 - 1), other = parent.maybeChild(index2);
    if (!main) {
      let tmp = main;
      main = other;
      other = tmp;
    }
    let marks = main.marks;
    for (var i = 0; i < marks.length; i++)
      if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))
        marks = marks[i--].removeFromSet(marks);
    return marks;
  }
  /**
  Get the marks after the current position, if any, except those
  that are non-inclusive and not present at position `$end`. This
  is mostly useful for getting the set of marks to preserve after a
  deletion. Will return `null` if this position is at the end of
  its parent node or its parent node isn't a textblock (in which
  case no marks should be preserved).
  */
  marksAcross($end) {
    let after = this.parent.maybeChild(this.index());
    if (!after || !after.isInline)
      return null;
    let marks = after.marks, next = $end.parent.maybeChild($end.index());
    for (var i = 0; i < marks.length; i++)
      if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))
        marks = marks[i--].removeFromSet(marks);
    return marks;
  }
  /**
  The depth up to which this position and the given (non-resolved)
  position share the same parent nodes.
  */
  sharedDepth(pos) {
    for (let depth = this.depth; depth > 0; depth--)
      if (this.start(depth) <= pos && this.end(depth) >= pos)
        return depth;
    return 0;
  }
  /**
  Returns a range based on the place where this position and the
  given position diverge around block content. If both point into
  the same textblock, for example, a range around that textblock
  will be returned. If they point into different blocks, the range
  around those blocks in their shared ancestor is returned. You can
  pass in an optional predicate that will be called with a parent
  node to see if a range into that parent is acceptable.
  */
  blockRange(other = this, pred) {
    if (other.pos < this.pos)
      return other.blockRange(this);
    for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
      if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
        return new NodeRange(this, other, d);
    return null;
  }
  /**
  Query whether the given position shares the same parent node.
  */
  sameParent(other) {
    return this.pos - this.parentOffset == other.pos - other.parentOffset;
  }
  /**
  Return the greater of this and the given position.
  */
  max(other) {
    return other.pos > this.pos ? other : this;
  }
  /**
  Return the smaller of this and the given position.
  */
  min(other) {
    return other.pos < this.pos ? other : this;
  }
  /**
  @internal
  */
  toString() {
    let str = "";
    for (let i = 1; i <= this.depth; i++)
      str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
    return str + ":" + this.parentOffset;
  }
  /**
  @internal
  */
  static resolve(doc3, pos) {
    if (!(pos >= 0 && pos <= doc3.content.size))
      throw new RangeError("Position " + pos + " out of range");
    let path = [];
    let start = 0, parentOffset = pos;
    for (let node = doc3; ; ) {
      let { index: index2, offset } = node.content.findIndex(parentOffset);
      let rem = parentOffset - offset;
      path.push(node, index2, start + offset);
      if (!rem)
        break;
      node = node.child(index2);
      if (node.isText)
        break;
      parentOffset = rem - 1;
      start += offset + 1;
    }
    return new _ResolvedPos(pos, path, parentOffset);
  }
  /**
  @internal
  */
  static resolveCached(doc3, pos) {
    let cache2 = resolveCache.get(doc3);
    if (cache2) {
      for (let i = 0; i < cache2.elts.length; i++) {
        let elt = cache2.elts[i];
        if (elt.pos == pos)
          return elt;
      }
    } else {
      resolveCache.set(doc3, cache2 = new ResolveCache());
    }
    let result = cache2.elts[cache2.i] = _ResolvedPos.resolve(doc3, pos);
    cache2.i = (cache2.i + 1) % resolveCacheSize;
    return result;
  }
};
var ResolveCache = class {
  constructor() {
    this.elts = [];
    this.i = 0;
  }
};
var resolveCacheSize = 12;
var resolveCache = /* @__PURE__ */ new WeakMap();
var NodeRange = class {
  /**
  Construct a node range. `$from` and `$to` should point into the
  same node until at least the given `depth`, since a node range
  denotes an adjacent set of nodes in a single parent node.
  */
  constructor($from, $to, depth) {
    this.$from = $from;
    this.$to = $to;
    this.depth = depth;
  }
  /**
  The position at the start of the range.
  */
  get start() {
    return this.$from.before(this.depth + 1);
  }
  /**
  The position at the end of the range.
  */
  get end() {
    return this.$to.after(this.depth + 1);
  }
  /**
  The parent node that the range points into.
  */
  get parent() {
    return this.$from.node(this.depth);
  }
  /**
  The start index of the range in the parent node.
  */
  get startIndex() {
    return this.$from.index(this.depth);
  }
  /**
  The end index of the range in the parent node.
  */
  get endIndex() {
    return this.$to.indexAfter(this.depth);
  }
};
var emptyAttrs = /* @__PURE__ */ Object.create(null);
var Node2 = class _Node {
  /**
  @internal
  */
  constructor(type, attrs, content, marks = Mark.none) {
    this.type = type;
    this.attrs = attrs;
    this.marks = marks;
    this.content = content || Fragment.empty;
  }
  /**
  The array of this node's child nodes.
  */
  get children() {
    return this.content.content;
  }
  /**
  The size of this node, as defined by the integer-based [indexing
  scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the
  amount of characters. For other leaf nodes, it is one. For
  non-leaf nodes, it is the size of the content plus two (the
  start and end token).
  */
  get nodeSize() {
    return this.isLeaf ? 1 : 2 + this.content.size;
  }
  /**
  The number of children that the node has.
  */
  get childCount() {
    return this.content.childCount;
  }
  /**
  Get the child node at the given index. Raises an error when the
  index is out of range.
  */
  child(index2) {
    return this.content.child(index2);
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index2) {
    return this.content.maybeChild(index2);
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f) {
    this.content.forEach(f);
  }
  /**
  Invoke a callback for all descendant nodes recursively between
  the given two positions that are relative to start of this
  node's content. The callback is invoked with the node, its
  position relative to the original node (method receiver),
  its parent node, and its child index. When the callback returns
  false for a given node, that node's children will not be
  recursed over. The last parameter can be used to specify a
  starting position to count from.
  */
  nodesBetween(from2, to, f, startPos = 0) {
    this.content.nodesBetween(from2, to, f, startPos, this);
  }
  /**
  Call the given callback for every descendant node. Doesn't
  descend into a node when the callback returns `false`.
  */
  descendants(f) {
    this.nodesBetween(0, this.content.size, f);
  }
  /**
  Concatenates all the text nodes found in this fragment and its
  children.
  */
  get textContent() {
    return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
  }
  /**
  Get all text between positions `from` and `to`. When
  `blockSeparator` is given, it will be inserted to separate text
  from different block nodes. If `leafText` is given, it'll be
  inserted for every non-text leaf node encountered, otherwise
  [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.
  */
  textBetween(from2, to, blockSeparator, leafText) {
    return this.content.textBetween(from2, to, blockSeparator, leafText);
  }
  /**
  Returns this node's first child, or `null` if there are no
  children.
  */
  get firstChild() {
    return this.content.firstChild;
  }
  /**
  Returns this node's last child, or `null` if there are no
  children.
  */
  get lastChild() {
    return this.content.lastChild;
  }
  /**
  Test whether two nodes represent the same piece of document.
  */
  eq(other) {
    return this == other || this.sameMarkup(other) && this.content.eq(other.content);
  }
  /**
  Compare the markup (type, attributes, and marks) of this node to
  those of another. Returns `true` if both have the same markup.
  */
  sameMarkup(other) {
    return this.hasMarkup(other.type, other.attrs, other.marks);
  }
  /**
  Check whether this node's markup correspond to the given type,
  attributes, and marks.
  */
  hasMarkup(type, attrs, marks) {
    return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
  }
  /**
  Create a new node with the same markup as this node, containing
  the given content (or empty, if no content is given).
  */
  copy(content = null) {
    if (content == this.content)
      return this;
    return new _Node(this.type, this.attrs, content, this.marks);
  }
  /**
  Create a copy of this node, with the given set of marks instead
  of the node's own marks.
  */
  mark(marks) {
    return marks == this.marks ? this : new _Node(this.type, this.attrs, this.content, marks);
  }
  /**
  Create a copy of this node with only the content between the
  given positions. If `to` is not given, it defaults to the end of
  the node.
  */
  cut(from2, to = this.content.size) {
    if (from2 == 0 && to == this.content.size)
      return this;
    return this.copy(this.content.cut(from2, to));
  }
  /**
  Cut out the part of the document between the given positions, and
  return it as a `Slice` object.
  */
  slice(from2, to = this.content.size, includeParents = false) {
    if (from2 == to)
      return Slice.empty;
    let $from = this.resolve(from2), $to = this.resolve(to);
    let depth = includeParents ? 0 : $from.sharedDepth(to);
    let start = $from.start(depth), node = $from.node(depth);
    let content = node.content.cut($from.pos - start, $to.pos - start);
    return new Slice(content, $from.depth - depth, $to.depth - depth);
  }
  /**
  Replace the part of the document between the given positions with
  the given slice. The slice must 'fit', meaning its open sides
  must be able to connect to the surrounding content, and its
  content nodes must be valid children for the node they are placed
  into. If any of this is violated, an error of type
  [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
  */
  replace(from2, to, slice2) {
    return replace(this.resolve(from2), this.resolve(to), slice2);
  }
  /**
  Find the node directly after the given position.
  */
  nodeAt(pos) {
    for (let node = this; ; ) {
      let { index: index2, offset } = node.content.findIndex(pos);
      node = node.maybeChild(index2);
      if (!node)
        return null;
      if (offset == pos || node.isText)
        return node;
      pos -= offset + 1;
    }
  }
  /**
  Find the (direct) child node after the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childAfter(pos) {
    let { index: index2, offset } = this.content.findIndex(pos);
    return { node: this.content.maybeChild(index2), index: index2, offset };
  }
  /**
  Find the (direct) child node before the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childBefore(pos) {
    if (pos == 0)
      return { node: null, index: 0, offset: 0 };
    let { index: index2, offset } = this.content.findIndex(pos);
    if (offset < pos)
      return { node: this.content.child(index2), index: index2, offset };
    let node = this.content.child(index2 - 1);
    return { node, index: index2 - 1, offset: offset - node.nodeSize };
  }
  /**
  Resolve the given position in the document, returning an
  [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  */
  resolve(pos) {
    return ResolvedPos.resolveCached(this, pos);
  }
  /**
  @internal
  */
  resolveNoCache(pos) {
    return ResolvedPos.resolve(this, pos);
  }
  /**
  Test whether a given mark or mark type occurs in this document
  between the two given positions.
  */
  rangeHasMark(from2, to, type) {
    let found2 = false;
    if (to > from2)
      this.nodesBetween(from2, to, (node) => {
        if (type.isInSet(node.marks))
          found2 = true;
        return !found2;
      });
    return found2;
  }
  /**
  True when this is a block (non-inline node)
  */
  get isBlock() {
    return this.type.isBlock;
  }
  /**
  True when this is a textblock node, a block node with inline
  content.
  */
  get isTextblock() {
    return this.type.isTextblock;
  }
  /**
  True when this node allows inline content.
  */
  get inlineContent() {
    return this.type.inlineContent;
  }
  /**
  True when this is an inline node (a text node or a node that can
  appear among text).
  */
  get isInline() {
    return this.type.isInline;
  }
  /**
  True when this is a text node.
  */
  get isText() {
    return this.type.isText;
  }
  /**
  True when this is a leaf node.
  */
  get isLeaf() {
    return this.type.isLeaf;
  }
  /**
  True when this is an atom, i.e. when it does not have directly
  editable content. This is usually the same as `isLeaf`, but can
  be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
  on a node's spec (typically used when the node is displayed as
  an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
  */
  get isAtom() {
    return this.type.isAtom;
  }
  /**
  Return a string representation of this node for debugging
  purposes.
  */
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    let name = this.type.name;
    if (this.content.size)
      name += "(" + this.content.toStringInner() + ")";
    return wrapMarks(this.marks, name);
  }
  /**
  Get the content match in this node at the given index.
  */
  contentMatchAt(index2) {
    let match = this.type.contentMatch.matchFragment(this.content, 0, index2);
    if (!match)
      throw new Error("Called contentMatchAt on a node with invalid content");
    return match;
  }
  /**
  Test whether replacing the range between `from` and `to` (by
  child index) with the given replacement fragment (which defaults
  to the empty fragment) would leave the node's content valid. You
  can optionally pass `start` and `end` indices into the
  replacement fragment.
  */
  canReplace(from2, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
    let one = this.contentMatchAt(from2).matchFragment(replacement, start, end);
    let two = one && one.matchFragment(this.content, to);
    if (!two || !two.validEnd)
      return false;
    for (let i = start; i < end; i++)
      if (!this.type.allowsMarks(replacement.child(i).marks))
        return false;
    return true;
  }
  /**
  Test whether replacing the range `from` to `to` (by index) with
  a node of the given type would leave the node's content valid.
  */
  canReplaceWith(from2, to, type, marks) {
    if (marks && !this.type.allowsMarks(marks))
      return false;
    let start = this.contentMatchAt(from2).matchType(type);
    let end = start && start.matchFragment(this.content, to);
    return end ? end.validEnd : false;
  }
  /**
  Test whether the given node's content could be appended to this
  node. If that node is empty, this will only return true if there
  is at least one node type that can appear in both nodes (to avoid
  merging completely incompatible nodes).
  */
  canAppend(other) {
    if (other.content.size)
      return this.canReplace(this.childCount, this.childCount, other.content);
    else
      return this.type.compatibleContent(other.type);
  }
  /**
  Check whether this node and its descendants conform to the
  schema, and raise an exception when they do not.
  */
  check() {
    this.type.checkContent(this.content);
    this.type.checkAttrs(this.attrs);
    let copy3 = Mark.none;
    for (let i = 0; i < this.marks.length; i++) {
      let mark = this.marks[i];
      mark.type.checkAttrs(mark.attrs);
      copy3 = mark.addToSet(copy3);
    }
    if (!Mark.sameSet(copy3, this.marks))
      throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`);
    this.content.forEach((node) => node.check());
  }
  /**
  Return a JSON-serializeable representation of this node.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _ in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    if (this.content.size)
      obj.content = this.content.toJSON();
    if (this.marks.length)
      obj.marks = this.marks.map((n) => n.toJSON());
    return obj;
  }
  /**
  Deserialize a node from its JSON representation.
  */
  static fromJSON(schema, json) {
    if (!json)
      throw new RangeError("Invalid input for Node.fromJSON");
    let marks = void 0;
    if (json.marks) {
      if (!Array.isArray(json.marks))
        throw new RangeError("Invalid mark data for Node.fromJSON");
      marks = json.marks.map(schema.markFromJSON);
    }
    if (json.type == "text") {
      if (typeof json.text != "string")
        throw new RangeError("Invalid text node in JSON");
      return schema.text(json.text, marks);
    }
    let content = Fragment.fromJSON(schema, json.content);
    let node = schema.nodeType(json.type).create(json.attrs, content, marks);
    node.type.checkAttrs(node.attrs);
    return node;
  }
};
Node2.prototype.text = void 0;
var TextNode = class _TextNode extends Node2 {
  /**
  @internal
  */
  constructor(type, attrs, content, marks) {
    super(type, attrs, null, marks);
    if (!content)
      throw new RangeError("Empty text nodes are not allowed");
    this.text = content;
  }
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    return wrapMarks(this.marks, JSON.stringify(this.text));
  }
  get textContent() {
    return this.text;
  }
  textBetween(from2, to) {
    return this.text.slice(from2, to);
  }
  get nodeSize() {
    return this.text.length;
  }
  mark(marks) {
    return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks);
  }
  withText(text2) {
    if (text2 == this.text)
      return this;
    return new _TextNode(this.type, this.attrs, text2, this.marks);
  }
  cut(from2 = 0, to = this.text.length) {
    if (from2 == 0 && to == this.text.length)
      return this;
    return this.withText(this.text.slice(from2, to));
  }
  eq(other) {
    return this.sameMarkup(other) && this.text == other.text;
  }
  toJSON() {
    let base2 = super.toJSON();
    base2.text = this.text;
    return base2;
  }
};
function wrapMarks(marks, str) {
  for (let i = marks.length - 1; i >= 0; i--)
    str = marks[i].type.name + "(" + str + ")";
  return str;
}
var ContentMatch = class _ContentMatch {
  /**
  @internal
  */
  constructor(validEnd) {
    this.validEnd = validEnd;
    this.next = [];
    this.wrapCache = [];
  }
  /**
  @internal
  */
  static parse(string, nodeTypes) {
    let stream = new TokenStream(string, nodeTypes);
    if (stream.next == null)
      return _ContentMatch.empty;
    let expr = parseExpr(stream);
    if (stream.next)
      stream.err("Unexpected trailing text");
    let match = dfa(nfa(expr));
    checkForDeadEnds(match, stream);
    return match;
  }
  /**
  Match a node type, returning a match after that node if
  successful.
  */
  matchType(type) {
    for (let i = 0; i < this.next.length; i++)
      if (this.next[i].type == type)
        return this.next[i].next;
    return null;
  }
  /**
  Try to match a fragment. Returns the resulting match when
  successful.
  */
  matchFragment(frag, start = 0, end = frag.childCount) {
    let cur = this;
    for (let i = start; cur && i < end; i++)
      cur = cur.matchType(frag.child(i).type);
    return cur;
  }
  /**
  @internal
  */
  get inlineContent() {
    return this.next.length != 0 && this.next[0].type.isInline;
  }
  /**
  Get the first matching node type at this match position that can
  be generated.
  */
  get defaultType() {
    for (let i = 0; i < this.next.length; i++) {
      let { type } = this.next[i];
      if (!(type.isText || type.hasRequiredAttrs()))
        return type;
    }
    return null;
  }
  /**
  @internal
  */
  compatible(other) {
    for (let i = 0; i < this.next.length; i++)
      for (let j = 0; j < other.next.length; j++)
        if (this.next[i].type == other.next[j].type)
          return true;
    return false;
  }
  /**
  Try to match the given fragment, and if that fails, see if it can
  be made to match by inserting nodes in front of it. When
  successful, return a fragment of inserted nodes (which may be
  empty if nothing had to be inserted). When `toEnd` is true, only
  return a fragment if the resulting match goes to the end of the
  content expression.
  */
  fillBefore(after, toEnd = false, startIndex = 0) {
    let seen = [this];
    function search(match, types) {
      let finished = match.matchFragment(after, startIndex);
      if (finished && (!toEnd || finished.validEnd))
        return Fragment.from(types.map((tp) => tp.createAndFill()));
      for (let i = 0; i < match.next.length; i++) {
        let { type, next } = match.next[i];
        if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
          seen.push(next);
          let found2 = search(next, types.concat(type));
          if (found2)
            return found2;
        }
      }
      return null;
    }
    return search(this, []);
  }
  /**
  Find a set of wrapping node types that would allow a node of the
  given type to appear at this position. The result may be empty
  (when it fits directly) and will be null when no such wrapping
  exists.
  */
  findWrapping(target2) {
    for (let i = 0; i < this.wrapCache.length; i += 2)
      if (this.wrapCache[i] == target2)
        return this.wrapCache[i + 1];
    let computed = this.computeWrapping(target2);
    this.wrapCache.push(target2, computed);
    return computed;
  }
  /**
  @internal
  */
  computeWrapping(target2) {
    let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
    while (active.length) {
      let current = active.shift(), match = current.match;
      if (match.matchType(target2)) {
        let result = [];
        for (let obj = current; obj.type; obj = obj.via)
          result.push(obj.type);
        return result.reverse();
      }
      for (let i = 0; i < match.next.length; i++) {
        let { type, next } = match.next[i];
        if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
          active.push({ match: type.contentMatch, type, via: current });
          seen[type.name] = true;
        }
      }
    }
    return null;
  }
  /**
  The number of outgoing edges this node has in the finite
  automaton that describes the content expression.
  */
  get edgeCount() {
    return this.next.length;
  }
  /**
  Get the _n_​th outgoing edge from this node in the finite
  automaton that describes the content expression.
  */
  edge(n) {
    if (n >= this.next.length)
      throw new RangeError(`There's no ${n}th edge in this content match`);
    return this.next[n];
  }
  /**
  @internal
  */
  toString() {
    let seen = [];
    function scan(m) {
      seen.push(m);
      for (let i = 0; i < m.next.length; i++)
        if (seen.indexOf(m.next[i].next) == -1)
          scan(m.next[i].next);
    }
    scan(this);
    return seen.map((m, i) => {
      let out = i + (m.validEnd ? "*" : " ") + " ";
      for (let i2 = 0; i2 < m.next.length; i2++)
        out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next);
      return out;
    }).join("\n");
  }
};
ContentMatch.empty = new ContentMatch(true);
var TokenStream = class {
  constructor(string, nodeTypes) {
    this.string = string;
    this.nodeTypes = nodeTypes;
    this.inline = null;
    this.pos = 0;
    this.tokens = string.split(/\s*(?=\b|\W|$)/);
    if (this.tokens[this.tokens.length - 1] == "")
      this.tokens.pop();
    if (this.tokens[0] == "")
      this.tokens.shift();
  }
  get next() {
    return this.tokens[this.pos];
  }
  eat(tok) {
    return this.next == tok && (this.pos++ || true);
  }
  err(str) {
    throw new SyntaxError(str + " (in content expression '" + this.string + "')");
  }
};
function parseExpr(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSeq(stream));
  } while (stream.eat("|"));
  return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
}
function parseExprSeq(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSubscript(stream));
  } while (stream.next && stream.next != ")" && stream.next != "|");
  return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
}
function parseExprSubscript(stream) {
  let expr = parseExprAtom(stream);
  for (; ; ) {
    if (stream.eat("+"))
      expr = { type: "plus", expr };
    else if (stream.eat("*"))
      expr = { type: "star", expr };
    else if (stream.eat("?"))
      expr = { type: "opt", expr };
    else if (stream.eat("{"))
      expr = parseExprRange(stream, expr);
    else
      break;
  }
  return expr;
}
function parseNum(stream) {
  if (/\D/.test(stream.next))
    stream.err("Expected number, got '" + stream.next + "'");
  let result = Number(stream.next);
  stream.pos++;
  return result;
}
function parseExprRange(stream, expr) {
  let min = parseNum(stream), max = min;
  if (stream.eat(",")) {
    if (stream.next != "}")
      max = parseNum(stream);
    else
      max = -1;
  }
  if (!stream.eat("}"))
    stream.err("Unclosed braced range");
  return { type: "range", min, max, expr };
}
function resolveName(stream, name) {
  let types = stream.nodeTypes, type = types[name];
  if (type)
    return [type];
  let result = [];
  for (let typeName in types) {
    let type2 = types[typeName];
    if (type2.isInGroup(name))
      result.push(type2);
  }
  if (result.length == 0)
    stream.err("No node type or group '" + name + "' found");
  return result;
}
function parseExprAtom(stream) {
  if (stream.eat("(")) {
    let expr = parseExpr(stream);
    if (!stream.eat(")"))
      stream.err("Missing closing paren");
    return expr;
  } else if (!/\W/.test(stream.next)) {
    let exprs = resolveName(stream, stream.next).map((type) => {
      if (stream.inline == null)
        stream.inline = type.isInline;
      else if (stream.inline != type.isInline)
        stream.err("Mixing inline and block content");
      return { type: "name", value: type };
    });
    stream.pos++;
    return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  } else {
    stream.err("Unexpected token '" + stream.next + "'");
  }
}
function nfa(expr) {
  let nfa2 = [[]];
  connect(compile(expr, 0), node());
  return nfa2;
  function node() {
    return nfa2.push([]) - 1;
  }
  function edge(from2, to, term) {
    let edge2 = { term, to };
    nfa2[from2].push(edge2);
    return edge2;
  }
  function connect(edges, to) {
    edges.forEach((edge2) => edge2.to = to);
  }
  function compile(expr2, from2) {
    if (expr2.type == "choice") {
      return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from2)), []);
    } else if (expr2.type == "seq") {
      for (let i = 0; ; i++) {
        let next = compile(expr2.exprs[i], from2);
        if (i == expr2.exprs.length - 1)
          return next;
        connect(next, from2 = node());
      }
    } else if (expr2.type == "star") {
      let loop = node();
      edge(from2, loop);
      connect(compile(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "plus") {
      let loop = node();
      connect(compile(expr2.expr, from2), loop);
      connect(compile(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "opt") {
      return [edge(from2)].concat(compile(expr2.expr, from2));
    } else if (expr2.type == "range") {
      let cur = from2;
      for (let i = 0; i < expr2.min; i++) {
        let next = node();
        connect(compile(expr2.expr, cur), next);
        cur = next;
      }
      if (expr2.max == -1) {
        connect(compile(expr2.expr, cur), cur);
      } else {
        for (let i = expr2.min; i < expr2.max; i++) {
          let next = node();
          edge(cur, next);
          connect(compile(expr2.expr, cur), next);
          cur = next;
        }
      }
      return [edge(cur)];
    } else if (expr2.type == "name") {
      return [edge(from2, void 0, expr2.value)];
    } else {
      throw new Error("Unknown expr type");
    }
  }
}
function cmp(a, b) {
  return b - a;
}
function nullFrom(nfa2, node) {
  let result = [];
  scan(node);
  return result.sort(cmp);
  function scan(node2) {
    let edges = nfa2[node2];
    if (edges.length == 1 && !edges[0].term)
      return scan(edges[0].to);
    result.push(node2);
    for (let i = 0; i < edges.length; i++) {
      let { term, to } = edges[i];
      if (!term && result.indexOf(to) == -1)
        scan(to);
    }
  }
}
function dfa(nfa2) {
  let labeled = /* @__PURE__ */ Object.create(null);
  return explore(nullFrom(nfa2, 0));
  function explore(states) {
    let out = [];
    states.forEach((node) => {
      nfa2[node].forEach(({ term, to }) => {
        if (!term)
          return;
        let set;
        for (let i = 0; i < out.length; i++)
          if (out[i][0] == term)
            set = out[i][1];
        nullFrom(nfa2, to).forEach((node2) => {
          if (!set)
            out.push([term, set = []]);
          if (set.indexOf(node2) == -1)
            set.push(node2);
        });
      });
    });
    let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
    for (let i = 0; i < out.length; i++) {
      let states2 = out[i][1].sort(cmp);
      state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) });
    }
    return state;
  }
}
function checkForDeadEnds(match, stream) {
  for (let i = 0, work = [match]; i < work.length; i++) {
    let state = work[i], dead = !state.validEnd, nodes = [];
    for (let j = 0; j < state.next.length; j++) {
      let { type, next } = state.next[j];
      nodes.push(type.name);
      if (dead && !(type.isText || type.hasRequiredAttrs()))
        dead = false;
      if (work.indexOf(next) == -1)
        work.push(next);
    }
    if (dead)
      stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  }
}
function defaultAttrs(attrs) {
  let defaults = /* @__PURE__ */ Object.create(null);
  for (let attrName in attrs) {
    let attr = attrs[attrName];
    if (!attr.hasDefault)
      return null;
    defaults[attrName] = attr.default;
  }
  return defaults;
}
function computeAttrs(attrs, value) {
  let built = /* @__PURE__ */ Object.create(null);
  for (let name in attrs) {
    let given = value && value[name];
    if (given === void 0) {
      let attr = attrs[name];
      if (attr.hasDefault)
        given = attr.default;
      else
        throw new RangeError("No value supplied for attribute " + name);
    }
    built[name] = given;
  }
  return built;
}
function checkAttrs(attrs, values, type, name) {
  for (let name2 in values)
    if (!(name2 in attrs))
      throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`);
  for (let name2 in attrs) {
    let attr = attrs[name2];
    if (attr.validate)
      attr.validate(values[name2]);
  }
}
function initAttrs(typeName, attrs) {
  let result = /* @__PURE__ */ Object.create(null);
  if (attrs)
    for (let name in attrs)
      result[name] = new Attribute(typeName, name, attrs[name]);
  return result;
}
var NodeType = class _NodeType {
  /**
  @internal
  */
  constructor(name, schema, spec) {
    this.name = name;
    this.schema = schema;
    this.spec = spec;
    this.markSet = null;
    this.groups = spec.group ? spec.group.split(" ") : [];
    this.attrs = initAttrs(name, spec.attrs);
    this.defaultAttrs = defaultAttrs(this.attrs);
    this.contentMatch = null;
    this.inlineContent = null;
    this.isBlock = !(spec.inline || name == "text");
    this.isText = name == "text";
  }
  /**
  True if this is an inline type.
  */
  get isInline() {
    return !this.isBlock;
  }
  /**
  True if this is a textblock type, a block that contains inline
  content.
  */
  get isTextblock() {
    return this.isBlock && this.inlineContent;
  }
  /**
  True for node types that allow no content.
  */
  get isLeaf() {
    return this.contentMatch == ContentMatch.empty;
  }
  /**
  True when this node is an atom, i.e. when it does not have
  directly editable content.
  */
  get isAtom() {
    return this.isLeaf || !!this.spec.atom;
  }
  /**
  Return true when this node type is part of the given
  [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
  */
  isInGroup(group) {
    return this.groups.indexOf(group) > -1;
  }
  /**
  The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
  */
  get whitespace() {
    return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
  }
  /**
  Tells you whether this node type has any required attributes.
  */
  hasRequiredAttrs() {
    for (let n in this.attrs)
      if (this.attrs[n].isRequired)
        return true;
    return false;
  }
  /**
  Indicates whether this node allows some of the same content as
  the given node type.
  */
  compatibleContent(other) {
    return this == other || this.contentMatch.compatible(other.contentMatch);
  }
  /**
  @internal
  */
  computeAttrs(attrs) {
    if (!attrs && this.defaultAttrs)
      return this.defaultAttrs;
    else
      return computeAttrs(this.attrs, attrs);
  }
  /**
  Create a `Node` of this type. The given attributes are
  checked and defaulted (you can pass `null` to use the type's
  defaults entirely, if no required attributes exist). `content`
  may be a `Fragment`, a node, an array of nodes, or
  `null`. Similarly `marks` may be `null` to default to the empty
  set of marks.
  */
  create(attrs = null, content, marks) {
    if (this.isText)
      throw new Error("NodeType.create can't construct text nodes");
    return new Node2(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
  against the node type's content restrictions, and throw an error
  if it doesn't match.
  */
  createChecked(attrs = null, content, marks) {
    content = Fragment.from(content);
    this.checkContent(content);
    return new Node2(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
  necessary to add nodes to the start or end of the given fragment
  to make it fit the node. If no fitting wrapping can be found,
  return null. Note that, due to the fact that required nodes can
  always be created, this will always succeed if you pass null or
  `Fragment.empty` as content.
  */
  createAndFill(attrs = null, content, marks) {
    attrs = this.computeAttrs(attrs);
    content = Fragment.from(content);
    if (content.size) {
      let before = this.contentMatch.fillBefore(content);
      if (!before)
        return null;
      content = before.append(content);
    }
    let matched = this.contentMatch.matchFragment(content);
    let after = matched && matched.fillBefore(Fragment.empty, true);
    if (!after)
      return null;
    return new Node2(this, attrs, content.append(after), Mark.setFrom(marks));
  }
  /**
  Returns true if the given fragment is valid content for this node
  type.
  */
  validContent(content) {
    let result = this.contentMatch.matchFragment(content);
    if (!result || !result.validEnd)
      return false;
    for (let i = 0; i < content.childCount; i++)
      if (!this.allowsMarks(content.child(i).marks))
        return false;
    return true;
  }
  /**
  Throws a RangeError if the given fragment is not valid content for this
  node type.
  @internal
  */
  checkContent(content) {
    if (!this.validContent(content))
      throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
  }
  /**
  @internal
  */
  checkAttrs(attrs) {
    checkAttrs(this.attrs, attrs, "node", this.name);
  }
  /**
  Check whether the given mark type is allowed in this node.
  */
  allowsMarkType(markType) {
    return this.markSet == null || this.markSet.indexOf(markType) > -1;
  }
  /**
  Test whether the given set of marks are allowed in this node.
  */
  allowsMarks(marks) {
    if (this.markSet == null)
      return true;
    for (let i = 0; i < marks.length; i++)
      if (!this.allowsMarkType(marks[i].type))
        return false;
    return true;
  }
  /**
  Removes the marks that are not allowed in this node from the given set.
  */
  allowedMarks(marks) {
    if (this.markSet == null)
      return marks;
    let copy3;
    for (let i = 0; i < marks.length; i++) {
      if (!this.allowsMarkType(marks[i].type)) {
        if (!copy3)
          copy3 = marks.slice(0, i);
      } else if (copy3) {
        copy3.push(marks[i]);
      }
    }
    return !copy3 ? marks : copy3.length ? copy3 : Mark.none;
  }
  /**
  @internal
  */
  static compile(nodes, schema) {
    let result = /* @__PURE__ */ Object.create(null);
    nodes.forEach((name, spec) => result[name] = new _NodeType(name, schema, spec));
    let topType = schema.spec.topNode || "doc";
    if (!result[topType])
      throw new RangeError("Schema is missing its top node type ('" + topType + "')");
    if (!result.text)
      throw new RangeError("Every schema needs a 'text' type");
    for (let _ in result.text.attrs)
      throw new RangeError("The text node type should not have attributes");
    return result;
  }
};
function validateType(typeName, attrName, type) {
  let types = type.split("|");
  return (value) => {
    let name = value === null ? "null" : typeof value;
    if (types.indexOf(name) < 0)
      throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);
  };
}
var Attribute = class {
  constructor(typeName, attrName, options) {
    this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
    this.default = options.default;
    this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
  }
  get isRequired() {
    return !this.hasDefault;
  }
};
var MarkType = class _MarkType {
  /**
  @internal
  */
  constructor(name, rank, schema, spec) {
    this.name = name;
    this.rank = rank;
    this.schema = schema;
    this.spec = spec;
    this.attrs = initAttrs(name, spec.attrs);
    this.excluded = null;
    let defaults = defaultAttrs(this.attrs);
    this.instance = defaults ? new Mark(this, defaults) : null;
  }
  /**
  Create a mark of this type. `attrs` may be `null` or an object
  containing only some of the mark's attributes. The others, if
  they have defaults, will be added.
  */
  create(attrs = null) {
    if (!attrs && this.instance)
      return this.instance;
    return new Mark(this, computeAttrs(this.attrs, attrs));
  }
  /**
  @internal
  */
  static compile(marks, schema) {
    let result = /* @__PURE__ */ Object.create(null), rank = 0;
    marks.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema, spec));
    return result;
  }
  /**
  When there is a mark of this type in the given set, a new set
  without it is returned. Otherwise, the input set is returned.
  */
  removeFromSet(set) {
    for (var i = 0; i < set.length; i++)
      if (set[i].type == this) {
        set = set.slice(0, i).concat(set.slice(i + 1));
        i--;
      }
    return set;
  }
  /**
  Tests whether there is a mark of this type in the given set.
  */
  isInSet(set) {
    for (let i = 0; i < set.length; i++)
      if (set[i].type == this)
        return set[i];
  }
  /**
  @internal
  */
  checkAttrs(attrs) {
    checkAttrs(this.attrs, attrs, "mark", this.name);
  }
  /**
  Queries whether a given mark type is
  [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  */
  excludes(other) {
    return this.excluded.indexOf(other) > -1;
  }
};
var Schema = class {
  /**
  Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  */
  constructor(spec) {
    this.linebreakReplacement = null;
    this.cached = /* @__PURE__ */ Object.create(null);
    let instanceSpec = this.spec = {};
    for (let prop2 in spec)
      instanceSpec[prop2] = spec[prop2];
    instanceSpec.nodes = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);
    this.marks = MarkType.compile(this.spec.marks, this);
    let contentExprCache = /* @__PURE__ */ Object.create(null);
    for (let prop2 in this.nodes) {
      if (prop2 in this.marks)
        throw new RangeError(prop2 + " can not be both a node and a mark");
      let type = this.nodes[prop2], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
      type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
      type.inlineContent = type.contentMatch.inlineContent;
      if (type.spec.linebreakReplacement) {
        if (this.linebreakReplacement)
          throw new RangeError("Multiple linebreak nodes defined");
        if (!type.isInline || !type.isLeaf)
          throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
        this.linebreakReplacement = type;
      }
      type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
    }
    for (let prop2 in this.marks) {
      let type = this.marks[prop2], excl2 = type.spec.excludes;
      type.excluded = excl2 == null ? [type] : excl2 == "" ? [] : gatherMarks(this, excl2.split(" "));
    }
    this.nodeFromJSON = (json) => Node2.fromJSON(this, json);
    this.markFromJSON = (json) => Mark.fromJSON(this, json);
    this.topNodeType = this.nodes[this.spec.topNode || "doc"];
    this.cached.wrappings = /* @__PURE__ */ Object.create(null);
  }
  /**
  Create a node in this schema. The `type` may be a string or a
  `NodeType` instance. Attributes will be extended with defaults,
  `content` may be a `Fragment`, `null`, a `Node`, or an array of
  nodes.
  */
  node(type, attrs = null, content, marks) {
    if (typeof type == "string")
      type = this.nodeType(type);
    else if (!(type instanceof NodeType))
      throw new RangeError("Invalid node type: " + type);
    else if (type.schema != this)
      throw new RangeError("Node type from different schema used (" + type.name + ")");
    return type.createChecked(attrs, content, marks);
  }
  /**
  Create a text node in the schema. Empty text nodes are not
  allowed.
  */
  text(text2, marks) {
    let type = this.nodes.text;
    return new TextNode(type, type.defaultAttrs, text2, Mark.setFrom(marks));
  }
  /**
  Create a mark with the given type and attributes.
  */
  mark(type, attrs) {
    if (typeof type == "string")
      type = this.marks[type];
    return type.create(attrs);
  }
  /**
  @internal
  */
  nodeType(name) {
    let found2 = this.nodes[name];
    if (!found2)
      throw new RangeError("Unknown node type: " + name);
    return found2;
  }
};
function gatherMarks(schema, marks) {
  let found2 = [];
  for (let i = 0; i < marks.length; i++) {
    let name = marks[i], mark = schema.marks[name], ok = mark;
    if (mark) {
      found2.push(mark);
    } else {
      for (let prop2 in schema.marks) {
        let mark2 = schema.marks[prop2];
        if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1)
          found2.push(ok = mark2);
      }
    }
    if (!ok)
      throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
  }
  return found2;
}
function isTagRule(rule) {
  return rule.tag != null;
}
function isStyleRule(rule) {
  return rule.style != null;
}
var DOMParser = class _DOMParser {
  /**
  Create a parser that targets the given schema, using the given
  parsing rules.
  */
  constructor(schema, rules) {
    this.schema = schema;
    this.rules = rules;
    this.tags = [];
    this.styles = [];
    let matchedStyles = this.matchedStyles = [];
    rules.forEach((rule) => {
      if (isTagRule(rule)) {
        this.tags.push(rule);
      } else if (isStyleRule(rule)) {
        let prop2 = /[^=]*/.exec(rule.style)[0];
        if (matchedStyles.indexOf(prop2) < 0)
          matchedStyles.push(prop2);
        this.styles.push(rule);
      }
    });
    this.normalizeLists = !this.tags.some((r) => {
      if (!/^(ul|ol)\b/.test(r.tag) || !r.node)
        return false;
      let node = schema.nodes[r.node];
      return node.contentMatch.matchType(node);
    });
  }
  /**
  Parse a document from the content of a DOM node.
  */
  parse(dom, options = {}) {
    let context = new ParseContext(this, options, false);
    context.addAll(dom, Mark.none, options.from, options.to);
    return context.finish();
  }
  /**
  Parses the content of the given DOM node, like
  [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
  options. But unlike that method, which produces a whole node,
  this one returns a slice that is open at the sides, meaning that
  the schema constraints aren't applied to the start of nodes to
  the left of the input and the end of nodes at the end.
  */
  parseSlice(dom, options = {}) {
    let context = new ParseContext(this, options, true);
    context.addAll(dom, Mark.none, options.from, options.to);
    return Slice.maxOpen(context.finish());
  }
  /**
  @internal
  */
  matchTag(dom, context, after) {
    for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {
      let rule = this.tags[i];
      if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
        if (rule.getAttrs) {
          let result = rule.getAttrs(dom);
          if (result === false)
            continue;
          rule.attrs = result || void 0;
        }
        return rule;
      }
    }
  }
  /**
  @internal
  */
  matchStyle(prop2, value, context, after) {
    for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {
      let rule = this.styles[i], style = rule.style;
      if (style.indexOf(prop2) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
      // or has an '=' sign after the prop, followed by the given
      // value.
      style.length > prop2.length && (style.charCodeAt(prop2.length) != 61 || style.slice(prop2.length + 1) != value))
        continue;
      if (rule.getAttrs) {
        let result = rule.getAttrs(value);
        if (result === false)
          continue;
        rule.attrs = result || void 0;
      }
      return rule;
    }
  }
  /**
  @internal
  */
  static schemaRules(schema) {
    let result = [];
    function insert(rule) {
      let priority = rule.priority == null ? 50 : rule.priority, i = 0;
      for (; i < result.length; i++) {
        let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;
        if (nextPriority < priority)
          break;
      }
      result.splice(i, 0, rule);
    }
    for (let name in schema.marks) {
      let rules = schema.marks[name].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.mark || rule.ignore || rule.clearMark))
            rule.mark = name;
        });
    }
    for (let name in schema.nodes) {
      let rules = schema.nodes[name].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.node || rule.ignore || rule.mark))
            rule.node = name;
        });
    }
    return result;
  }
  /**
  Construct a DOM parser using the parsing rules listed in a
  schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
  [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).
  */
  static fromSchema(schema) {
    return schema.cached.domParser || (schema.cached.domParser = new _DOMParser(schema, _DOMParser.schemaRules(schema)));
  }
};
var blockTags = {
  address: true,
  article: true,
  aside: true,
  blockquote: true,
  canvas: true,
  dd: true,
  div: true,
  dl: true,
  fieldset: true,
  figcaption: true,
  figure: true,
  footer: true,
  form: true,
  h1: true,
  h2: true,
  h3: true,
  h4: true,
  h5: true,
  h6: true,
  header: true,
  hgroup: true,
  hr: true,
  li: true,
  noscript: true,
  ol: true,
  output: true,
  p: true,
  pre: true,
  section: true,
  table: true,
  tfoot: true,
  ul: true
};
var ignoreTags = {
  head: true,
  noscript: true,
  object: true,
  script: true,
  style: true,
  title: true
};
var listTags = { ol: true, ul: true };
var OPT_PRESERVE_WS = 1;
var OPT_PRESERVE_WS_FULL = 2;
var OPT_OPEN_LEFT = 4;
function wsOptionsFor(type, preserveWhitespace, base2) {
  if (preserveWhitespace != null)
    return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
  return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT;
}
var NodeContext = class {
  constructor(type, attrs, marks, solid, match, options) {
    this.type = type;
    this.attrs = attrs;
    this.marks = marks;
    this.solid = solid;
    this.options = options;
    this.content = [];
    this.activeMarks = Mark.none;
    this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
  }
  findWrapping(node) {
    if (!this.match) {
      if (!this.type)
        return [];
      let fill = this.type.contentMatch.fillBefore(Fragment.from(node));
      if (fill) {
        this.match = this.type.contentMatch.matchFragment(fill);
      } else {
        let start = this.type.contentMatch, wrap2;
        if (wrap2 = start.findWrapping(node.type)) {
          this.match = start;
          return wrap2;
        } else {
          return null;
        }
      }
    }
    return this.match.findWrapping(node.type);
  }
  finish(openEnd) {
    if (!(this.options & OPT_PRESERVE_WS)) {
      let last2 = this.content[this.content.length - 1], m;
      if (last2 && last2.isText && (m = /[ \t\r\n\u000c]+$/.exec(last2.text))) {
        let text2 = last2;
        if (last2.text.length == m[0].length)
          this.content.pop();
        else
          this.content[this.content.length - 1] = text2.withText(text2.text.slice(0, text2.text.length - m[0].length));
      }
    }
    let content = Fragment.from(this.content);
    if (!openEnd && this.match)
      content = content.append(this.match.fillBefore(Fragment.empty, true));
    return this.type ? this.type.create(this.attrs, content, this.marks) : content;
  }
  inlineContext(node) {
    if (this.type)
      return this.type.inlineContent;
    if (this.content.length)
      return this.content[0].isInline;
    return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());
  }
};
var ParseContext = class {
  constructor(parser, options, isOpen) {
    this.parser = parser;
    this.options = options;
    this.isOpen = isOpen;
    this.open = 0;
    this.localPreserveWS = false;
    let topNode = options.topNode, topContext;
    let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
    if (topNode)
      topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);
    else if (isOpen)
      topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);
    else
      topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);
    this.nodes = [topContext];
    this.find = options.findPositions;
    this.needsBlock = false;
  }
  get top() {
    return this.nodes[this.open];
  }
  // Add a DOM node to the content. Text is inserted as text node,
  // otherwise, the node is passed to `addElement` or, if it has a
  // `style` attribute, `addElementWithStyles`.
  addDOM(dom, marks) {
    if (dom.nodeType == 3)
      this.addTextNode(dom, marks);
    else if (dom.nodeType == 1)
      this.addElement(dom, marks);
  }
  addTextNode(dom, marks) {
    let value = dom.nodeValue;
    let top2 = this.top, preserveWS = top2.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top2.options & OPT_PRESERVE_WS) > 0;
    let { schema } = this.parser;
    if (preserveWS === "full" || top2.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) {
      if (!preserveWS) {
        value = value.replace(/[ \t\r\n\u000c]+/g, " ");
        if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
          let nodeBefore = top2.content[top2.content.length - 1];
          let domNodeBefore = dom.previousSibling;
          if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))
            value = value.slice(1);
        }
      } else if (preserveWS === "full") {
        value = value.replace(/\r\n?/g, "\n");
      } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {
        let lines = value.split(/\r?\n|\r/);
        for (let i = 0; i < lines.length; i++) {
          if (i)
            this.insertNode(schema.linebreakReplacement.create(), marks, true);
          if (lines[i])
            this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i]));
        }
        value = "";
      } else {
        value = value.replace(/\r?\n|\r/g, " ");
      }
      if (value)
        this.insertNode(schema.text(value), marks, !/\S/.test(value));
      this.findInText(dom);
    } else {
      this.findInside(dom);
    }
  }
  // Try to find a handler for the given tag and use that to parse. If
  // none is found, the element's content nodes are added directly.
  addElement(dom, marks, matchAfter) {
    let outerWS = this.localPreserveWS, top2 = this.top;
    if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
      this.localPreserveWS = true;
    let name = dom.nodeName.toLowerCase(), ruleID;
    if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)
      normalizeList(dom);
    let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));
    out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
      this.findInside(dom);
      this.ignoreFallback(dom, marks);
    } else if (!rule || rule.skip || rule.closeParent) {
      if (rule && rule.closeParent)
        this.open = Math.max(0, this.open - 1);
      else if (rule && rule.skip.nodeType)
        dom = rule.skip;
      let sync, oldNeedsBlock = this.needsBlock;
      if (blockTags.hasOwnProperty(name)) {
        if (top2.content.length && top2.content[0].isInline && this.open) {
          this.open--;
          top2 = this.top;
        }
        sync = true;
        if (!top2.type)
          this.needsBlock = true;
      } else if (!dom.firstChild) {
        this.leafFallback(dom, marks);
        break out;
      }
      let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
      if (innerMarks)
        this.addAll(dom, innerMarks);
      if (sync)
        this.sync(top2);
      this.needsBlock = oldNeedsBlock;
    } else {
      let innerMarks = this.readStyles(dom, marks);
      if (innerMarks)
        this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0);
    }
    this.localPreserveWS = outerWS;
  }
  // Called for leaf DOM nodes that would otherwise be ignored
  leafFallback(dom, marks) {
    if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
      this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
  }
  // Called for ignored nodes
  ignoreFallback(dom, marks) {
    if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
      this.findPlace(this.parser.schema.text("-"), marks, true);
  }
  // Run any style parser associated with the node's styles. Either
  // return an updated array of marks, or null to indicate some of the
  // styles had a rule with `ignore` set.
  readStyles(dom, marks) {
    let styles = dom.style;
    if (styles && styles.length)
      for (let i = 0; i < this.parser.matchedStyles.length; i++) {
        let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);
        if (value)
          for (let after = void 0; ; ) {
            let rule = this.parser.matchStyle(name, value, this, after);
            if (!rule)
              break;
            if (rule.ignore)
              return null;
            if (rule.clearMark)
              marks = marks.filter((m) => !rule.clearMark(m));
            else
              marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
            if (rule.consuming === false)
              after = rule;
            else
              break;
          }
      }
    return marks;
  }
  // Look up a handler for the given node. If none are found, return
  // false. Otherwise, apply it, use its return value to drive the way
  // the node's content is wrapped, and return true.
  addElementByRule(dom, rule, marks, continueAfter) {
    let sync, nodeType;
    if (rule.node) {
      nodeType = this.parser.schema.nodes[rule.node];
      if (!nodeType.isLeaf) {
        let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
        if (inner) {
          sync = true;
          marks = inner;
        }
      } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) {
        this.leafFallback(dom, marks);
      }
    } else {
      let markType = this.parser.schema.marks[rule.mark];
      marks = marks.concat(markType.create(rule.attrs));
    }
    let startIn = this.top;
    if (nodeType && nodeType.isLeaf) {
      this.findInside(dom);
    } else if (continueAfter) {
      this.addElement(dom, marks, continueAfter);
    } else if (rule.getContent) {
      this.findInside(dom);
      rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false));
    } else {
      let contentDOM = dom;
      if (typeof rule.contentElement == "string")
        contentDOM = dom.querySelector(rule.contentElement);
      else if (typeof rule.contentElement == "function")
        contentDOM = rule.contentElement(dom);
      else if (rule.contentElement)
        contentDOM = rule.contentElement;
      this.findAround(dom, contentDOM, true);
      this.addAll(contentDOM, marks);
      this.findAround(dom, contentDOM, false);
    }
    if (sync && this.sync(startIn))
      this.open--;
  }
  // Add all child nodes between `startIndex` and `endIndex` (or the
  // whole node, if not given). If `sync` is passed, use it to
  // synchronize after every block element.
  addAll(parent, marks, startIndex, endIndex) {
    let index2 = startIndex || 0;
    for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index2) {
      this.findAtPoint(parent, index2);
      this.addDOM(dom, marks);
    }
    this.findAtPoint(parent, index2);
  }
  // Try to find a way to fit the given node type into the current
  // context. May add intermediate wrappers and/or leave non-solid
  // nodes that we're in.
  findPlace(node, marks, cautious) {
    let route, sync;
    for (let depth = this.open, penalty = 0; depth >= 0; depth--) {
      let cx = this.nodes[depth];
      let found2 = cx.findWrapping(node);
      if (found2 && (!route || route.length > found2.length + penalty)) {
        route = found2;
        sync = cx;
        if (!found2.length)
          break;
      }
      if (cx.solid) {
        if (cautious)
          break;
        penalty += 2;
      }
    }
    if (!route)
      return null;
    this.sync(sync);
    for (let i = 0; i < route.length; i++)
      marks = this.enterInner(route[i], null, marks, false);
    return marks;
  }
  // Try to insert the given node, adjusting the context when needed.
  insertNode(node, marks, cautious) {
    if (node.isInline && this.needsBlock && !this.top.type) {
      let block2 = this.textblockFromContext();
      if (block2)
        marks = this.enterInner(block2, null, marks);
    }
    let innerMarks = this.findPlace(node, marks, cautious);
    if (innerMarks) {
      this.closeExtra();
      let top2 = this.top;
      if (top2.match)
        top2.match = top2.match.matchType(node.type);
      let nodeMarks = Mark.none;
      for (let m of innerMarks.concat(node.marks))
        if (top2.type ? top2.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))
          nodeMarks = m.addToSet(nodeMarks);
      top2.content.push(node.mark(nodeMarks));
      return true;
    }
    return false;
  }
  // Try to start a node of the given type, adjusting the context when
  // necessary.
  enter(type, attrs, marks, preserveWS) {
    let innerMarks = this.findPlace(type.create(attrs), marks, false);
    if (innerMarks)
      innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);
    return innerMarks;
  }
  // Open a node of the given type
  enterInner(type, attrs, marks, solid = false, preserveWS) {
    this.closeExtra();
    let top2 = this.top;
    top2.match = top2.match && top2.match.matchType(type);
    let options = wsOptionsFor(type, preserveWS, top2.options);
    if (top2.options & OPT_OPEN_LEFT && top2.content.length == 0)
      options |= OPT_OPEN_LEFT;
    let applyMarks = Mark.none;
    marks = marks.filter((m) => {
      if (top2.type ? top2.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {
        applyMarks = m.addToSet(applyMarks);
        return false;
      }
      return true;
    });
    this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));
    this.open++;
    return marks;
  }
  // Make sure all nodes above this.open are finished and added to
  // their parents
  closeExtra(openEnd = false) {
    let i = this.nodes.length - 1;
    if (i > this.open) {
      for (; i > this.open; i--)
        this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));
      this.nodes.length = this.open + 1;
    }
  }
  finish() {
    this.open = 0;
    this.closeExtra(this.isOpen);
    return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
  }
  sync(to) {
    for (let i = this.open; i >= 0; i--) {
      if (this.nodes[i] == to) {
        this.open = i;
        return true;
      } else if (this.localPreserveWS) {
        this.nodes[i].options |= OPT_PRESERVE_WS;
      }
    }
    return false;
  }
  get currentPos() {
    this.closeExtra();
    let pos = 0;
    for (let i = this.open; i >= 0; i--) {
      let content = this.nodes[i].content;
      for (let j = content.length - 1; j >= 0; j--)
        pos += content[j].nodeSize;
      if (i)
        pos++;
    }
    return pos;
  }
  findAtPoint(parent, offset) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].node == parent && this.find[i].offset == offset)
          this.find[i].pos = this.currentPos;
      }
  }
  findInside(parent) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))
          this.find[i].pos = this.currentPos;
      }
  }
  findAround(parent, content, before) {
    if (parent != content && this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {
          let pos = content.compareDocumentPosition(this.find[i].node);
          if (pos & (before ? 2 : 4))
            this.find[i].pos = this.currentPos;
        }
      }
  }
  findInText(textNode) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].node == textNode)
          this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);
      }
  }
  // Determines whether the given context string matches this context.
  matchesContext(context) {
    if (context.indexOf("|") > -1)
      return context.split(/\s*\|\s*/).some(this.matchesContext, this);
    let parts = context.split("/");
    let option = this.options.context;
    let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
    let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
    let match = (i, depth) => {
      for (; i >= 0; i--) {
        let part2 = parts[i];
        if (part2 == "") {
          if (i == parts.length - 1 || i == 0)
            continue;
          for (; depth >= minDepth; depth--)
            if (match(i - 1, depth))
              return true;
          return false;
        } else {
          let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;
          if (!next || next.name != part2 && !next.isInGroup(part2))
            return false;
          depth--;
        }
      }
      return true;
    };
    return match(parts.length - 1, this.open);
  }
  textblockFromContext() {
    let $context = this.options.context;
    if ($context)
      for (let d = $context.depth; d >= 0; d--) {
        let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;
        if (deflt && deflt.isTextblock && deflt.defaultAttrs)
          return deflt;
      }
    for (let name in this.parser.schema.nodes) {
      let type = this.parser.schema.nodes[name];
      if (type.isTextblock && type.defaultAttrs)
        return type;
    }
  }
};
function normalizeList(dom) {
  for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
    let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
    if (name && listTags.hasOwnProperty(name) && prevItem) {
      prevItem.appendChild(child);
      child = prevItem;
    } else if (name == "li") {
      prevItem = child;
    } else if (name) {
      prevItem = null;
    }
  }
}
function matches(dom, selector) {
  return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
}
function copy(obj) {
  let copy3 = {};
  for (let prop2 in obj)
    copy3[prop2] = obj[prop2];
  return copy3;
}
function markMayApply(markType, nodeType) {
  let nodes = nodeType.schema.nodes;
  for (let name in nodes) {
    let parent = nodes[name];
    if (!parent.allowsMarkType(markType))
      continue;
    let seen = [], scan = (match) => {
      seen.push(match);
      for (let i = 0; i < match.edgeCount; i++) {
        let { type, next } = match.edge(i);
        if (type == nodeType)
          return true;
        if (seen.indexOf(next) < 0 && scan(next))
          return true;
      }
    };
    if (scan(parent.contentMatch))
      return true;
  }
}
var DOMSerializer = class _DOMSerializer {
  /**
  Create a serializer. `nodes` should map node names to functions
  that take a node and return a description of the corresponding
  DOM. `marks` does the same for mark names, but also gets an
  argument that tells it whether the mark's content is block or
  inline content (for typical use, it'll always be inline). A mark
  serializer may be `null` to indicate that marks of that type
  should not be serialized.
  */
  constructor(nodes, marks) {
    this.nodes = nodes;
    this.marks = marks;
  }
  /**
  Serialize the content of this fragment to a DOM fragment. When
  not in the browser, the `document` option, containing a DOM
  document, should be passed so that the serializer can create
  nodes.
  */
  serializeFragment(fragment, options = {}, target2) {
    if (!target2)
      target2 = doc(options).createDocumentFragment();
    let top2 = target2, active = [];
    fragment.forEach((node) => {
      if (active.length || node.marks.length) {
        let keep = 0, rendered = 0;
        while (keep < active.length && rendered < node.marks.length) {
          let next = node.marks[rendered];
          if (!this.marks[next.type.name]) {
            rendered++;
            continue;
          }
          if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
            break;
          keep++;
          rendered++;
        }
        while (keep < active.length)
          top2 = active.pop()[1];
        while (rendered < node.marks.length) {
          let add = node.marks[rendered++];
          let markDOM = this.serializeMark(add, node.isInline, options);
          if (markDOM) {
            active.push([add, top2]);
            top2.appendChild(markDOM.dom);
            top2 = markDOM.contentDOM || markDOM.dom;
          }
        }
      }
      top2.appendChild(this.serializeNodeInner(node, options));
    });
    return target2;
  }
  /**
  @internal
  */
  serializeNodeInner(node, options) {
    let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);
    if (contentDOM) {
      if (node.isLeaf)
        throw new RangeError("Content hole not allowed in a leaf node spec");
      this.serializeFragment(node.content, options, contentDOM);
    }
    return dom;
  }
  /**
  Serialize this node to a DOM node. This can be useful when you
  need to serialize a part of a document, as opposed to the whole
  document. To serialize a whole document, use
  [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
  its [content](https://prosemirror.net/docs/ref/#model.Node.content).
  */
  serializeNode(node, options = {}) {
    let dom = this.serializeNodeInner(node, options);
    for (let i = node.marks.length - 1; i >= 0; i--) {
      let wrap2 = this.serializeMark(node.marks[i], node.isInline, options);
      if (wrap2) {
        (wrap2.contentDOM || wrap2.dom).appendChild(dom);
        dom = wrap2.dom;
      }
    }
    return dom;
  }
  /**
  @internal
  */
  serializeMark(mark, inline, options = {}) {
    let toDOM = this.marks[mark.type.name];
    return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);
  }
  static renderSpec(doc3, structure, xmlNS = null, blockArraysIn) {
    return renderSpec(doc3, structure, xmlNS, blockArraysIn);
  }
  /**
  Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
  properties in a schema's node and mark specs.
  */
  static fromSchema(schema) {
    return schema.cached.domSerializer || (schema.cached.domSerializer = new _DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));
  }
  /**
  Gather the serializers in a schema's node specs into an object.
  This can be useful as a base to build a custom serializer from.
  */
  static nodesFromSchema(schema) {
    let result = gatherToDOM(schema.nodes);
    if (!result.text)
      result.text = (node) => node.text;
    return result;
  }
  /**
  Gather the serializers in a schema's mark specs into an object.
  */
  static marksFromSchema(schema) {
    return gatherToDOM(schema.marks);
  }
};
function gatherToDOM(obj) {
  let result = {};
  for (let name in obj) {
    let toDOM = obj[name].spec.toDOM;
    if (toDOM)
      result[name] = toDOM;
  }
  return result;
}
function doc(options) {
  return options.document || window.document;
}
var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
function suspiciousAttributes(attrs) {
  let value = suspiciousAttributeCache.get(attrs);
  if (value === void 0)
    suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));
  return value;
}
function suspiciousAttributesInner(attrs) {
  let result = null;
  function scan(value) {
    if (value && typeof value == "object") {
      if (Array.isArray(value)) {
        if (typeof value[0] == "string") {
          if (!result)
            result = [];
          result.push(value);
        } else {
          for (let i = 0; i < value.length; i++)
            scan(value[i]);
        }
      } else {
        for (let prop2 in value)
          scan(value[prop2]);
      }
    }
  }
  scan(attrs);
  return result;
}
function renderSpec(doc3, structure, xmlNS, blockArraysIn) {
  if (typeof structure == "string")
    return { dom: doc3.createTextNode(structure) };
  if (structure.nodeType != null)
    return { dom: structure };
  if (structure.dom && structure.dom.nodeType != null)
    return structure;
  let tagName = structure[0], suspicious;
  if (typeof tagName != "string")
    throw new RangeError("Invalid array passed to renderSpec");
  if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
    throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
  let space = tagName.indexOf(" ");
  if (space > 0) {
    xmlNS = tagName.slice(0, space);
    tagName = tagName.slice(space + 1);
  }
  let contentDOM;
  let dom = xmlNS ? doc3.createElementNS(xmlNS, tagName) : doc3.createElement(tagName);
  let attrs = structure[1], start = 1;
  if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
    start = 2;
    for (let name in attrs)
      if (attrs[name] != null) {
        let space2 = name.indexOf(" ");
        if (space2 > 0)
          dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs[name]);
        else if (name == "style" && dom.style)
          dom.style.cssText = attrs[name];
        else
          dom.setAttribute(name, attrs[name]);
      }
  }
  for (let i = start; i < structure.length; i++) {
    let child = structure[i];
    if (child === 0) {
      if (i < structure.length - 1 || i > start)
        throw new RangeError("Content hole must be the only child of its parent node");
      return { dom, contentDOM: dom };
    } else {
      let { dom: inner, contentDOM: innerContent } = renderSpec(doc3, child, xmlNS, blockArraysIn);
      dom.appendChild(inner);
      if (innerContent) {
        if (contentDOM)
          throw new RangeError("Multiple content holes");
        contentDOM = innerContent;
      }
    }
  }
  return { dom, contentDOM };
}

// node_modules/prosemirror-transform/dist/index.js
var lower16 = 65535;
var factor16 = Math.pow(2, 16);
function makeRecover(index2, offset) {
  return index2 + offset * factor16;
}
function recoverIndex(value) {
  return value & lower16;
}
function recoverOffset(value) {
  return (value - (value & lower16)) / factor16;
}
var DEL_BEFORE = 1;
var DEL_AFTER = 2;
var DEL_ACROSS = 4;
var DEL_SIDE = 8;
var MapResult = class {
  /**
  @internal
  */
  constructor(pos, delInfo, recover) {
    this.pos = pos;
    this.delInfo = delInfo;
    this.recover = recover;
  }
  /**
  Tells you whether the position was deleted, that is, whether the
  step removed the token on the side queried (via the `assoc`)
  argument from the document.
  */
  get deleted() {
    return (this.delInfo & DEL_SIDE) > 0;
  }
  /**
  Tells you whether the token before the mapped position was deleted.
  */
  get deletedBefore() {
    return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;
  }
  /**
  True when the token after the mapped position was deleted.
  */
  get deletedAfter() {
    return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;
  }
  /**
  Tells whether any of the steps mapped through deletes across the
  position (including both the token before and after the
  position).
  */
  get deletedAcross() {
    return (this.delInfo & DEL_ACROSS) > 0;
  }
};
var StepMap = class _StepMap {
  /**
  Create a position map. The modifications to the document are
  represented as an array of numbers, in which each group of three
  represents a modified chunk as `[start, oldSize, newSize]`.
  */
  constructor(ranges, inverted = false) {
    this.ranges = ranges;
    this.inverted = inverted;
    if (!ranges.length && _StepMap.empty)
      return _StepMap.empty;
  }
  /**
  @internal
  */
  recover(value) {
    let diff2 = 0, index2 = recoverIndex(value);
    if (!this.inverted)
      for (let i = 0; i < index2; i++)
        diff2 += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
    return this.ranges[index2 * 3] + diff2 + recoverOffset(value);
  }
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  map(pos, assoc = 1) {
    return this._map(pos, assoc, true);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let diff2 = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0; i < this.ranges.length; i += 3) {
      let start = this.ranges[i] - (this.inverted ? diff2 : 0);
      if (start > pos)
        break;
      let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;
      if (pos <= end) {
        let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
        let result = start + diff2 + (side < 0 ? 0 : newSize);
        if (simple)
          return result;
        let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);
        let del2 = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
        if (assoc < 0 ? pos != start : pos != end)
          del2 |= DEL_SIDE;
        return new MapResult(result, del2, recover);
      }
      diff2 += newSize - oldSize;
    }
    return simple ? pos + diff2 : new MapResult(pos + diff2, 0, null);
  }
  /**
  @internal
  */
  touches(pos, recover) {
    let diff2 = 0, index2 = recoverIndex(recover);
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0; i < this.ranges.length; i += 3) {
      let start = this.ranges[i] - (this.inverted ? diff2 : 0);
      if (start > pos)
        break;
      let oldSize = this.ranges[i + oldIndex], end = start + oldSize;
      if (pos <= end && i == index2 * 3)
        return true;
      diff2 += this.ranges[i + newIndex] - oldSize;
    }
    return false;
  }
  /**
  Calls the given function on each of the changed ranges included in
  this map.
  */
  forEach(f) {
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0, diff2 = 0; i < this.ranges.length; i += 3) {
      let start = this.ranges[i], oldStart = start - (this.inverted ? diff2 : 0), newStart = start + (this.inverted ? 0 : diff2);
      let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];
      f(oldStart, oldStart + oldSize, newStart, newStart + newSize);
      diff2 += newSize - oldSize;
    }
  }
  /**
  Create an inverted version of this map. The result can be used to
  map positions in the post-step document to the pre-step document.
  */
  invert() {
    return new _StepMap(this.ranges, !this.inverted);
  }
  /**
  @internal
  */
  toString() {
    return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
  }
  /**
  Create a map that moves all positions by offset `n` (which may be
  negative). This can be useful when applying steps meant for a
  sub-document to a larger document, or vice-versa.
  */
  static offset(n) {
    return n == 0 ? _StepMap.empty : new _StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
  }
};
StepMap.empty = new StepMap([]);
var Mapping = class _Mapping {
  /**
  Create a new mapping with the given position maps.
  */
  constructor(maps, mirror, from2 = 0, to = maps ? maps.length : 0) {
    this.mirror = mirror;
    this.from = from2;
    this.to = to;
    this._maps = maps || [];
    this.ownData = !(maps || mirror);
  }
  /**
  The step maps in this mapping.
  */
  get maps() {
    return this._maps;
  }
  /**
  Create a mapping that maps only through a part of this one.
  */
  slice(from2 = 0, to = this.maps.length) {
    return new _Mapping(this._maps, this.mirror, from2, to);
  }
  /**
  Add a step map to the end of this mapping. If `mirrors` is
  given, it should be the index of the step map that is the mirror
  image of this one.
  */
  appendMap(map3, mirrors) {
    if (!this.ownData) {
      this._maps = this._maps.slice();
      this.mirror = this.mirror && this.mirror.slice();
      this.ownData = true;
    }
    this.to = this._maps.push(map3);
    if (mirrors != null)
      this.setMirror(this._maps.length - 1, mirrors);
  }
  /**
  Add all the step maps in a given mapping to this one (preserving
  mirroring information).
  */
  appendMapping(mapping) {
    for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {
      let mirr = mapping.getMirror(i);
      this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : void 0);
    }
  }
  /**
  Finds the offset of the step map that mirrors the map at the
  given offset, in this mapping (as per the second argument to
  `appendMap`).
  */
  getMirror(n) {
    if (this.mirror) {
      for (let i = 0; i < this.mirror.length; i++)
        if (this.mirror[i] == n)
          return this.mirror[i + (i % 2 ? -1 : 1)];
    }
  }
  /**
  @internal
  */
  setMirror(n, m) {
    if (!this.mirror)
      this.mirror = [];
    this.mirror.push(n, m);
  }
  /**
  Append the inverse of the given mapping to this one.
  */
  appendMappingInverted(mapping) {
    for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {
      let mirr = mapping.getMirror(i);
      this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0);
    }
  }
  /**
  Create an inverted version of this mapping.
  */
  invert() {
    let inverse = new _Mapping();
    inverse.appendMappingInverted(this);
    return inverse;
  }
  /**
  Map a position through this mapping.
  */
  map(pos, assoc = 1) {
    if (this.mirror)
      return this._map(pos, assoc, true);
    for (let i = this.from; i < this.to; i++)
      pos = this._maps[i].map(pos, assoc);
    return pos;
  }
  /**
  Map a position through this mapping, returning a mapping
  result.
  */
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let delInfo = 0;
    for (let i = this.from; i < this.to; i++) {
      let map3 = this._maps[i], result = map3.mapResult(pos, assoc);
      if (result.recover != null) {
        let corr = this.getMirror(i);
        if (corr != null && corr > i && corr < this.to) {
          i = corr;
          pos = this._maps[corr].recover(result.recover);
          continue;
        }
      }
      delInfo |= result.delInfo;
      pos = result.pos;
    }
    return simple ? pos : new MapResult(pos, delInfo, null);
  }
};
var stepsByID = /* @__PURE__ */ Object.create(null);
var Step = class {
  /**
  Get the step map that represents the changes made by this step,
  and which can be used to transform between positions in the old
  and the new document.
  */
  getMap() {
    return StepMap.empty;
  }
  /**
  Try to merge this step with another one, to be applied directly
  after it. Returns the merged step when possible, null if the
  steps can't be merged.
  */
  merge(other) {
    return null;
  }
  /**
  Deserialize a step from its JSON representation. Will call
  through to the step class' own implementation of this method.
  */
  static fromJSON(schema, json) {
    if (!json || !json.stepType)
      throw new RangeError("Invalid input for Step.fromJSON");
    let type = stepsByID[json.stepType];
    if (!type)
      throw new RangeError(`No step type ${json.stepType} defined`);
    return type.fromJSON(schema, json);
  }
  /**
  To be able to serialize steps to JSON, each step needs a string
  ID to attach to its JSON representation. Use this method to
  register an ID for your step classes. Try to pick something
  that's unlikely to clash with steps from other modules.
  */
  static jsonID(id, stepClass) {
    if (id in stepsByID)
      throw new RangeError("Duplicate use of step JSON ID " + id);
    stepsByID[id] = stepClass;
    stepClass.prototype.jsonID = id;
    return stepClass;
  }
};
var StepResult = class _StepResult {
  /**
  @internal
  */
  constructor(doc3, failed) {
    this.doc = doc3;
    this.failed = failed;
  }
  /**
  Create a successful step result.
  */
  static ok(doc3) {
    return new _StepResult(doc3, null);
  }
  /**
  Create a failed step result.
  */
  static fail(message) {
    return new _StepResult(null, message);
  }
  /**
  Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
  arguments. Create a successful result if it succeeds, and a
  failed one if it throws a `ReplaceError`.
  */
  static fromReplace(doc3, from2, to, slice2) {
    try {
      return _StepResult.ok(doc3.replace(from2, to, slice2));
    } catch (e) {
      if (e instanceof ReplaceError)
        return _StepResult.fail(e.message);
      throw e;
    }
  }
};
function mapFragment(fragment, f, parent) {
  let mapped = [];
  for (let i = 0; i < fragment.childCount; i++) {
    let child = fragment.child(i);
    if (child.content.size)
      child = child.copy(mapFragment(child.content, f, child));
    if (child.isInline)
      child = f(child, parent, i);
    mapped.push(child);
  }
  return Fragment.fromArray(mapped);
}
var AddMarkStep = class _AddMarkStep extends Step {
  /**
  Create a mark step.
  */
  constructor(from2, to, mark) {
    super();
    this.from = from2;
    this.to = to;
    this.mark = mark;
  }
  apply(doc3) {
    let oldSlice = doc3.slice(this.from, this.to), $from = doc3.resolve(this.from);
    let parent = $from.node($from.sharedDepth(this.to));
    let slice2 = new Slice(mapFragment(oldSlice.content, (node, parent2) => {
      if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type))
        return node;
      return node.mark(this.mark.addToSet(node.marks));
    }, parent), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc3, this.from, this.to, slice2);
  }
  invert() {
    return new RemoveMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deleted && to.deleted || from2.pos >= to.pos)
      return null;
    return new _AddMarkStep(from2.pos, to.pos, this.mark);
  }
  merge(other) {
    if (other instanceof _AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new _AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    return new _AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("addMark", AddMarkStep);
var RemoveMarkStep = class _RemoveMarkStep extends Step {
  /**
  Create a mark-removing step.
  */
  constructor(from2, to, mark) {
    super();
    this.from = from2;
    this.to = to;
    this.mark = mark;
  }
  apply(doc3) {
    let oldSlice = doc3.slice(this.from, this.to);
    let slice2 = new Slice(mapFragment(oldSlice.content, (node) => {
      return node.mark(this.mark.removeFromSet(node.marks));
    }, doc3), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc3, this.from, this.to, slice2);
  }
  invert() {
    return new AddMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deleted && to.deleted || from2.pos >= to.pos)
      return null;
    return new _RemoveMarkStep(from2.pos, to.pos, this.mark);
  }
  merge(other) {
    if (other instanceof _RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new _RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    return new _RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("removeMark", RemoveMarkStep);
var AddNodeMarkStep = class _AddNodeMarkStep extends Step {
  /**
  Create a node mark step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at mark step's position");
    let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));
    return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  invert(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (node) {
      let newSet = this.mark.addToSet(node.marks);
      if (newSet.length == node.marks.length) {
        for (let i = 0; i < node.marks.length; i++)
          if (!node.marks[i].isInSet(newSet))
            return new _AddNodeMarkStep(this.pos, node.marks[i]);
        return new _AddNodeMarkStep(this.pos, this.mark);
      }
    }
    return new RemoveNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _AddNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
    return new _AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("addNodeMark", AddNodeMarkStep);
var RemoveNodeMarkStep = class _RemoveNodeMarkStep extends Step {
  /**
  Create a mark-removing step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at mark step's position");
    let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));
    return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  invert(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node || !this.mark.isInSet(node.marks))
      return this;
    return new AddNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _RemoveNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
    return new _RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
var ReplaceStep = class _ReplaceStep extends Step {
  /**
  The given `slice` should fit the 'gap' between `from` and
  `to`—the depths must line up, and the surrounding nodes must be
  able to be joined with the open sides of the slice. When
  `structure` is true, the step will fail if the content between
  from and to is not just a sequence of closing and then opening
  tokens (this is to guard against rebased replace steps
  overwriting something they weren't supposed to).
  */
  constructor(from2, to, slice2, structure = false) {
    super();
    this.from = from2;
    this.to = to;
    this.slice = slice2;
    this.structure = structure;
  }
  apply(doc3) {
    if (this.structure && contentBetween(doc3, this.from, this.to))
      return StepResult.fail("Structure replace would overwrite content");
    return StepResult.fromReplace(doc3, this.from, this.to, this.slice);
  }
  getMap() {
    return new StepMap([this.from, this.to - this.from, this.slice.size]);
  }
  invert(doc3) {
    return new _ReplaceStep(this.from, this.from + this.slice.size, doc3.slice(this.from, this.to));
  }
  map(mapping) {
    let to = mapping.mapResult(this.to, -1);
    let from2 = this.from == this.to && _ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1);
    if (from2.deletedAcross && to.deletedAcross)
      return null;
    return new _ReplaceStep(from2.pos, Math.max(from2.pos, to.pos), this.slice, this.structure);
  }
  merge(other) {
    if (!(other instanceof _ReplaceStep) || other.structure || this.structure)
      return null;
    if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
      return new _ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure);
    } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
      return new _ReplaceStep(other.from, this.to, slice2, this.structure);
    } else {
      return null;
    }
  }
  toJSON() {
    let json = { stepType: "replace", from: this.from, to: this.to };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    return new _ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);
  }
};
ReplaceStep.MAP_BIAS = 1;
Step.jsonID("replace", ReplaceStep);
var ReplaceAroundStep = class _ReplaceAroundStep extends Step {
  /**
  Create a replace-around step with the given range and gap.
  `insert` should be the point in the slice into which the content
  of the gap should be moved. `structure` has the same meaning as
  it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
  */
  constructor(from2, to, gapFrom, gapTo, slice2, insert, structure = false) {
    super();
    this.from = from2;
    this.to = to;
    this.gapFrom = gapFrom;
    this.gapTo = gapTo;
    this.slice = slice2;
    this.insert = insert;
    this.structure = structure;
  }
  apply(doc3) {
    if (this.structure && (contentBetween(doc3, this.from, this.gapFrom) || contentBetween(doc3, this.gapTo, this.to)))
      return StepResult.fail("Structure gap-replace would overwrite content");
    let gap2 = doc3.slice(this.gapFrom, this.gapTo);
    if (gap2.openStart || gap2.openEnd)
      return StepResult.fail("Gap is not a flat range");
    let inserted = this.slice.insertAt(this.insert, gap2.content);
    if (!inserted)
      return StepResult.fail("Content does not fit in gap");
    return StepResult.fromReplace(doc3, this.from, this.to, inserted);
  }
  getMap() {
    return new StepMap([
      this.from,
      this.gapFrom - this.from,
      this.insert,
      this.gapTo,
      this.to - this.gapTo,
      this.slice.size - this.insert
    ]);
  }
  invert(doc3) {
    let gap2 = this.gapTo - this.gapFrom;
    return new _ReplaceAroundStep(this.from, this.from + this.slice.size + gap2, this.from + this.insert, this.from + this.insert + gap2, doc3.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    let gapFrom = this.from == this.gapFrom ? from2.pos : mapping.map(this.gapFrom, -1);
    let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);
    if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos)
      return null;
    return new _ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  }
  toJSON() {
    let json = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    return new _ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
  }
};
Step.jsonID("replaceAround", ReplaceAroundStep);
function contentBetween(doc3, from2, to) {
  let $from = doc3.resolve(from2), dist = to - from2, depth = $from.depth;
  while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
    depth--;
    dist--;
  }
  if (dist > 0) {
    let next = $from.node(depth).maybeChild($from.indexAfter(depth));
    while (dist > 0) {
      if (!next || next.isLeaf)
        return true;
      next = next.firstChild;
      dist--;
    }
  }
  return false;
}
function addMark(tr, from2, to, mark) {
  let removed = [], added = [];
  let removing, adding;
  tr.doc.nodesBetween(from2, to, (node, pos, parent) => {
    if (!node.isInline)
      return;
    let marks = node.marks;
    if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {
      let start = Math.max(pos, from2), end = Math.min(pos + node.nodeSize, to);
      let newSet = mark.addToSet(marks);
      for (let i = 0; i < marks.length; i++) {
        if (!marks[i].isInSet(newSet)) {
          if (removing && removing.to == start && removing.mark.eq(marks[i]))
            removing.to = end;
          else
            removed.push(removing = new RemoveMarkStep(start, end, marks[i]));
        }
      }
      if (adding && adding.to == start)
        adding.to = end;
      else
        added.push(adding = new AddMarkStep(start, end, mark));
    }
  });
  removed.forEach((s) => tr.step(s));
  added.forEach((s) => tr.step(s));
}
function removeMark(tr, from2, to, mark) {
  let matched = [], step = 0;
  tr.doc.nodesBetween(from2, to, (node, pos) => {
    if (!node.isInline)
      return;
    step++;
    let toRemove = null;
    if (mark instanceof MarkType) {
      let set = node.marks, found2;
      while (found2 = mark.isInSet(set)) {
        (toRemove || (toRemove = [])).push(found2);
        set = found2.removeFromSet(set);
      }
    } else if (mark) {
      if (mark.isInSet(node.marks))
        toRemove = [mark];
    } else {
      toRemove = node.marks;
    }
    if (toRemove && toRemove.length) {
      let end = Math.min(pos + node.nodeSize, to);
      for (let i = 0; i < toRemove.length; i++) {
        let style = toRemove[i], found2;
        for (let j = 0; j < matched.length; j++) {
          let m = matched[j];
          if (m.step == step - 1 && style.eq(matched[j].style))
            found2 = m;
        }
        if (found2) {
          found2.to = end;
          found2.step = step;
        } else {
          matched.push({ style, from: Math.max(pos, from2), to: end, step });
        }
      }
    }
  });
  matched.forEach((m) => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));
}
function clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {
  let node = tr.doc.nodeAt(pos);
  let replSteps = [], cur = pos + 1;
  for (let i = 0; i < node.childCount; i++) {
    let child = node.child(i), end = cur + child.nodeSize;
    let allowed = match.matchType(child.type);
    if (!allowed) {
      replSteps.push(new ReplaceStep(cur, end, Slice.empty));
    } else {
      match = allowed;
      for (let j = 0; j < child.marks.length; j++)
        if (!parentType.allowsMarkType(child.marks[j].type))
          tr.step(new RemoveMarkStep(cur, end, child.marks[j]));
      if (clearNewlines && child.isText && parentType.whitespace != "pre") {
        let m, newline = /\r?\n|\r/g, slice2;
        while (m = newline.exec(child.text)) {
          if (!slice2)
            slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0);
          replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice2));
        }
      }
    }
    cur = end;
  }
  if (!match.validEnd) {
    let fill = match.fillBefore(Fragment.empty, true);
    tr.replace(cur, cur, new Slice(fill, 0, 0));
  }
  for (let i = replSteps.length - 1; i >= 0; i--)
    tr.step(replSteps[i]);
}
function canCut(node, start, end) {
  return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end));
}
function liftTarget(range2) {
  let parent = range2.parent;
  let content = parent.content.cutByIndex(range2.startIndex, range2.endIndex);
  for (let depth = range2.depth, contentBefore = 0, contentAfter = 0; ; --depth) {
    let node = range2.$from.node(depth);
    let index2 = range2.$from.index(depth) + contentBefore, endIndex = range2.$to.indexAfter(depth) - contentAfter;
    if (depth < range2.depth && node.canReplace(index2, endIndex, content))
      return depth;
    if (depth == 0 || node.type.spec.isolating || !canCut(node, index2, endIndex))
      break;
    if (index2)
      contentBefore = 1;
    if (endIndex < node.childCount)
      contentAfter = 1;
  }
  return null;
}
function lift(tr, range2, target2) {
  let { $from, $to, depth } = range2;
  let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
  let start = gapStart, end = gapEnd;
  let before = Fragment.empty, openStart = 0;
  for (let d = depth, splitting = false; d > target2; d--)
    if (splitting || $from.index(d) > 0) {
      splitting = true;
      before = Fragment.from($from.node(d).copy(before));
      openStart++;
    } else {
      start--;
    }
  let after = Fragment.empty, openEnd = 0;
  for (let d = depth, splitting = false; d > target2; d--)
    if (splitting || $to.after(d + 1) < $to.end(d)) {
      splitting = true;
      after = Fragment.from($to.node(d).copy(after));
      openEnd++;
    } else {
      end++;
    }
  tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
}
function findWrapping(range2, nodeType, attrs = null, innerRange = range2) {
  let around = findWrappingOutside(range2, nodeType);
  let inner = around && findWrappingInside(innerRange, nodeType);
  if (!inner)
    return null;
  return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));
}
function withAttrs(type) {
  return { type, attrs: null };
}
function findWrappingOutside(range2, type) {
  let { parent, startIndex, endIndex } = range2;
  let around = parent.contentMatchAt(startIndex).findWrapping(type);
  if (!around)
    return null;
  let outer = around.length ? around[0] : type;
  return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
}
function findWrappingInside(range2, type) {
  let { parent, startIndex, endIndex } = range2;
  let inner = parent.child(startIndex);
  let inside = type.contentMatch.findWrapping(inner.type);
  if (!inside)
    return null;
  let lastType = inside.length ? inside[inside.length - 1] : type;
  let innerMatch = lastType.contentMatch;
  for (let i = startIndex; innerMatch && i < endIndex; i++)
    innerMatch = innerMatch.matchType(parent.child(i).type);
  if (!innerMatch || !innerMatch.validEnd)
    return null;
  return inside;
}
function wrap(tr, range2, wrappers) {
  let content = Fragment.empty;
  for (let i = wrappers.length - 1; i >= 0; i--) {
    if (content.size) {
      let match = wrappers[i].type.contentMatch.matchFragment(content);
      if (!match || !match.validEnd)
        throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
    }
    content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  }
  let start = range2.start, end = range2.end;
  tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));
}
function setBlockType(tr, from2, to, type, attrs) {
  if (!type.isTextblock)
    throw new RangeError("Type given to setBlockType should be a textblock");
  let mapFrom = tr.steps.length;
  tr.doc.nodesBetween(from2, to, (node, pos) => {
    let attrsHere = typeof attrs == "function" ? attrs(node) : attrs;
    if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {
      let convertNewlines = null;
      if (type.schema.linebreakReplacement) {
        let pre2 = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);
        if (pre2 && !supportLinebreak)
          convertNewlines = false;
        else if (!pre2 && supportLinebreak)
          convertNewlines = true;
      }
      if (convertNewlines === false)
        replaceLinebreaks(tr, node, pos, mapFrom);
      clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null);
      let mapping = tr.mapping.slice(mapFrom);
      let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);
      tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));
      if (convertNewlines === true)
        replaceNewlines(tr, node, pos, mapFrom);
      return false;
    }
  });
}
function replaceNewlines(tr, node, pos, mapFrom) {
  node.forEach((child, offset) => {
    if (child.isText) {
      let m, newline = /\r?\n|\r/g;
      while (m = newline.exec(child.text)) {
        let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);
        tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());
      }
    }
  });
}
function replaceLinebreaks(tr, node, pos, mapFrom) {
  node.forEach((child, offset) => {
    if (child.type == child.type.schema.linebreakReplacement) {
      let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);
      tr.replaceWith(start, start + 1, node.type.schema.text("\n"));
    }
  });
}
function canChangeType(doc3, pos, type) {
  let $pos = doc3.resolve(pos), index2 = $pos.index();
  return $pos.parent.canReplaceWith(index2, index2 + 1, type);
}
function setNodeMarkup(tr, pos, type, attrs, marks) {
  let node = tr.doc.nodeAt(pos);
  if (!node)
    throw new RangeError("No node at given position");
  if (!type)
    type = node.type;
  let newNode = type.create(attrs, null, marks || node.marks);
  if (node.isLeaf)
    return tr.replaceWith(pos, pos + node.nodeSize, newNode);
  if (!type.validContent(node.content))
    throw new RangeError("Invalid content for node type " + type.name);
  tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
}
function canSplit(doc3, pos, depth = 1, typesAfter) {
  let $pos = doc3.resolve(pos), base2 = $pos.depth - depth;
  let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;
  if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
    return false;
  for (let d = $pos.depth - 1, i = depth - 2; d > base2; d--, i--) {
    let node = $pos.node(d), index3 = $pos.index(d);
    if (node.type.spec.isolating)
      return false;
    let rest = node.content.cutByIndex(index3, node.childCount);
    let overrideChild = typesAfter && typesAfter[i + 1];
    if (overrideChild)
      rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
    let after = typesAfter && typesAfter[i] || node;
    if (!node.canReplace(index3 + 1, node.childCount) || !after.type.validContent(rest))
      return false;
  }
  let index2 = $pos.indexAfter(base2);
  let baseType = typesAfter && typesAfter[0];
  return $pos.node(base2).canReplaceWith(index2, index2, baseType ? baseType.type : $pos.node(base2 + 1).type);
}
function split(tr, pos, depth = 1, typesAfter) {
  let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
  for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {
    before = Fragment.from($pos.node(d).copy(before));
    let typeAfter = typesAfter && typesAfter[i];
    after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));
  }
  tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
}
function canJoin(doc3, pos) {
  let $pos = doc3.resolve(pos), index2 = $pos.index();
  return joinable2($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index2, index2 + 1);
}
function canAppendWithSubstitutedLinebreaks(a, b) {
  if (!b.content.size)
    a.type.compatibleContent(b.type);
  let match = a.contentMatchAt(a.childCount);
  let { linebreakReplacement } = a.type.schema;
  for (let i = 0; i < b.childCount; i++) {
    let child = b.child(i);
    let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;
    match = match.matchType(type);
    if (!match)
      return false;
    if (!a.type.allowsMarks(child.marks))
      return false;
  }
  return match.validEnd;
}
function joinable2(a, b) {
  return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));
}
function join(tr, pos, depth) {
  let convertNewlines = null;
  let { linebreakReplacement } = tr.doc.type.schema;
  let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;
  if (linebreakReplacement && beforeType.inlineContent) {
    let pre2 = beforeType.whitespace == "pre";
    let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);
    if (pre2 && !supportLinebreak)
      convertNewlines = false;
    else if (!pre2 && supportLinebreak)
      convertNewlines = true;
  }
  let mapFrom = tr.steps.length;
  if (convertNewlines === false) {
    let $after = tr.doc.resolve(pos + depth);
    replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);
  }
  if (beforeType.inlineContent)
    clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);
  let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);
  tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));
  if (convertNewlines === true) {
    let $full = tr.doc.resolve(start);
    replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);
  }
  return tr;
}
function insertPoint(doc3, pos, nodeType) {
  let $pos = doc3.resolve(pos);
  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
    return pos;
  if ($pos.parentOffset == 0)
    for (let d = $pos.depth - 1; d >= 0; d--) {
      let index2 = $pos.index(d);
      if ($pos.node(d).canReplaceWith(index2, index2, nodeType))
        return $pos.before(d + 1);
      if (index2 > 0)
        return null;
    }
  if ($pos.parentOffset == $pos.parent.content.size)
    for (let d = $pos.depth - 1; d >= 0; d--) {
      let index2 = $pos.indexAfter(d);
      if ($pos.node(d).canReplaceWith(index2, index2, nodeType))
        return $pos.after(d + 1);
      if (index2 < $pos.node(d).childCount)
        return null;
    }
  return null;
}
function dropPoint(doc3, pos, slice2) {
  let $pos = doc3.resolve(pos);
  if (!slice2.content.size)
    return pos;
  let content = slice2.content;
  for (let i = 0; i < slice2.openStart; i++)
    content = content.firstChild.content;
  for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) {
    for (let d = $pos.depth; d >= 0; d--) {
      let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;
      let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);
      let parent = $pos.node(d), fits = false;
      if (pass == 1) {
        fits = parent.canReplace(insertPos, insertPos, content);
      } else {
        let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);
        fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);
      }
      if (fits)
        return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);
    }
  }
  return null;
}
function replaceStep(doc3, from2, to = from2, slice2 = Slice.empty) {
  if (from2 == to && !slice2.size)
    return null;
  let $from = doc3.resolve(from2), $to = doc3.resolve(to);
  if (fitsTrivially($from, $to, slice2))
    return new ReplaceStep(from2, to, slice2);
  return new Fitter($from, $to, slice2).fit();
}
function fitsTrivially($from, $to, slice2) {
  return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content);
}
var Fitter = class {
  constructor($from, $to, unplaced) {
    this.$from = $from;
    this.$to = $to;
    this.unplaced = unplaced;
    this.frontier = [];
    this.placed = Fragment.empty;
    for (let i = 0; i <= $from.depth; i++) {
      let node = $from.node(i);
      this.frontier.push({
        type: node.type,
        match: node.contentMatchAt($from.indexAfter(i))
      });
    }
    for (let i = $from.depth; i > 0; i--)
      this.placed = Fragment.from($from.node(i).copy(this.placed));
  }
  get depth() {
    return this.frontier.length - 1;
  }
  fit() {
    while (this.unplaced.size) {
      let fit = this.findFittable();
      if (fit)
        this.placeNodes(fit);
      else
        this.openMore() || this.dropNode();
    }
    let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
    let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
    if (!$to)
      return null;
    let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
    while (openStart && openEnd && content.childCount == 1) {
      content = content.firstChild.content;
      openStart--;
      openEnd--;
    }
    let slice2 = new Slice(content, openStart, openEnd);
    if (moveInline > -1)
      return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize);
    if (slice2.size || $from.pos != this.$to.pos)
      return new ReplaceStep($from.pos, $to.pos, slice2);
    return null;
  }
  // Find a position on the start spine of `this.unplaced` that has
  // content that can be moved somewhere on the frontier. Returns two
  // depths, one for the slice and one for the frontier.
  findFittable() {
    let startDepth = this.unplaced.openStart;
    for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {
      let node = cur.firstChild;
      if (cur.childCount > 1)
        openEnd = 0;
      if (node.type.spec.isolating && openEnd <= d) {
        startDepth = d;
        break;
      }
      cur = node.content;
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
        let fragment, parent = null;
        if (sliceDepth) {
          parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
          fragment = parent.content;
        } else {
          fragment = this.unplaced.content;
        }
        let first = fragment.firstChild;
        for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
          let { type, match } = this.frontier[frontierDepth], wrap2, inject = null;
          if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false)) : parent && type.compatibleContent(parent.type)))
            return { sliceDepth, frontierDepth, parent, inject };
          else if (pass == 2 && first && (wrap2 = match.findWrapping(first.type)))
            return { sliceDepth, frontierDepth, parent, wrap: wrap2 };
          if (parent && match.matchType(parent.type))
            break;
        }
      }
    }
  }
  openMore() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content, openStart);
    if (!inner.childCount || inner.firstChild.isLeaf)
      return false;
    this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
    return true;
  }
  dropNode() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content, openStart);
    if (inner.childCount <= 1 && openStart > 0) {
      let openAtEnd = content.size - openStart <= openStart + inner.size;
      this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
    } else {
      this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
    }
  }
  // Move content from the unplaced slice at `sliceDepth` to the
  // frontier node at `frontierDepth`. Close that frontier node when
  // applicable.
  placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) {
    while (this.depth > frontierDepth)
      this.closeFrontierNode();
    if (wrap2)
      for (let i = 0; i < wrap2.length; i++)
        this.openFrontierNode(wrap2[i]);
    let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content;
    let openStart = slice2.openStart - sliceDepth;
    let taken = 0, add = [];
    let { match, type } = this.frontier[frontierDepth];
    if (inject) {
      for (let i = 0; i < inject.childCount; i++)
        add.push(inject.child(i));
      match = match.matchFragment(inject);
    }
    let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd);
    while (taken < fragment.childCount) {
      let next = fragment.child(taken), matches3 = match.matchType(next.type);
      if (!matches3)
        break;
      taken++;
      if (taken > 1 || openStart == 0 || next.content.size) {
        match = matches3;
        add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
      }
    }
    let toEnd = taken == fragment.childCount;
    if (!toEnd)
      openEndCount = -1;
    this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));
    this.frontier[frontierDepth].match = match;
    if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)
      this.closeFrontierNode();
    for (let i = 0, cur = fragment; i < openEndCount; i++) {
      let node = cur.lastChild;
      this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });
      cur = node.content;
    }
    this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1);
  }
  mustMoveInline() {
    if (!this.$to.parent.isTextblock)
      return -1;
    let top2 = this.frontier[this.depth], level;
    if (!top2.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top2.type, top2.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)
      return -1;
    let { depth } = this.$to, after = this.$to.after(depth);
    while (depth > 1 && after == this.$to.end(--depth))
      ++after;
    return after;
  }
  findCloseLevel($to) {
    scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {
      let { match, type } = this.frontier[i];
      let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));
      let fit = contentAfterFits($to, i, type, match, dropInner);
      if (!fit)
        continue;
      for (let d = i - 1; d >= 0; d--) {
        let { match: match2, type: type2 } = this.frontier[d];
        let matches3 = contentAfterFits($to, d, type2, match2, true);
        if (!matches3 || matches3.childCount)
          continue scan;
      }
      return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };
    }
  }
  close($to) {
    let close2 = this.findCloseLevel($to);
    if (!close2)
      return null;
    while (this.depth > close2.depth)
      this.closeFrontierNode();
    if (close2.fit.childCount)
      this.placed = addToFragment(this.placed, close2.depth, close2.fit);
    $to = close2.move;
    for (let d = close2.depth + 1; d <= $to.depth; d++) {
      let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));
      this.openFrontierNode(node.type, node.attrs, add);
    }
    return $to;
  }
  openFrontierNode(type, attrs = null, content) {
    let top2 = this.frontier[this.depth];
    top2.match = top2.match.matchType(type);
    this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));
    this.frontier.push({ type, match: type.contentMatch });
  }
  closeFrontierNode() {
    let open = this.frontier.pop();
    let add = open.match.fillBefore(Fragment.empty, true);
    if (add.childCount)
      this.placed = addToFragment(this.placed, this.frontier.length, add);
  }
};
function dropFromFragment(fragment, depth, count) {
  if (depth == 0)
    return fragment.cutByIndex(count, fragment.childCount);
  return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
}
function addToFragment(fragment, depth, content) {
  if (depth == 0)
    return fragment.append(content);
  return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
}
function contentAt(fragment, depth) {
  for (let i = 0; i < depth; i++)
    fragment = fragment.firstChild.content;
  return fragment;
}
function closeNodeStart(node, openStart, openEnd) {
  if (openStart <= 0)
    return node;
  let frag = node.content;
  if (openStart > 1)
    frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  if (openStart > 0) {
    frag = node.type.contentMatch.fillBefore(frag).append(frag);
    if (openEnd <= 0)
      frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
  }
  return node.copy(frag);
}
function contentAfterFits($to, depth, type, match, open) {
  let node = $to.node(depth), index2 = open ? $to.indexAfter(depth) : $to.index(depth);
  if (index2 == node.childCount && !type.compatibleContent(node.type))
    return null;
  let fit = match.fillBefore(node.content, true, index2);
  return fit && !invalidMarks(type, node.content, index2) ? fit : null;
}
function invalidMarks(type, fragment, start) {
  for (let i = start; i < fragment.childCount; i++)
    if (!type.allowsMarks(fragment.child(i).marks))
      return true;
  return false;
}
function definesContent(type) {
  return type.spec.defining || type.spec.definingForContent;
}
function replaceRange(tr, from2, to, slice2) {
  if (!slice2.size)
    return tr.deleteRange(from2, to);
  let $from = tr.doc.resolve(from2), $to = tr.doc.resolve(to);
  if (fitsTrivially($from, $to, slice2))
    return tr.step(new ReplaceStep(from2, to, slice2));
  let targetDepths = coveredDepths($from, $to);
  if (targetDepths[targetDepths.length - 1] == 0)
    targetDepths.pop();
  let preferredTarget = -($from.depth + 1);
  targetDepths.unshift(preferredTarget);
  for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {
    let spec = $from.node(d).type.spec;
    if (spec.defining || spec.definingAsContext || spec.isolating)
      break;
    if (targetDepths.indexOf(d) > -1)
      preferredTarget = d;
    else if ($from.before(d) == pos)
      targetDepths.splice(1, 0, -d);
  }
  let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  let leftNodes = [], preferredDepth = slice2.openStart;
  for (let content = slice2.content, i = 0; ; i++) {
    let node = content.firstChild;
    leftNodes.push(node);
    if (i == slice2.openStart)
      break;
    content = node.content;
  }
  for (let d = preferredDepth - 1; d >= 0; d--) {
    let leftNode = leftNodes[d], def = definesContent(leftNode.type);
    if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))
      preferredDepth = d;
    else if (def || !leftNode.type.isTextblock)
      break;
  }
  for (let j = slice2.openStart; j >= 0; j--) {
    let openDepth = (j + preferredDepth + 1) % (slice2.openStart + 1);
    let insert = leftNodes[openDepth];
    if (!insert)
      continue;
    for (let i = 0; i < targetDepths.length; i++) {
      let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;
      if (targetDepth < 0) {
        expand = false;
        targetDepth = -targetDepth;
      }
      let parent = $from.node(targetDepth - 1), index2 = $from.index(targetDepth - 1);
      if (parent.canReplaceWith(index2, index2, insert.type, insert.marks))
        return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd));
    }
  }
  let startSteps = tr.steps.length;
  for (let i = targetDepths.length - 1; i >= 0; i--) {
    tr.replace(from2, to, slice2);
    if (tr.steps.length > startSteps)
      break;
    let depth = targetDepths[i];
    if (depth < 0)
      continue;
    from2 = $from.before(depth);
    to = $to.after(depth);
  }
}
function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
  if (depth < oldOpen) {
    let first = fragment.firstChild;
    fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));
  }
  if (depth > newOpen) {
    let match = parent.contentMatchAt(0);
    let start = match.fillBefore(fragment).append(fragment);
    fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));
  }
  return fragment;
}
function replaceRangeWith(tr, from2, to, node) {
  if (!node.isInline && from2 == to && tr.doc.resolve(from2).parent.content.size) {
    let point = insertPoint(tr.doc, from2, node.type);
    if (point != null)
      from2 = to = point;
  }
  tr.replaceRange(from2, to, new Slice(Fragment.from(node), 0, 0));
}
function deleteRange(tr, from2, to) {
  let $from = tr.doc.resolve(from2), $to = tr.doc.resolve(to);
  if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() && $from.parentOffset == 0 && $to.parentOffset == 0) {
    let shared = $from.sharedDepth(to), isolated = false;
    for (let d = $from.depth; d > shared; d--)
      if ($from.node(d).type.spec.isolating)
        isolated = true;
    for (let d = $to.depth; d > shared; d--)
      if ($to.node(d).type.spec.isolating)
        isolated = true;
    if (!isolated) {
      for (let d = $from.depth; d > 0 && from2 == $from.start(d); d--)
        from2 = $from.before(d);
      for (let d = $to.depth; d > 0 && to == $to.start(d); d--)
        to = $to.before(d);
      $from = tr.doc.resolve(from2);
      $to = tr.doc.resolve(to);
    }
  }
  let covered = coveredDepths($from, $to);
  for (let i = 0; i < covered.length; i++) {
    let depth = covered[i], last2 = i == covered.length - 1;
    if (last2 && depth == 0 || $from.node(depth).type.contentMatch.validEnd)
      return tr.delete($from.start(depth), $to.end(depth));
    if (depth > 0 && (last2 || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
      return tr.delete($from.before(depth), $to.after(depth));
  }
  for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {
    if (from2 - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))
      return tr.delete($from.before(d), to);
  }
  tr.delete(from2, to);
}
function coveredDepths($from, $to) {
  let result = [], minDepth = Math.min($from.depth, $to.depth);
  for (let d = minDepth; d >= 0; d--) {
    let start = $from.start(d);
    if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating)
      break;
    if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1)
      result.push(d);
  }
  return result;
}
var AttrStep = class _AttrStep extends Step {
  /**
  Construct an attribute step.
  */
  constructor(pos, attr, value) {
    super();
    this.pos = pos;
    this.attr = attr;
    this.value = value;
  }
  apply(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at attribute step's position");
    let attrs = /* @__PURE__ */ Object.create(null);
    for (let name in node.attrs)
      attrs[name] = node.attrs[name];
    attrs[this.attr] = this.value;
    let updated = node.type.create(attrs, null, node.marks);
    return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc3) {
    return new _AttrStep(this.pos, this.attr, doc3.nodeAt(this.pos).attrs[this.attr]);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _AttrStep(pos.pos, this.attr, this.value);
  }
  toJSON() {
    return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  }
  static fromJSON(schema, json) {
    if (typeof json.pos != "number" || typeof json.attr != "string")
      throw new RangeError("Invalid input for AttrStep.fromJSON");
    return new _AttrStep(json.pos, json.attr, json.value);
  }
};
Step.jsonID("attr", AttrStep);
var DocAttrStep = class _DocAttrStep extends Step {
  /**
  Construct an attribute step.
  */
  constructor(attr, value) {
    super();
    this.attr = attr;
    this.value = value;
  }
  apply(doc3) {
    let attrs = /* @__PURE__ */ Object.create(null);
    for (let name in doc3.attrs)
      attrs[name] = doc3.attrs[name];
    attrs[this.attr] = this.value;
    let updated = doc3.type.create(attrs, doc3.content, doc3.marks);
    return StepResult.ok(updated);
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc3) {
    return new _DocAttrStep(this.attr, doc3.attrs[this.attr]);
  }
  map(mapping) {
    return this;
  }
  toJSON() {
    return { stepType: "docAttr", attr: this.attr, value: this.value };
  }
  static fromJSON(schema, json) {
    if (typeof json.attr != "string")
      throw new RangeError("Invalid input for DocAttrStep.fromJSON");
    return new _DocAttrStep(json.attr, json.value);
  }
};
Step.jsonID("docAttr", DocAttrStep);
var TransformError = class extends Error {
};
TransformError = function TransformError2(message) {
  let err = Error.call(this, message);
  err.__proto__ = TransformError2.prototype;
  return err;
};
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
TransformError.prototype.name = "TransformError";
var Transform = class {
  /**
  Create a transform that starts with the given document.
  */
  constructor(doc3) {
    this.doc = doc3;
    this.steps = [];
    this.docs = [];
    this.mapping = new Mapping();
  }
  /**
  The starting document.
  */
  get before() {
    return this.docs.length ? this.docs[0] : this.doc;
  }
  /**
  Apply a new step in this transform, saving the result. Throws an
  error when the step fails.
  */
  step(step) {
    let result = this.maybeStep(step);
    if (result.failed)
      throw new TransformError(result.failed);
    return this;
  }
  /**
  Try to apply a step in this transformation, ignoring it if it
  fails. Returns the step result.
  */
  maybeStep(step) {
    let result = step.apply(this.doc);
    if (!result.failed)
      this.addStep(step, result.doc);
    return result;
  }
  /**
  True when the document has been changed (when there are any
  steps).
  */
  get docChanged() {
    return this.steps.length > 0;
  }
  /**
  Return a single range, in post-transform document positions,
  that covers all content changed by this transform. Returns null
  if no replacements are made. Note that this will ignore changes
  that add/remove marks without replacing the underlying content.
  */
  changedRange() {
    let from2 = 1e9, to = -1e9;
    for (let i = 0; i < this.mapping.maps.length; i++) {
      let map3 = this.mapping.maps[i];
      if (i) {
        from2 = map3.map(from2, 1);
        to = map3.map(to, -1);
      }
      map3.forEach((_f, _t, fromB, toB) => {
        from2 = Math.min(from2, fromB);
        to = Math.max(to, toB);
      });
    }
    return from2 == 1e9 ? null : { from: from2, to };
  }
  /**
  @internal
  */
  addStep(step, doc3) {
    this.docs.push(this.doc);
    this.steps.push(step);
    this.mapping.appendMap(step.getMap());
    this.doc = doc3;
  }
  /**
  Replace the part of the document between `from` and `to` with the
  given `slice`.
  */
  replace(from2, to = from2, slice2 = Slice.empty) {
    let step = replaceStep(this.doc, from2, to, slice2);
    if (step)
      this.step(step);
    return this;
  }
  /**
  Replace the given range with the given content, which may be a
  fragment, node, or array of nodes.
  */
  replaceWith(from2, to, content) {
    return this.replace(from2, to, new Slice(Fragment.from(content), 0, 0));
  }
  /**
  Delete the content between the given positions.
  */
  delete(from2, to) {
    return this.replace(from2, to, Slice.empty);
  }
  /**
  Insert the given content at the given position.
  */
  insert(pos, content) {
    return this.replaceWith(pos, pos, content);
  }
  /**
  Replace a range of the document with a given slice, using
  `from`, `to`, and the slice's
  [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
  than fixed start and end points. This method may grow the
  replaced area or close open nodes in the slice in order to get a
  fit that is more in line with WYSIWYG expectations, by dropping
  fully covered parent nodes of the replaced region when they are
  marked [non-defining as
  context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
  open parent node from the slice that _is_ marked as [defining
  its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
  
  This is the method, for example, to handle paste. The similar
  [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
  primitive tool which will _not_ move the start and end of its given
  range, and is useful in situations where you need more precise
  control over what happens.
  */
  replaceRange(from2, to, slice2) {
    replaceRange(this, from2, to, slice2);
    return this;
  }
  /**
  Replace the given range with a node, but use `from` and `to` as
  hints, rather than precise positions. When from and to are the same
  and are at the start or end of a parent node in which the given
  node doesn't fit, this method may _move_ them out towards a parent
  that does allow the given node to be placed. When the given range
  completely covers a parent node, this method may completely replace
  that parent node.
  */
  replaceRangeWith(from2, to, node) {
    replaceRangeWith(this, from2, to, node);
    return this;
  }
  /**
  Delete the given range, expanding it to cover fully covered
  parent nodes until a valid replace is found.
  */
  deleteRange(from2, to) {
    deleteRange(this, from2, to);
    return this;
  }
  /**
  Split the content in the given range off from its parent, if there
  is sibling content before or after it, and move it up the tree to
  the depth specified by `target`. You'll probably want to use
  [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
  sure the lift is valid.
  */
  lift(range2, target2) {
    lift(this, range2, target2);
    return this;
  }
  /**
  Join the blocks around the given position. If depth is 2, their
  last and first siblings are also joined, and so on.
  */
  join(pos, depth = 1) {
    join(this, pos, depth);
    return this;
  }
  /**
  Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
  The wrappers are assumed to be valid in this position, and should
  probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
  */
  wrap(range2, wrappers) {
    wrap(this, range2, wrappers);
    return this;
  }
  /**
  Set the type of all textblocks (partly) between `from` and `to` to
  the given node type with the given attributes.
  */
  setBlockType(from2, to = from2, type, attrs = null) {
    setBlockType(this, from2, to, type, attrs);
    return this;
  }
  /**
  Change the type, attributes, and/or marks of the node at `pos`.
  When `type` isn't given, the existing node type is preserved,
  */
  setNodeMarkup(pos, type, attrs = null, marks) {
    setNodeMarkup(this, pos, type, attrs, marks);
    return this;
  }
  /**
  Set a single attribute on a given node to a new value.
  The `pos` addresses the document content. Use `setDocAttribute`
  to set attributes on the document itself.
  */
  setNodeAttribute(pos, attr, value) {
    this.step(new AttrStep(pos, attr, value));
    return this;
  }
  /**
  Set a single attribute on the document to a new value.
  */
  setDocAttribute(attr, value) {
    this.step(new DocAttrStep(attr, value));
    return this;
  }
  /**
  Add a mark to the node at position `pos`.
  */
  addNodeMark(pos, mark) {
    this.step(new AddNodeMarkStep(pos, mark));
    return this;
  }
  /**
  Remove a mark (or all marks of the given type) from the node at
  position `pos`.
  */
  removeNodeMark(pos, mark) {
    let node = this.doc.nodeAt(pos);
    if (!node)
      throw new RangeError("No node at position " + pos);
    if (mark instanceof Mark) {
      if (mark.isInSet(node.marks))
        this.step(new RemoveNodeMarkStep(pos, mark));
    } else {
      let set = node.marks, found2, steps = [];
      while (found2 = mark.isInSet(set)) {
        steps.push(new RemoveNodeMarkStep(pos, found2));
        set = found2.removeFromSet(set);
      }
      for (let i = steps.length - 1; i >= 0; i--)
        this.step(steps[i]);
    }
    return this;
  }
  /**
  Split the node at the given position, and optionally, if `depth` is
  greater than one, any number of nodes above that. By default, the
  parts split off will inherit the node type of the original node.
  This can be changed by passing an array of types and attributes to
  use after the split (with the outermost nodes coming first).
  */
  split(pos, depth = 1, typesAfter) {
    split(this, pos, depth, typesAfter);
    return this;
  }
  /**
  Add the given mark to the inline content between `from` and `to`.
  */
  addMark(from2, to, mark) {
    addMark(this, from2, to, mark);
    return this;
  }
  /**
  Remove marks from inline nodes between `from` and `to`. When
  `mark` is a single mark, remove precisely that mark. When it is
  a mark type, remove all marks of that type. When it is null,
  remove all marks of any type.
  */
  removeMark(from2, to, mark) {
    removeMark(this, from2, to, mark);
    return this;
  }
  /**
  Removes all marks and nodes from the content of the node at
  `pos` that don't match the given new parent node type. Accepts
  an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
  third argument.
  */
  clearIncompatible(pos, parentType, match) {
    clearIncompatible(this, pos, parentType, match);
    return this;
  }
};

// node_modules/prosemirror-state/dist/index.js
var classesById = /* @__PURE__ */ Object.create(null);
var Selection = class {
  /**
  Initialize a selection with the head and anchor and ranges. If no
  ranges are given, constructs a single range across `$anchor` and
  `$head`.
  */
  constructor($anchor, $head, ranges) {
    this.$anchor = $anchor;
    this.$head = $head;
    this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
  }
  /**
  The selection's anchor, as an unresolved position.
  */
  get anchor() {
    return this.$anchor.pos;
  }
  /**
  The selection's head.
  */
  get head() {
    return this.$head.pos;
  }
  /**
  The lower bound of the selection's main range.
  */
  get from() {
    return this.$from.pos;
  }
  /**
  The upper bound of the selection's main range.
  */
  get to() {
    return this.$to.pos;
  }
  /**
  The resolved lower  bound of the selection's main range.
  */
  get $from() {
    return this.ranges[0].$from;
  }
  /**
  The resolved upper bound of the selection's main range.
  */
  get $to() {
    return this.ranges[0].$to;
  }
  /**
  Indicates whether the selection contains any content.
  */
  get empty() {
    let ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++)
      if (ranges[i].$from.pos != ranges[i].$to.pos)
        return false;
    return true;
  }
  /**
  Get the content of this selection as a slice.
  */
  content() {
    return this.$from.doc.slice(this.from, this.to, true);
  }
  /**
  Replace the selection with a slice or, if no slice is given,
  delete the selection. Will append to the given transaction.
  */
  replace(tr, content = Slice.empty) {
    let lastNode = content.content.lastChild, lastParent = null;
    for (let i = 0; i < content.openEnd; i++) {
      lastParent = lastNode;
      lastNode = lastNode.lastChild;
    }
    let mapFrom = tr.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
      tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);
      if (i == 0)
        selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
    }
  }
  /**
  Replace the selection with the given node, appending the changes
  to the given transaction.
  */
  replaceWith(tr, node) {
    let mapFrom = tr.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
      let from2 = mapping.map($from.pos), to = mapping.map($to.pos);
      if (i) {
        tr.deleteRange(from2, to);
      } else {
        tr.replaceRangeWith(from2, to, node);
        selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);
      }
    }
  }
  /**
  Find a valid cursor or leaf node selection starting at the given
  position and searching back if `dir` is negative, and forward if
  positive. When `textOnly` is true, only consider cursor
  selections. Will return null when no valid selection position is
  found.
  */
  static findFrom($pos, dir, textOnly = false) {
    let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
    if (inner)
      return inner;
    for (let depth = $pos.depth - 1; depth >= 0; depth--) {
      let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
      if (found2)
        return found2;
    }
    return null;
  }
  /**
  Find a valid cursor or leaf node selection near the given
  position. Searches forward first by default, but if `bias` is
  negative, it will search backwards first.
  */
  static near($pos, bias = 1) {
    return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
  }
  /**
  Find the cursor or leaf node selection closest to the start of
  the given document. Will return an
  [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
  exists.
  */
  static atStart(doc3) {
    return findSelectionIn(doc3, doc3, 0, 0, 1) || new AllSelection(doc3);
  }
  /**
  Find the cursor or leaf node selection closest to the end of the
  given document.
  */
  static atEnd(doc3) {
    return findSelectionIn(doc3, doc3, doc3.content.size, doc3.childCount, -1) || new AllSelection(doc3);
  }
  /**
  Deserialize the JSON representation of a selection. Must be
  implemented for custom classes (as a static class method).
  */
  static fromJSON(doc3, json) {
    if (!json || !json.type)
      throw new RangeError("Invalid input for Selection.fromJSON");
    let cls2 = classesById[json.type];
    if (!cls2)
      throw new RangeError(`No selection type ${json.type} defined`);
    return cls2.fromJSON(doc3, json);
  }
  /**
  To be able to deserialize selections from JSON, custom selection
  classes must register themselves with an ID string, so that they
  can be disambiguated. Try to pick something that's unlikely to
  clash with classes from other modules.
  */
  static jsonID(id, selectionClass) {
    if (id in classesById)
      throw new RangeError("Duplicate use of selection JSON ID " + id);
    classesById[id] = selectionClass;
    selectionClass.prototype.jsonID = id;
    return selectionClass;
  }
  /**
  Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
  which is a value that can be mapped without having access to a
  current document, and later resolved to a real selection for a
  given document again. (This is used mostly by the history to
  track and restore old selections.) The default implementation of
  this method just converts the selection to a text selection and
  returns the bookmark for that.
  */
  getBookmark() {
    return TextSelection.between(this.$anchor, this.$head).getBookmark();
  }
};
Selection.prototype.visible = true;
var SelectionRange = class {
  /**
  Create a range.
  */
  constructor($from, $to) {
    this.$from = $from;
    this.$to = $to;
  }
};
var warnedAboutTextSelection = false;
function checkTextSelection($pos) {
  if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
    warnedAboutTextSelection = true;
    console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
  }
}
var TextSelection = class _TextSelection extends Selection {
  /**
  Construct a text selection between the given points.
  */
  constructor($anchor, $head = $anchor) {
    checkTextSelection($anchor);
    checkTextSelection($head);
    super($anchor, $head);
  }
  /**
  Returns a resolved position if this is a cursor selection (an
  empty text selection), and null otherwise.
  */
  get $cursor() {
    return this.$anchor.pos == this.$head.pos ? this.$head : null;
  }
  map(doc3, mapping) {
    let $head = doc3.resolve(mapping.map(this.head));
    if (!$head.parent.inlineContent)
      return Selection.near($head);
    let $anchor = doc3.resolve(mapping.map(this.anchor));
    return new _TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  }
  replace(tr, content = Slice.empty) {
    super.replace(tr, content);
    if (content == Slice.empty) {
      let marks = this.$from.marksAcross(this.$to);
      if (marks)
        tr.ensureMarks(marks);
    }
  }
  eq(other) {
    return other instanceof _TextSelection && other.anchor == this.anchor && other.head == this.head;
  }
  getBookmark() {
    return new TextBookmark(this.anchor, this.head);
  }
  toJSON() {
    return { type: "text", anchor: this.anchor, head: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc3, json) {
    if (typeof json.anchor != "number" || typeof json.head != "number")
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    return new _TextSelection(doc3.resolve(json.anchor), doc3.resolve(json.head));
  }
  /**
  Create a text selection from non-resolved positions.
  */
  static create(doc3, anchor, head = anchor) {
    let $anchor = doc3.resolve(anchor);
    return new this($anchor, head == anchor ? $anchor : doc3.resolve(head));
  }
  /**
  Return a text selection that spans the given positions or, if
  they aren't text positions, find a text selection near them.
  `bias` determines whether the method searches forward (default)
  or backwards (negative number) first. Will fall back to calling
  [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
  doesn't contain a valid text position.
  */
  static between($anchor, $head, bias) {
    let dPos = $anchor.pos - $head.pos;
    if (!bias || dPos)
      bias = dPos >= 0 ? 1 : -1;
    if (!$head.parent.inlineContent) {
      let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
      if (found2)
        $head = found2.$head;
      else
        return Selection.near($head, bias);
    }
    if (!$anchor.parent.inlineContent) {
      if (dPos == 0) {
        $anchor = $head;
      } else {
        $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
        if ($anchor.pos < $head.pos != dPos < 0)
          $anchor = $head;
      }
    }
    return new _TextSelection($anchor, $head);
  }
};
Selection.jsonID("text", TextSelection);
var TextBookmark = class _TextBookmark {
  constructor(anchor, head) {
    this.anchor = anchor;
    this.head = head;
  }
  map(mapping) {
    return new _TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc3) {
    return TextSelection.between(doc3.resolve(this.anchor), doc3.resolve(this.head));
  }
};
var NodeSelection = class _NodeSelection extends Selection {
  /**
  Create a node selection. Does not verify the validity of its
  argument.
  */
  constructor($pos) {
    let node = $pos.nodeAfter;
    let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
    super($pos, $end);
    this.node = node;
  }
  map(doc3, mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    let $pos = doc3.resolve(pos);
    if (deleted)
      return Selection.near($pos);
    return new _NodeSelection($pos);
  }
  content() {
    return new Slice(Fragment.from(this.node), 0, 0);
  }
  eq(other) {
    return other instanceof _NodeSelection && other.anchor == this.anchor;
  }
  toJSON() {
    return { type: "node", anchor: this.anchor };
  }
  getBookmark() {
    return new NodeBookmark(this.anchor);
  }
  /**
  @internal
  */
  static fromJSON(doc3, json) {
    if (typeof json.anchor != "number")
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    return new _NodeSelection(doc3.resolve(json.anchor));
  }
  /**
  Create a node selection from non-resolved positions.
  */
  static create(doc3, from2) {
    return new _NodeSelection(doc3.resolve(from2));
  }
  /**
  Determines whether the given node may be selected as a node
  selection.
  */
  static isSelectable(node) {
    return !node.isText && node.type.spec.selectable !== false;
  }
};
NodeSelection.prototype.visible = false;
Selection.jsonID("node", NodeSelection);
var NodeBookmark = class _NodeBookmark {
  constructor(anchor) {
    this.anchor = anchor;
  }
  map(mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    return deleted ? new TextBookmark(pos, pos) : new _NodeBookmark(pos);
  }
  resolve(doc3) {
    let $pos = doc3.resolve(this.anchor), node = $pos.nodeAfter;
    if (node && NodeSelection.isSelectable(node))
      return new NodeSelection($pos);
    return Selection.near($pos);
  }
};
var AllSelection = class _AllSelection extends Selection {
  /**
  Create an all-selection over the given document.
  */
  constructor(doc3) {
    super(doc3.resolve(0), doc3.resolve(doc3.content.size));
  }
  replace(tr, content = Slice.empty) {
    if (content == Slice.empty) {
      tr.delete(0, tr.doc.content.size);
      let sel = Selection.atStart(tr.doc);
      if (!sel.eq(tr.selection))
        tr.setSelection(sel);
    } else {
      super.replace(tr, content);
    }
  }
  toJSON() {
    return { type: "all" };
  }
  /**
  @internal
  */
  static fromJSON(doc3) {
    return new _AllSelection(doc3);
  }
  map(doc3) {
    return new _AllSelection(doc3);
  }
  eq(other) {
    return other instanceof _AllSelection;
  }
  getBookmark() {
    return AllBookmark;
  }
};
Selection.jsonID("all", AllSelection);
var AllBookmark = {
  map() {
    return this;
  },
  resolve(doc3) {
    return new AllSelection(doc3);
  }
};
function findSelectionIn(doc3, node, pos, index2, dir, text2 = false) {
  if (node.inlineContent)
    return TextSelection.create(doc3, pos);
  for (let i = index2 - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {
    let child = node.child(i);
    if (!child.isAtom) {
      let inner = findSelectionIn(doc3, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text2);
      if (inner)
        return inner;
    } else if (!text2 && NodeSelection.isSelectable(child)) {
      return NodeSelection.create(doc3, pos - (dir < 0 ? child.nodeSize : 0));
    }
    pos += child.nodeSize * dir;
  }
  return null;
}
function selectionToInsertionEnd(tr, startLen, bias) {
  let last2 = tr.steps.length - 1;
  if (last2 < startLen)
    return;
  let step = tr.steps[last2];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
    return;
  let map3 = tr.mapping.maps[last2], end;
  map3.forEach((_from, _to, _newFrom, newTo) => {
    if (end == null)
      end = newTo;
  });
  tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
}
var UPDATED_SEL = 1;
var UPDATED_MARKS = 2;
var UPDATED_SCROLL = 4;
var Transaction = class extends Transform {
  /**
  @internal
  */
  constructor(state) {
    super(state.doc);
    this.curSelectionFor = 0;
    this.updated = 0;
    this.meta = /* @__PURE__ */ Object.create(null);
    this.time = Date.now();
    this.curSelection = state.selection;
    this.storedMarks = state.storedMarks;
  }
  /**
  The transaction's current selection. This defaults to the editor
  selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
  transaction, but can be overwritten with
  [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
  */
  get selection() {
    if (this.curSelectionFor < this.steps.length) {
      this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
      this.curSelectionFor = this.steps.length;
    }
    return this.curSelection;
  }
  /**
  Update the transaction's current selection. Will determine the
  selection that the editor gets when the transaction is applied.
  */
  setSelection(selection) {
    if (selection.$from.doc != this.doc)
      throw new RangeError("Selection passed to setSelection must point at the current document");
    this.curSelection = selection;
    this.curSelectionFor = this.steps.length;
    this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
    this.storedMarks = null;
    return this;
  }
  /**
  Whether the selection was explicitly updated by this transaction.
  */
  get selectionSet() {
    return (this.updated & UPDATED_SEL) > 0;
  }
  /**
  Set the current stored marks.
  */
  setStoredMarks(marks) {
    this.storedMarks = marks;
    this.updated |= UPDATED_MARKS;
    return this;
  }
  /**
  Make sure the current stored marks or, if that is null, the marks
  at the selection, match the given set of marks. Does nothing if
  this is already the case.
  */
  ensureMarks(marks) {
    if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
      this.setStoredMarks(marks);
    return this;
  }
  /**
  Add a mark to the set of stored marks.
  */
  addStoredMark(mark) {
    return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Remove a mark or mark type from the set of stored marks.
  */
  removeStoredMark(mark) {
    return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Whether the stored marks were explicitly set for this transaction.
  */
  get storedMarksSet() {
    return (this.updated & UPDATED_MARKS) > 0;
  }
  /**
  @internal
  */
  addStep(step, doc3) {
    super.addStep(step, doc3);
    this.updated = this.updated & ~UPDATED_MARKS;
    this.storedMarks = null;
  }
  /**
  Update the timestamp for the transaction.
  */
  setTime(time) {
    this.time = time;
    return this;
  }
  /**
  Replace the current selection with the given slice.
  */
  replaceSelection(slice2) {
    this.selection.replace(this, slice2);
    return this;
  }
  /**
  Replace the selection with the given node. When `inheritMarks` is
  true and the content is inline, it inherits the marks from the
  place where it is inserted.
  */
  replaceSelectionWith(node, inheritMarks = true) {
    let selection = this.selection;
    if (inheritMarks)
      node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none));
    selection.replaceWith(this, node);
    return this;
  }
  /**
  Delete the selection.
  */
  deleteSelection() {
    this.selection.replace(this);
    return this;
  }
  /**
  Replace the given range, or the selection if no range is given,
  with a text node containing the given string.
  */
  insertText(text2, from2, to) {
    let schema = this.doc.type.schema;
    if (from2 == null) {
      if (!text2)
        return this.deleteSelection();
      return this.replaceSelectionWith(schema.text(text2), true);
    } else {
      if (to == null)
        to = from2;
      if (!text2)
        return this.deleteRange(from2, to);
      let marks = this.storedMarks;
      if (!marks) {
        let $from = this.doc.resolve(from2);
        marks = to == from2 ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
      }
      this.replaceRangeWith(from2, to, schema.text(text2, marks));
      if (!this.selection.empty && this.selection.to == from2 + text2.length)
        this.setSelection(Selection.near(this.selection.$to));
      return this;
    }
  }
  /**
  Store a metadata property in this transaction, keyed either by
  name or by plugin.
  */
  setMeta(key, value) {
    this.meta[typeof key == "string" ? key : key.key] = value;
    return this;
  }
  /**
  Retrieve a metadata property for a given name or plugin.
  */
  getMeta(key) {
    return this.meta[typeof key == "string" ? key : key.key];
  }
  /**
  Returns true if this transaction doesn't contain any metadata,
  and can thus safely be extended.
  */
  get isGeneric() {
    for (let _ in this.meta)
      return false;
    return true;
  }
  /**
  Indicate that the editor should scroll the selection into view
  when updated to the state produced by this transaction.
  */
  scrollIntoView() {
    this.updated |= UPDATED_SCROLL;
    return this;
  }
  /**
  True when this transaction has had `scrollIntoView` called on it.
  */
  get scrolledIntoView() {
    return (this.updated & UPDATED_SCROLL) > 0;
  }
};
function bind(f, self2) {
  return !self2 || !f ? f : f.bind(self2);
}
var FieldDesc = class {
  constructor(name, desc, self2) {
    this.name = name;
    this.init = bind(desc.init, self2);
    this.apply = bind(desc.apply, self2);
  }
};
var baseFields = [
  new FieldDesc("doc", {
    init(config) {
      return config.doc || config.schema.topNodeType.createAndFill();
    },
    apply(tr) {
      return tr.doc;
    }
  }),
  new FieldDesc("selection", {
    init(config, instance) {
      return config.selection || Selection.atStart(instance.doc);
    },
    apply(tr) {
      return tr.selection;
    }
  }),
  new FieldDesc("storedMarks", {
    init(config) {
      return config.storedMarks || null;
    },
    apply(tr, _marks, _old, state) {
      return state.selection.$cursor ? tr.storedMarks : null;
    }
  }),
  new FieldDesc("scrollToSelection", {
    init() {
      return 0;
    },
    apply(tr, prev) {
      return tr.scrolledIntoView ? prev + 1 : prev;
    }
  })
];
var Configuration = class {
  constructor(schema, plugins) {
    this.schema = schema;
    this.plugins = [];
    this.pluginsByKey = /* @__PURE__ */ Object.create(null);
    this.fields = baseFields.slice();
    if (plugins)
      plugins.forEach((plugin) => {
        if (this.pluginsByKey[plugin.key])
          throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
        this.plugins.push(plugin);
        this.pluginsByKey[plugin.key] = plugin;
        if (plugin.spec.state)
          this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
      });
  }
};
var EditorState = class _EditorState {
  /**
  @internal
  */
  constructor(config) {
    this.config = config;
  }
  /**
  The schema of the state's document.
  */
  get schema() {
    return this.config.schema;
  }
  /**
  The plugins that are active in this state.
  */
  get plugins() {
    return this.config.plugins;
  }
  /**
  Apply the given transaction to produce a new state.
  */
  apply(tr) {
    return this.applyTransaction(tr).state;
  }
  /**
  @internal
  */
  filterTransaction(tr, ignore = -1) {
    for (let i = 0; i < this.config.plugins.length; i++)
      if (i != ignore) {
        let plugin = this.config.plugins[i];
        if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))
          return false;
      }
    return true;
  }
  /**
  Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that
  returns the precise transactions that were applied (which might
  be influenced by the [transaction
  hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of
  plugins) along with the new state.
  */
  applyTransaction(rootTr) {
    if (!this.filterTransaction(rootTr))
      return { state: this, transactions: [] };
    let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;
    for (; ; ) {
      let haveNew = false;
      for (let i = 0; i < this.config.plugins.length; i++) {
        let plugin = this.config.plugins[i];
        if (plugin.spec.appendTransaction) {
          let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;
          let tr = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);
          if (tr && newState.filterTransaction(tr, i)) {
            tr.setMeta("appendedTransaction", rootTr);
            if (!seen) {
              seen = [];
              for (let j = 0; j < this.config.plugins.length; j++)
                seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });
            }
            trs.push(tr);
            newState = newState.applyInner(tr);
            haveNew = true;
          }
          if (seen)
            seen[i] = { state: newState, n: trs.length };
        }
      }
      if (!haveNew)
        return { state: newState, transactions: trs };
    }
  }
  /**
  @internal
  */
  applyInner(tr) {
    if (!tr.before.eq(this.doc))
      throw new RangeError("Applying a mismatched transaction");
    let newInstance = new _EditorState(this.config), fields = this.config.fields;
    for (let i = 0; i < fields.length; i++) {
      let field = fields[i];
      newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);
    }
    return newInstance;
  }
  /**
  Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  */
  get tr() {
    return new Transaction(this);
  }
  /**
  Create a new state.
  */
  static create(config) {
    let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);
    let instance = new _EditorState($config);
    for (let i = 0; i < $config.fields.length; i++)
      instance[$config.fields[i].name] = $config.fields[i].init(config, instance);
    return instance;
  }
  /**
  Create a new state based on this one, but with an adjusted set
  of active plugins. State fields that exist in both sets of
  plugins are kept unchanged. Those that no longer exist are
  dropped, and those that are new are initialized using their
  [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new
  configuration object..
  */
  reconfigure(config) {
    let $config = new Configuration(this.schema, config.plugins);
    let fields = $config.fields, instance = new _EditorState($config);
    for (let i = 0; i < fields.length; i++) {
      let name = fields[i].name;
      instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);
    }
    return instance;
  }
  /**
  Serialize this state to JSON. If you want to serialize the state
  of plugins, pass an object mapping property names to use in the
  resulting JSON object to plugin objects. The argument may also be
  a string or number, in which case it is ignored, to support the
  way `JSON.stringify` calls `toString` methods.
  */
  toJSON(pluginFields) {
    let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
    if (this.storedMarks)
      result.storedMarks = this.storedMarks.map((m) => m.toJSON());
    if (pluginFields && typeof pluginFields == "object")
      for (let prop2 in pluginFields) {
        if (prop2 == "doc" || prop2 == "selection")
          throw new RangeError("The JSON fields `doc` and `selection` are reserved");
        let plugin = pluginFields[prop2], state = plugin.spec.state;
        if (state && state.toJSON)
          result[prop2] = state.toJSON.call(plugin, this[plugin.key]);
      }
    return result;
  }
  /**
  Deserialize a JSON representation of a state. `config` should
  have at least a `schema` field, and should contain array of
  plugins to initialize the state with. `pluginFields` can be used
  to deserialize the state of plugins, by associating plugin
  instances with the property names they use in the JSON object.
  */
  static fromJSON(config, json, pluginFields) {
    if (!json)
      throw new RangeError("Invalid input for EditorState.fromJSON");
    if (!config.schema)
      throw new RangeError("Required config field 'schema' missing");
    let $config = new Configuration(config.schema, config.plugins);
    let instance = new _EditorState($config);
    $config.fields.forEach((field) => {
      if (field.name == "doc") {
        instance.doc = Node2.fromJSON(config.schema, json.doc);
      } else if (field.name == "selection") {
        instance.selection = Selection.fromJSON(instance.doc, json.selection);
      } else if (field.name == "storedMarks") {
        if (json.storedMarks)
          instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);
      } else {
        if (pluginFields)
          for (let prop2 in pluginFields) {
            let plugin = pluginFields[prop2], state = plugin.spec.state;
            if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop2)) {
              instance[field.name] = state.fromJSON.call(plugin, config, json[prop2], instance);
              return;
            }
          }
        instance[field.name] = field.init(config, instance);
      }
    });
    return instance;
  }
};
function bindProps(obj, self2, target2) {
  for (let prop2 in obj) {
    let val = obj[prop2];
    if (val instanceof Function)
      val = val.bind(self2);
    else if (prop2 == "handleDOMEvents")
      val = bindProps(val, self2, {});
    target2[prop2] = val;
  }
  return target2;
}
var Plugin = class {
  /**
  Create a plugin.
  */
  constructor(spec) {
    this.spec = spec;
    this.props = {};
    if (spec.props)
      bindProps(spec.props, this, this.props);
    this.key = spec.key ? spec.key.key : createKey("plugin");
  }
  /**
  Extract the plugin's state field from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
};
var keys = /* @__PURE__ */ Object.create(null);
function createKey(name) {
  if (name in keys)
    return name + "$" + ++keys[name];
  keys[name] = 0;
  return name + "$";
}
var PluginKey = class {
  /**
  Create a plugin key.
  */
  constructor(name = "key") {
    this.key = createKey(name);
  }
  /**
  Get the active plugin with this key, if any, from an editor
  state.
  */
  get(state) {
    return state.config.pluginsByKey[this.key];
  }
  /**
  Get the plugin's state from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
};

// node_modules/prosemirror-view/dist/index.js
var domIndex = function(node) {
  for (var index2 = 0; ; index2++) {
    node = node.previousSibling;
    if (!node)
      return index2;
  }
};
var parentNode = function(node) {
  let parent = node.assignedSlot || node.parentNode;
  return parent && parent.nodeType == 11 ? parent.host : parent;
};
var reusedRange = null;
var textRange = function(node, from2, to) {
  let range2 = reusedRange || (reusedRange = document.createRange());
  range2.setEnd(node, to == null ? node.nodeValue.length : to);
  range2.setStart(node, from2 || 0);
  return range2;
};
var clearReusedRange = function() {
  reusedRange = null;
};
var isEquivalentPosition = function(node, off2, targetNode, targetOff) {
  return targetNode && (scanFor(node, off2, targetNode, targetOff, -1) || scanFor(node, off2, targetNode, targetOff, 1));
};
var atomElements = /^(img|br|input|textarea|hr)$/i;
function scanFor(node, off2, targetNode, targetOff, dir) {
  var _a;
  for (; ; ) {
    if (node == targetNode && off2 == targetOff)
      return true;
    if (off2 == (dir < 0 ? 0 : nodeSize(node))) {
      let parent = node.parentNode;
      if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false")
        return false;
      off2 = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent;
    } else if (node.nodeType == 1) {
      let child = node.childNodes[off2 + (dir < 0 ? -1 : 0)];
      if (child.nodeType == 1 && child.contentEditable == "false") {
        if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)
          off2 += dir;
        else
          return false;
      } else {
        node = child;
        off2 = dir < 0 ? nodeSize(node) : 0;
      }
    } else {
      return false;
    }
  }
}
function nodeSize(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function textNodeBefore$1(node, offset) {
  for (; ; ) {
    if (node.nodeType == 3 && offset)
      return node;
    if (node.nodeType == 1 && offset > 0) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset - 1];
      offset = nodeSize(node);
    } else if (node.parentNode && !hasBlockDesc(node)) {
      offset = domIndex(node);
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
function textNodeAfter$1(node, offset) {
  for (; ; ) {
    if (node.nodeType == 3 && offset < node.nodeValue.length)
      return node;
    if (node.nodeType == 1 && offset < node.childNodes.length) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset];
      offset = 0;
    } else if (node.parentNode && !hasBlockDesc(node)) {
      offset = domIndex(node) + 1;
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
function isOnEdge(node, offset, parent) {
  for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) {
    if (node == parent)
      return true;
    let index2 = domIndex(node);
    node = node.parentNode;
    if (!node)
      return false;
    atStart = atStart && index2 == 0;
    atEnd = atEnd && index2 == nodeSize(node);
  }
}
function hasBlockDesc(dom) {
  let desc;
  for (let cur = dom; cur; cur = cur.parentNode)
    if (desc = cur.pmViewDesc)
      break;
  return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
}
var selectionCollapsed = function(domSel) {
  return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);
};
function keyEvent(keyCode, key) {
  let event = document.createEvent("Event");
  event.initEvent("keydown", true, true);
  event.keyCode = keyCode;
  event.key = event.code = key;
  return event;
}
function deepActiveElement(doc3) {
  let elt = doc3.activeElement;
  while (elt && elt.shadowRoot)
    elt = elt.shadowRoot.activeElement;
  return elt;
}
function caretFromPoint(doc3, x, y) {
  if (doc3.caretPositionFromPoint) {
    try {
      let pos = doc3.caretPositionFromPoint(x, y);
      if (pos)
        return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };
    } catch (_) {
    }
  }
  if (doc3.caretRangeFromPoint) {
    let range2 = doc3.caretRangeFromPoint(x, y);
    if (range2)
      return { node: range2.startContainer, offset: Math.min(nodeSize(range2.startContainer), range2.startOffset) };
  }
}
var nav = typeof navigator != "undefined" ? navigator : null;
var doc2 = typeof document != "undefined" ? document : null;
var agent = nav && nav.userAgent || "";
var ie_edge = /Edge\/(\d+)/.exec(agent);
var ie_upto10 = /MSIE \d/.exec(agent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent);
var ie = !!(ie_upto10 || ie_11up || ie_edge);
var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;
var gecko = !ie && /gecko\/(\d+)/i.test(agent);
gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1];
var _chrome = !ie && /Chrome\/(\d+)/.exec(agent);
var chrome = !!_chrome;
var chrome_version = _chrome ? +_chrome[1] : 0;
var safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);
var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);
var mac = ios || (nav ? /Mac/.test(nav.platform) : false);
var windows = nav ? /Win/.test(nav.platform) : false;
var android = /Android \d/.test(agent);
var webkit = !!doc2 && "webkitFontSmoothing" in doc2.documentElement.style;
var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
function windowRect(doc3) {
  let vp = doc3.defaultView && doc3.defaultView.visualViewport;
  if (vp)
    return {
      left: 0,
      right: vp.width,
      top: 0,
      bottom: vp.height
    };
  return {
    left: 0,
    right: doc3.documentElement.clientWidth,
    top: 0,
    bottom: doc3.documentElement.clientHeight
  };
}
function getSide(value, side) {
  return typeof value == "number" ? value : value[side];
}
function clientRect(node) {
  let rect2 = node.getBoundingClientRect();
  let scaleX = rect2.width / node.offsetWidth || 1;
  let scaleY = rect2.height / node.offsetHeight || 1;
  return {
    left: rect2.left,
    right: rect2.left + node.clientWidth * scaleX,
    top: rect2.top,
    bottom: rect2.top + node.clientHeight * scaleY
  };
}
function scrollRectIntoView(view, rect2, startDOM) {
  let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5;
  let doc3 = view.dom.ownerDocument;
  for (let parent = startDOM || view.dom; ; ) {
    if (!parent)
      break;
    if (parent.nodeType != 1) {
      parent = parentNode(parent);
      continue;
    }
    let elt = parent;
    let atTop = elt == doc3.body;
    let bounding = atTop ? windowRect(doc3) : clientRect(elt);
    let moveX = 0, moveY = 0;
    if (rect2.top < bounding.top + getSide(scrollThreshold, "top"))
      moveY = -(bounding.top - rect2.top + getSide(scrollMargin, "top"));
    else if (rect2.bottom > bounding.bottom - getSide(scrollThreshold, "bottom"))
      moveY = rect2.bottom - rect2.top > bounding.bottom - bounding.top ? rect2.top + getSide(scrollMargin, "top") - bounding.top : rect2.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
    if (rect2.left < bounding.left + getSide(scrollThreshold, "left"))
      moveX = -(bounding.left - rect2.left + getSide(scrollMargin, "left"));
    else if (rect2.right > bounding.right - getSide(scrollThreshold, "right"))
      moveX = rect2.right - bounding.right + getSide(scrollMargin, "right");
    if (moveX || moveY) {
      if (atTop) {
        doc3.defaultView.scrollBy(moveX, moveY);
      } else {
        let startX = elt.scrollLeft, startY = elt.scrollTop;
        if (moveY)
          elt.scrollTop += moveY;
        if (moveX)
          elt.scrollLeft += moveX;
        let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;
        rect2 = { left: rect2.left - dX, top: rect2.top - dY, right: rect2.right - dX, bottom: rect2.bottom - dY };
      }
    }
    let pos = atTop ? "fixed" : getComputedStyle(parent).position;
    if (/^(fixed|sticky)$/.test(pos))
      break;
    parent = pos == "absolute" ? parent.offsetParent : parentNode(parent);
  }
}
function storeScrollPos(view) {
  let rect2 = view.dom.getBoundingClientRect(), startY = Math.max(0, rect2.top);
  let refDOM, refTop;
  for (let x = (rect2.left + rect2.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect2.bottom); y += 5) {
    let dom = view.root.elementFromPoint(x, y);
    if (!dom || dom == view.dom || !view.dom.contains(dom))
      continue;
    let localRect = dom.getBoundingClientRect();
    if (localRect.top >= startY - 20) {
      refDOM = dom;
      refTop = localRect.top;
      break;
    }
  }
  return { refDOM, refTop, stack: scrollStack(view.dom) };
}
function scrollStack(dom) {
  let stack = [], doc3 = dom.ownerDocument;
  for (let cur = dom; cur; cur = parentNode(cur)) {
    stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });
    if (dom == doc3)
      break;
  }
  return stack;
}
function resetScrollPos({ refDOM, refTop, stack }) {
  let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
  restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);
}
function restoreScrollStack(stack, dTop) {
  for (let i = 0; i < stack.length; i++) {
    let { dom, top: top2, left } = stack[i];
    if (dom.scrollTop != top2 + dTop)
      dom.scrollTop = top2 + dTop;
    if (dom.scrollLeft != left)
      dom.scrollLeft = left;
  }
}
var preventScrollSupported = null;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stored = scrollStack(dom);
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    restoreScrollStack(stored, 0);
  }
}
function findOffsetInNode(node, coords) {
  let closest2, dxClosest = 2e8, coordsClosest, offset = 0;
  let rowBot = coords.top, rowTop = coords.top;
  let firstBelow, coordsBelow;
  for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {
    let rects;
    if (child.nodeType == 1)
      rects = child.getClientRects();
    else if (child.nodeType == 3)
      rects = textRange(child).getClientRects();
    else
      continue;
    for (let i = 0; i < rects.length; i++) {
      let rect2 = rects[i];
      if (rect2.top <= rowBot && rect2.bottom >= rowTop) {
        rowBot = Math.max(rect2.bottom, rowBot);
        rowTop = Math.min(rect2.top, rowTop);
        let dx = rect2.left > coords.left ? rect2.left - coords.left : rect2.right < coords.left ? coords.left - rect2.right : 0;
        if (dx < dxClosest) {
          closest2 = child;
          dxClosest = dx;
          coordsClosest = dx && closest2.nodeType == 3 ? {
            left: rect2.right < coords.left ? rect2.right : rect2.left,
            top: coords.top
          } : coords;
          if (child.nodeType == 1 && dx)
            offset = childIndex + (coords.left >= (rect2.left + rect2.right) / 2 ? 1 : 0);
          continue;
        }
      } else if (rect2.top > coords.top && !firstBelow && rect2.left <= coords.left && rect2.right >= coords.left) {
        firstBelow = child;
        coordsBelow = { left: Math.max(rect2.left, Math.min(rect2.right, coords.left)), top: rect2.top };
      }
      if (!closest2 && (coords.left >= rect2.right && coords.top >= rect2.top || coords.left >= rect2.left && coords.top >= rect2.bottom))
        offset = childIndex + 1;
    }
  }
  if (!closest2 && firstBelow) {
    closest2 = firstBelow;
    coordsClosest = coordsBelow;
    dxClosest = 0;
  }
  if (closest2 && closest2.nodeType == 3)
    return findOffsetInText(closest2, coordsClosest);
  if (!closest2 || dxClosest && closest2.nodeType == 1)
    return { node, offset };
  return findOffsetInNode(closest2, coordsClosest);
}
function findOffsetInText(node, coords) {
  let len = node.nodeValue.length;
  let range2 = document.createRange(), result;
  for (let i = 0; i < len; i++) {
    range2.setEnd(node, i + 1);
    range2.setStart(node, i);
    let rect2 = singleRect(range2, 1);
    if (rect2.top == rect2.bottom)
      continue;
    if (inRect(coords, rect2)) {
      result = { node, offset: i + (coords.left >= (rect2.left + rect2.right) / 2 ? 1 : 0) };
      break;
    }
  }
  range2.detach();
  return result || { node, offset: 0 };
}
function inRect(coords, rect2) {
  return coords.left >= rect2.left - 1 && coords.left <= rect2.right + 1 && coords.top >= rect2.top - 1 && coords.top <= rect2.bottom + 1;
}
function targetKludge(dom, coords) {
  let parent = dom.parentNode;
  if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)
    return parent;
  return dom;
}
function posFromElement(view, elt, coords) {
  let { node, offset } = findOffsetInNode(elt, coords), bias = -1;
  if (node.nodeType == 1 && !node.firstChild) {
    let rect2 = node.getBoundingClientRect();
    bias = rect2.left != rect2.right && coords.left > (rect2.left + rect2.right) / 2 ? 1 : -1;
  }
  return view.docView.posFromDOM(node, offset, bias);
}
function posFromCaret(view, node, offset, coords) {
  let outsideBlock = -1;
  for (let cur = node, sawBlock = false; ; ) {
    if (cur == view.dom)
      break;
    let desc = view.docView.nearestDesc(cur, true), rect2;
    if (!desc)
      return null;
    if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles
    ((rect2 = desc.dom.getBoundingClientRect()).width || rect2.height)) {
      if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {
        if (!sawBlock && rect2.left > coords.left || rect2.top > coords.top)
          outsideBlock = desc.posBefore;
        else if (!sawBlock && rect2.right < coords.left || rect2.bottom < coords.top)
          outsideBlock = desc.posAfter;
        sawBlock = true;
      }
      if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {
        let before = desc.node.isBlock ? coords.top < (rect2.top + rect2.bottom) / 2 : coords.left < (rect2.left + rect2.right) / 2;
        return before ? desc.posBefore : desc.posAfter;
      }
    }
    cur = desc.dom.parentNode;
  }
  return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);
}
function elementFromPoint(element, coords, box) {
  let len = element.childNodes.length;
  if (len && box.top < box.bottom) {
    for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI; ; ) {
      let child = element.childNodes[i];
      if (child.nodeType == 1) {
        let rects = child.getClientRects();
        for (let j = 0; j < rects.length; j++) {
          let rect2 = rects[j];
          if (inRect(coords, rect2))
            return elementFromPoint(child, coords, rect2);
        }
      }
      if ((i = (i + 1) % len) == startI)
        break;
    }
  }
  return element;
}
function posAtCoords(view, coords) {
  let doc3 = view.dom.ownerDocument, node, offset = 0;
  let caret2 = caretFromPoint(doc3, coords.left, coords.top);
  if (caret2)
    ({ node, offset } = caret2);
  let elt = (view.root.elementFromPoint ? view.root : doc3).elementFromPoint(coords.left, coords.top);
  let pos;
  if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {
    let box = view.dom.getBoundingClientRect();
    if (!inRect(coords, box))
      return null;
    elt = elementFromPoint(view.dom, coords, box);
    if (!elt)
      return null;
  }
  if (safari) {
    for (let p = elt; node && p; p = parentNode(p))
      if (p.draggable)
        node = void 0;
  }
  elt = targetKludge(elt, coords);
  if (node) {
    if (gecko && node.nodeType == 1) {
      offset = Math.min(offset, node.childNodes.length);
      if (offset < node.childNodes.length) {
        let next = node.childNodes[offset], box;
        if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top)
          offset++;
      }
    }
    let prev;
    if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top)
      offset--;
    if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom)
      pos = view.state.doc.content.size;
    else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR")
      pos = posFromCaret(view, node, offset, coords);
  }
  if (pos == null)
    pos = posFromElement(view, elt, coords);
  let desc = view.docView.nearestDesc(elt, true);
  return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };
}
function nonZero(rect2) {
  return rect2.top < rect2.bottom || rect2.left < rect2.right;
}
function singleRect(target2, bias) {
  let rects = target2.getClientRects();
  if (rects.length) {
    let first = rects[bias < 0 ? 0 : rects.length - 1];
    if (nonZero(first))
      return first;
  }
  return Array.prototype.find.call(rects, nonZero) || target2.getBoundingClientRect();
}
var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
function coordsAtPos(view, pos, side) {
  let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);
  let supportEmptyRange = webkit || gecko;
  if (node.nodeType == 3) {
    if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {
      let rect2 = singleRect(textRange(node, offset, offset), side);
      if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {
        let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);
        if (rectBefore.top == rect2.top) {
          let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);
          if (rectAfter.top != rect2.top)
            return flattenV(rectAfter, rectAfter.left < rectBefore.left);
        }
      }
      return rect2;
    } else {
      let from2 = offset, to = offset, takeSide = side < 0 ? 1 : -1;
      if (side < 0 && !offset) {
        to++;
        takeSide = -1;
      } else if (side >= 0 && offset == node.nodeValue.length) {
        from2--;
        takeSide = 1;
      } else if (side < 0) {
        from2--;
      } else {
        to++;
      }
      return flattenV(singleRect(textRange(node, from2, to), takeSide), takeSide < 0);
    }
  }
  let $dom = view.state.doc.resolve(pos - (atom || 0));
  if (!$dom.parent.inlineContent) {
    if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
      let before = node.childNodes[offset - 1];
      if (before.nodeType == 1)
        return flattenH(before.getBoundingClientRect(), false);
    }
    if (atom == null && offset < nodeSize(node)) {
      let after = node.childNodes[offset];
      if (after.nodeType == 1)
        return flattenH(after.getBoundingClientRect(), true);
    }
    return flattenH(node.getBoundingClientRect(), side >= 0);
  }
  if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
    let before = node.childNodes[offset - 1];
    let target2 = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null;
    if (target2)
      return flattenV(singleRect(target2, 1), false);
  }
  if (atom == null && offset < nodeSize(node)) {
    let after = node.childNodes[offset];
    while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)
      after = after.nextSibling;
    let target2 = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null;
    if (target2)
      return flattenV(singleRect(target2, -1), true);
  }
  return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);
}
function flattenV(rect2, left) {
  if (rect2.width == 0)
    return rect2;
  let x = left ? rect2.left : rect2.right;
  return { top: rect2.top, bottom: rect2.bottom, left: x, right: x };
}
function flattenH(rect2, top2) {
  if (rect2.height == 0)
    return rect2;
  let y = top2 ? rect2.top : rect2.bottom;
  return { top: y, bottom: y, left: rect2.left, right: rect2.right };
}
function withFlushedState(view, state, f) {
  let viewState = view.state, active = view.root.activeElement;
  if (viewState != state)
    view.updateState(state);
  if (active != view.dom)
    view.focus();
  try {
    return f();
  } finally {
    if (viewState != state)
      view.updateState(viewState);
    if (active != view.dom && active)
      active.focus();
  }
}
function endOfTextblockVertical(view, state, dir) {
  let sel = state.selection;
  let $pos = dir == "up" ? sel.$from : sel.$to;
  return withFlushedState(view, state, () => {
    let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1);
    for (; ; ) {
      let nearest = view.docView.nearestDesc(dom, true);
      if (!nearest)
        break;
      if (nearest.node.isBlock) {
        dom = nearest.contentDOM || nearest.dom;
        break;
      }
      dom = nearest.dom.parentNode;
    }
    let coords = coordsAtPos(view, $pos.pos, 1);
    for (let child = dom.firstChild; child; child = child.nextSibling) {
      let boxes;
      if (child.nodeType == 1)
        boxes = child.getClientRects();
      else if (child.nodeType == 3)
        boxes = textRange(child, 0, child.nodeValue.length).getClientRects();
      else
        continue;
      for (let i = 0; i < boxes.length; i++) {
        let box = boxes[i];
        if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))
          return false;
      }
    }
    return true;
  });
}
var maybeRTL = /[\u0590-\u08ac]/;
function endOfTextblockHorizontal(view, state, dir) {
  let { $head } = state.selection;
  if (!$head.parent.isTextblock)
    return false;
  let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;
  let sel = view.domSelection();
  if (!sel)
    return $head.pos == $head.start() || $head.pos == $head.end();
  if (!maybeRTL.test($head.parent.textContent) || !sel.modify)
    return dir == "left" || dir == "backward" ? atStart : atEnd;
  return withFlushedState(view, state, () => {
    let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();
    let oldBidiLevel = sel.caretBidiLevel;
    sel.modify("move", dir, "character");
    let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
    let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();
    let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff;
    try {
      sel.collapse(anchorNode, anchorOffset);
      if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)
        sel.extend(oldNode, oldOff);
    } catch (_) {
    }
    if (oldBidiLevel != null)
      sel.caretBidiLevel = oldBidiLevel;
    return result;
  });
}
var cachedState = null;
var cachedDir = null;
var cachedResult = false;
function endOfTextblock(view, state, dir) {
  if (cachedState == state && cachedDir == dir)
    return cachedResult;
  cachedState = state;
  cachedDir = dir;
  return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
}
var NOT_DIRTY = 0;
var CHILD_DIRTY = 1;
var CONTENT_DIRTY = 2;
var NODE_DIRTY = 3;
var ViewDesc = class {
  constructor(parent, children, dom, contentDOM) {
    this.parent = parent;
    this.children = children;
    this.dom = dom;
    this.contentDOM = contentDOM;
    this.dirty = NOT_DIRTY;
    dom.pmViewDesc = this;
  }
  // Used to check whether a given description corresponds to a
  // widget/mark/node.
  matchesWidget(widget) {
    return false;
  }
  matchesMark(mark) {
    return false;
  }
  matchesNode(node, outerDeco, innerDeco) {
    return false;
  }
  matchesHack(nodeName) {
    return false;
  }
  // When parsing in-editor content (in domchange.js), we allow
  // descriptions to determine the parse rules that should be used to
  // parse them.
  parseRule() {
    return null;
  }
  // Used by the editor's event handler to ignore events that come
  // from certain descs.
  stopEvent(event) {
    return false;
  }
  // The size of the content represented by this desc.
  get size() {
    let size = 0;
    for (let i = 0; i < this.children.length; i++)
      size += this.children[i].size;
    return size;
  }
  // For block nodes, this represents the space taken up by their
  // start/end tokens.
  get border() {
    return 0;
  }
  destroy() {
    this.parent = void 0;
    if (this.dom.pmViewDesc == this)
      this.dom.pmViewDesc = void 0;
    for (let i = 0; i < this.children.length; i++)
      this.children[i].destroy();
  }
  posBeforeChild(child) {
    for (let i = 0, pos = this.posAtStart; ; i++) {
      let cur = this.children[i];
      if (cur == child)
        return pos;
      pos += cur.size;
    }
  }
  get posBefore() {
    return this.parent.posBeforeChild(this);
  }
  get posAtStart() {
    return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
  }
  get posAfter() {
    return this.posBefore + this.size;
  }
  get posAtEnd() {
    return this.posAtStart + this.size - 2 * this.border;
  }
  localPosFromDOM(dom, offset, bias) {
    if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
      if (bias < 0) {
        let domBefore, desc;
        if (dom == this.contentDOM) {
          domBefore = dom.childNodes[offset - 1];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domBefore = dom.previousSibling;
        }
        while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))
          domBefore = domBefore.previousSibling;
        return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
      } else {
        let domAfter, desc;
        if (dom == this.contentDOM) {
          domAfter = dom.childNodes[offset];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domAfter = dom.nextSibling;
        }
        while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))
          domAfter = domAfter.nextSibling;
        return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;
      }
    }
    let atEnd;
    if (dom == this.dom && this.contentDOM) {
      atEnd = offset > domIndex(this.contentDOM);
    } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
      atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;
    } else if (this.dom.firstChild) {
      if (offset == 0)
        for (let search = dom; ; search = search.parentNode) {
          if (search == this.dom) {
            atEnd = false;
            break;
          }
          if (search.previousSibling)
            break;
        }
      if (atEnd == null && offset == dom.childNodes.length)
        for (let search = dom; ; search = search.parentNode) {
          if (search == this.dom) {
            atEnd = true;
            break;
          }
          if (search.nextSibling)
            break;
        }
    }
    return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
  }
  nearestDesc(dom, onlyNodes = false) {
    for (let first = true, cur = dom; cur; cur = cur.parentNode) {
      let desc = this.getDesc(cur), nodeDOM;
      if (desc && (!onlyNodes || desc.node)) {
        if (first && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))
          first = false;
        else
          return desc;
      }
    }
  }
  getDesc(dom) {
    let desc = dom.pmViewDesc;
    for (let cur = desc; cur; cur = cur.parent)
      if (cur == this)
        return desc;
  }
  posFromDOM(dom, offset, bias) {
    for (let scan = dom; scan; scan = scan.parentNode) {
      let desc = this.getDesc(scan);
      if (desc)
        return desc.localPosFromDOM(dom, offset, bias);
    }
    return -1;
  }
  // Find the desc for the node after the given pos, if any. (When a
  // parent node overrode rendering, there might not be one.)
  descAt(pos) {
    for (let i = 0, offset = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (offset == pos && end != offset) {
        while (!child.border && child.children.length) {
          for (let i2 = 0; i2 < child.children.length; i2++) {
            let inner = child.children[i2];
            if (inner.size) {
              child = inner;
              break;
            }
          }
        }
        return child;
      }
      if (pos < end)
        return child.descAt(pos - offset - child.border);
      offset = end;
    }
  }
  domFromPos(pos, side) {
    if (!this.contentDOM)
      return { node: this.dom, offset: 0, atom: pos + 1 };
    let i = 0, offset = 0;
    for (let curPos = 0; i < this.children.length; i++) {
      let child = this.children[i], end = curPos + child.size;
      if (end > pos || child instanceof TrailingHackViewDesc) {
        offset = pos - curPos;
        break;
      }
      curPos = end;
    }
    if (offset)
      return this.children[i].domFromPos(offset - this.children[i].border, side);
    for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) {
    }
    if (side <= 0) {
      let prev, enter = true;
      for (; ; i--, enter = false) {
        prev = i ? this.children[i - 1] : null;
        if (!prev || prev.dom.parentNode == this.contentDOM)
          break;
      }
      if (prev && side && enter && !prev.border && !prev.domAtom)
        return prev.domFromPos(prev.size, side);
      return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };
    } else {
      let next, enter = true;
      for (; ; i++, enter = false) {
        next = i < this.children.length ? this.children[i] : null;
        if (!next || next.dom.parentNode == this.contentDOM)
          break;
      }
      if (next && enter && !next.border && !next.domAtom)
        return next.domFromPos(0, side);
      return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };
    }
  }
  // Used to find a DOM range in a single parent for a given changed
  // range.
  parseRange(from2, to, base2 = 0) {
    if (this.children.length == 0)
      return { node: this.contentDOM, from: from2, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
    let fromOffset = -1, toOffset = -1;
    for (let offset = base2, i = 0; ; i++) {
      let child = this.children[i], end = offset + child.size;
      if (fromOffset == -1 && from2 <= end) {
        let childBase = offset + child.border;
        if (from2 >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM))
          return child.parseRange(from2, to, childBase);
        from2 = offset;
        for (let j = i; j > 0; j--) {
          let prev = this.children[j - 1];
          if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
            fromOffset = domIndex(prev.dom) + 1;
            break;
          }
          from2 -= prev.size;
        }
        if (fromOffset == -1)
          fromOffset = 0;
      }
      if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {
        to = end;
        for (let j = i + 1; j < this.children.length; j++) {
          let next = this.children[j];
          if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
            toOffset = domIndex(next.dom);
            break;
          }
          to += next.size;
        }
        if (toOffset == -1)
          toOffset = this.contentDOM.childNodes.length;
        break;
      }
      offset = end;
    }
    return { node: this.contentDOM, from: from2, to, fromOffset, toOffset };
  }
  emptyChildAt(side) {
    if (this.border || !this.contentDOM || !this.children.length)
      return false;
    let child = this.children[side < 0 ? 0 : this.children.length - 1];
    return child.size == 0 || child.emptyChildAt(side);
  }
  domAfterPos(pos) {
    let { node, offset } = this.domFromPos(pos, 0);
    if (node.nodeType != 1 || offset == node.childNodes.length)
      throw new RangeError("No node after pos " + pos);
    return node.childNodes[offset];
  }
  // View descs are responsible for setting any selection that falls
  // entirely inside of them, so that custom implementations can do
  // custom things with the selection. Note that this falls apart when
  // a selection starts in such a node and ends in another, in which
  // case we just use whatever domFromPos produces as a best effort.
  setSelection(anchor, head, view, force = false) {
    let from2 = Math.min(anchor, head), to = Math.max(anchor, head);
    for (let i = 0, offset = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (from2 > offset && to < end)
        return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);
      offset = end;
    }
    let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);
    let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);
    let domSel = view.root.getSelection();
    let selRange = view.domSelectionRange();
    let brKludge = false;
    if ((gecko || safari) && anchor == head) {
      let { node, offset } = anchorDOM;
      if (node.nodeType == 3) {
        brKludge = !!(offset && node.nodeValue[offset - 1] == "\n");
        if (brKludge && offset == node.nodeValue.length) {
          for (let scan = node, after; scan; scan = scan.parentNode) {
            if (after = scan.nextSibling) {
              if (after.nodeName == "BR")
                anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };
              break;
            }
            let desc = scan.pmViewDesc;
            if (desc && desc.node && desc.node.isBlock)
              break;
          }
        }
      } else {
        let prev = node.childNodes[offset - 1];
        brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false");
      }
    }
    if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {
      let after = selRange.focusNode.childNodes[selRange.focusOffset];
      if (after && after.contentEditable == "false")
        force = true;
    }
    if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))
      return;
    let domSelExtended = false;
    if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {
      domSel.collapse(anchorDOM.node, anchorDOM.offset);
      try {
        if (anchor != head)
          domSel.extend(headDOM.node, headDOM.offset);
        domSelExtended = true;
      } catch (_) {
      }
    }
    if (!domSelExtended) {
      if (anchor > head) {
        let tmp = anchorDOM;
        anchorDOM = headDOM;
        headDOM = tmp;
      }
      let range2 = document.createRange();
      range2.setEnd(headDOM.node, headDOM.offset);
      range2.setStart(anchorDOM.node, anchorDOM.offset);
      domSel.removeAllRanges();
      domSel.addRange(range2);
    }
  }
  ignoreMutation(mutation) {
    return !this.contentDOM && mutation.type != "selection";
  }
  get contentLost() {
    return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
  }
  // Remove a subtree of the element tree that has been touched
  // by a DOM change, so that the next update will redraw it.
  markDirty(from2, to) {
    for (let offset = 0, i = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (offset == end ? from2 <= end && to >= offset : from2 < end && to > offset) {
        let startInside = offset + child.border, endInside = end - child.border;
        if (from2 >= startInside && to <= endInside) {
          this.dirty = from2 == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;
          if (from2 == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM))
            child.dirty = NODE_DIRTY;
          else
            child.markDirty(from2 - startInside, to - startInside);
          return;
        } else {
          child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY;
        }
      }
      offset = end;
    }
    this.dirty = CONTENT_DIRTY;
  }
  markParentsDirty() {
    let level = 1;
    for (let node = this.parent; node; node = node.parent, level++) {
      let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;
      if (node.dirty < dirty)
        node.dirty = dirty;
    }
  }
  get domAtom() {
    return false;
  }
  get ignoreForCoords() {
    return false;
  }
  get ignoreForSelection() {
    return false;
  }
  isText(text2) {
    return false;
  }
};
var WidgetViewDesc = class extends ViewDesc {
  constructor(parent, widget, view, pos) {
    let self2, dom = widget.type.toDOM;
    if (typeof dom == "function")
      dom = dom(view, () => {
        if (!self2)
          return pos;
        if (self2.parent)
          return self2.parent.posBeforeChild(self2);
      });
    if (!widget.type.spec.raw) {
      if (dom.nodeType != 1) {
        let wrap2 = document.createElement("span");
        wrap2.appendChild(dom);
        dom = wrap2;
      }
      dom.contentEditable = "false";
      dom.classList.add("ProseMirror-widget");
    }
    super(parent, [], dom, null);
    this.widget = widget;
    this.widget = widget;
    self2 = this;
  }
  matchesWidget(widget) {
    return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
  }
  parseRule() {
    return { ignore: true };
  }
  stopEvent(event) {
    let stop = this.widget.spec.stopEvent;
    return stop ? stop(event) : false;
  }
  ignoreMutation(mutation) {
    return mutation.type != "selection" || this.widget.spec.ignoreSelection;
  }
  destroy() {
    this.widget.type.destroy(this.dom);
    super.destroy();
  }
  get domAtom() {
    return true;
  }
  get ignoreForSelection() {
    return !!this.widget.type.spec.relaxedSide;
  }
  get side() {
    return this.widget.type.side;
  }
};
var CompositionViewDesc = class extends ViewDesc {
  constructor(parent, dom, textDOM, text2) {
    super(parent, [], dom, null);
    this.textDOM = textDOM;
    this.text = text2;
  }
  get size() {
    return this.text.length;
  }
  localPosFromDOM(dom, offset) {
    if (dom != this.textDOM)
      return this.posAtStart + (offset ? this.size : 0);
    return this.posAtStart + offset;
  }
  domFromPos(pos) {
    return { node: this.textDOM, offset: pos };
  }
  ignoreMutation(mut) {
    return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue;
  }
};
var MarkViewDesc = class _MarkViewDesc extends ViewDesc {
  constructor(parent, mark, dom, contentDOM, spec) {
    super(parent, [], dom, contentDOM);
    this.mark = mark;
    this.spec = spec;
  }
  static create(parent, mark, inline, view) {
    let custom = view.nodeViews[mark.type.name];
    let spec = custom && custom(mark, view, inline);
    if (!spec || !spec.dom)
      spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);
    return new _MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);
  }
  parseRule() {
    if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView)
      return null;
    return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
  }
  matchesMark(mark) {
    return this.dirty != NODE_DIRTY && this.mark.eq(mark);
  }
  markDirty(from2, to) {
    super.markDirty(from2, to);
    if (this.dirty != NOT_DIRTY) {
      let parent = this.parent;
      while (!parent.node)
        parent = parent.parent;
      if (parent.dirty < this.dirty)
        parent.dirty = this.dirty;
      this.dirty = NOT_DIRTY;
    }
  }
  slice(from2, to, view) {
    let copy3 = _MarkViewDesc.create(this.parent, this.mark, true, view);
    let nodes = this.children, size = this.size;
    if (to < size)
      nodes = replaceNodes(nodes, to, size, view);
    if (from2 > 0)
      nodes = replaceNodes(nodes, 0, from2, view);
    for (let i = 0; i < nodes.length; i++)
      nodes[i].parent = copy3;
    copy3.children = nodes;
    return copy3;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
};
var NodeViewDesc = class _NodeViewDesc extends ViewDesc {
  constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {
    super(parent, [], dom, contentDOM);
    this.node = node;
    this.outerDeco = outerDeco;
    this.innerDeco = innerDeco;
    this.nodeDOM = nodeDOM;
  }
  // By default, a node is rendered using the `toDOM` method from the
  // node type spec. But client code can use the `nodeViews` spec to
  // supply a custom node view, which can influence various aspects of
  // the way the node works.
  //
  // (Using subclassing for this was intentionally decided against,
  // since it'd require exposing a whole slew of finicky
  // implementation details to the user code that they probably will
  // never need.)
  static create(parent, node, outerDeco, innerDeco, view, pos) {
    let custom = view.nodeViews[node.type.name], descObj;
    let spec = custom && custom(node, view, () => {
      if (!descObj)
        return pos;
      if (descObj.parent)
        return descObj.parent.posBeforeChild(descObj);
    }, outerDeco, innerDeco);
    let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;
    if (node.isText) {
      if (!dom)
        dom = document.createTextNode(node.text);
      else if (dom.nodeType != 3)
        throw new RangeError("Text must be rendered as a DOM text node");
    } else if (!dom) {
      let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);
      ({ dom, contentDOM } = spec2);
    }
    if (!contentDOM && !node.isText && dom.nodeName != "BR") {
      if (!dom.hasAttribute("contenteditable"))
        dom.contentEditable = "false";
      if (node.type.spec.draggable)
        dom.draggable = true;
    }
    let nodeDOM = dom;
    dom = applyOuterDeco(dom, outerDeco, node);
    if (spec)
      return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);
    else if (node.isText)
      return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);
    else
      return new _NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);
  }
  parseRule() {
    if (this.node.type.spec.reparseInView)
      return null;
    let rule = { node: this.node.type.name, attrs: this.node.attrs };
    if (this.node.type.whitespace == "pre")
      rule.preserveWhitespace = "full";
    if (!this.contentDOM) {
      rule.getContent = () => this.node.content;
    } else if (!this.contentLost) {
      rule.contentElement = this.contentDOM;
    } else {
      for (let i = this.children.length - 1; i >= 0; i--) {
        let child = this.children[i];
        if (this.dom.contains(child.dom.parentNode)) {
          rule.contentElement = child.dom.parentNode;
          break;
        }
      }
      if (!rule.contentElement)
        rule.getContent = () => Fragment.empty;
    }
    return rule;
  }
  matchesNode(node, outerDeco, innerDeco) {
    return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
  }
  get size() {
    return this.node.nodeSize;
  }
  get border() {
    return this.node.isLeaf ? 0 : 1;
  }
  // Syncs `this.children` to match `this.node.content` and the local
  // decorations, possibly introducing nesting for marks. Then, in a
  // separate step, syncs the DOM inside `this.contentDOM` to
  // `this.children`.
  updateChildren(view, pos) {
    let inline = this.node.inlineContent, off2 = pos;
    let composition = view.composing ? this.localCompositionInfo(view, pos) : null;
    let localComposition = composition && composition.pos > -1 ? composition : null;
    let compositionInChild = composition && composition.pos < 0;
    let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);
    iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {
      if (widget.spec.marks)
        updater.syncToMarks(widget.spec.marks, inline, view, i);
      else if (widget.type.side >= 0 && !insideNode)
        updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);
      updater.placeWidget(widget, view, off2);
    }, (child, outerDeco, innerDeco, i) => {
      updater.syncToMarks(child.marks, inline, view, i);
      let compIndex;
      if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;
      else if (compositionInChild && view.state.selection.from > off2 && view.state.selection.to < off2 + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;
      else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off2)) ;
      else {
        updater.addNode(child, outerDeco, innerDeco, view, off2);
      }
      off2 += child.nodeSize;
    });
    updater.syncToMarks([], inline, view, 0);
    if (this.node.isTextblock)
      updater.addTextblockHacks();
    updater.destroyRest();
    if (updater.changed || this.dirty == CONTENT_DIRTY) {
      if (localComposition)
        this.protectLocalComposition(view, localComposition);
      renderDescs(this.contentDOM, this.children, view);
      if (ios)
        iosHacks(this.dom);
    }
  }
  localCompositionInfo(view, pos) {
    let { from: from2, to } = view.state.selection;
    if (!(view.state.selection instanceof TextSelection) || from2 < pos || to > pos + this.node.content.size)
      return null;
    let textNode = view.input.compositionNode;
    if (!textNode || !this.dom.contains(textNode.parentNode))
      return null;
    if (this.node.inlineContent) {
      let text2 = textNode.nodeValue;
      let textPos = findTextInFragment(this.node.content, text2, from2 - pos, to - pos);
      return textPos < 0 ? null : { node: textNode, pos: textPos, text: text2 };
    } else {
      return { node: textNode, pos: -1, text: "" };
    }
  }
  protectLocalComposition(view, { node, pos, text: text2 }) {
    if (this.getDesc(node))
      return;
    let topNode = node;
    for (; ; topNode = topNode.parentNode) {
      if (topNode.parentNode == this.contentDOM)
        break;
      while (topNode.previousSibling)
        topNode.parentNode.removeChild(topNode.previousSibling);
      while (topNode.nextSibling)
        topNode.parentNode.removeChild(topNode.nextSibling);
      if (topNode.pmViewDesc)
        topNode.pmViewDesc = void 0;
    }
    let desc = new CompositionViewDesc(this, topNode, node, text2);
    view.input.compositionNodes.push(desc);
    this.children = replaceNodes(this.children, pos, pos + text2.length, view, desc);
  }
  // If this desc must be updated to match the given node decoration,
  // do so and return true.
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node))
      return false;
    this.updateInner(node, outerDeco, innerDeco, view);
    return true;
  }
  updateInner(node, outerDeco, innerDeco, view) {
    this.updateOuterDeco(outerDeco);
    this.node = node;
    this.innerDeco = innerDeco;
    if (this.contentDOM)
      this.updateChildren(view, this.posAtStart);
    this.dirty = NOT_DIRTY;
  }
  updateOuterDeco(outerDeco) {
    if (sameOuterDeco(outerDeco, this.outerDeco))
      return;
    let needsWrap = this.nodeDOM.nodeType != 1;
    let oldDOM = this.dom;
    this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));
    if (this.dom != oldDOM) {
      oldDOM.pmViewDesc = void 0;
      this.dom.pmViewDesc = this;
    }
    this.outerDeco = outerDeco;
  }
  // Mark this node as being the selected node.
  selectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.add("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.nodeDOM.draggable = true;
    }
  }
  // Remove selected node marking from this node.
  deselectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.remove("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.nodeDOM.removeAttribute("draggable");
    }
  }
  get domAtom() {
    return this.node.isAtom;
  }
};
function docViewDesc(doc3, outerDeco, innerDeco, dom, view) {
  applyOuterDeco(dom, outerDeco, doc3);
  let docView = new NodeViewDesc(void 0, doc3, outerDeco, innerDeco, dom, dom, dom, view, 0);
  if (docView.contentDOM)
    docView.updateChildren(view, 0);
  return docView;
}
var TextViewDesc = class _TextViewDesc extends NodeViewDesc {
  constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {
    super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);
  }
  parseRule() {
    let skip = this.nodeDOM.parentNode;
    while (skip && skip != this.dom && !skip.pmIsDeco)
      skip = skip.parentNode;
    return { skip: skip || true };
  }
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node))
      return false;
    this.updateOuterDeco(outerDeco);
    if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
      this.nodeDOM.nodeValue = node.text;
      if (view.trackWrites == this.nodeDOM)
        view.trackWrites = null;
    }
    this.node = node;
    this.dirty = NOT_DIRTY;
    return true;
  }
  inParent() {
    let parentDOM = this.parent.contentDOM;
    for (let n = this.nodeDOM; n; n = n.parentNode)
      if (n == parentDOM)
        return true;
    return false;
  }
  domFromPos(pos) {
    return { node: this.nodeDOM, offset: pos };
  }
  localPosFromDOM(dom, offset, bias) {
    if (dom == this.nodeDOM)
      return this.posAtStart + Math.min(offset, this.node.text.length);
    return super.localPosFromDOM(dom, offset, bias);
  }
  ignoreMutation(mutation) {
    return mutation.type != "characterData" && mutation.type != "selection";
  }
  slice(from2, to, view) {
    let node = this.node.cut(from2, to), dom = document.createTextNode(node.text);
    return new _TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);
  }
  markDirty(from2, to) {
    super.markDirty(from2, to);
    if (this.dom != this.nodeDOM && (from2 == 0 || to == this.nodeDOM.nodeValue.length))
      this.dirty = NODE_DIRTY;
  }
  get domAtom() {
    return false;
  }
  isText(text2) {
    return this.node.text == text2;
  }
};
var TrailingHackViewDesc = class extends ViewDesc {
  parseRule() {
    return { ignore: true };
  }
  matchesHack(nodeName) {
    return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName;
  }
  get domAtom() {
    return true;
  }
  get ignoreForCoords() {
    return this.dom.nodeName == "IMG";
  }
};
var CustomNodeViewDesc = class extends NodeViewDesc {
  constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {
    super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);
    this.spec = spec;
  }
  // A custom `update` method gets to decide whether the update goes
  // through. If it does, and there's a `contentDOM` node, our logic
  // updates the children.
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY)
      return false;
    if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {
      let result = this.spec.update(node, outerDeco, innerDeco);
      if (result)
        this.updateInner(node, outerDeco, innerDeco, view);
      return result;
    } else if (!this.contentDOM && !node.isLeaf) {
      return false;
    } else {
      return super.update(node, outerDeco, innerDeco, view);
    }
  }
  selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
  }
  deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
  }
  setSelection(anchor, head, view, force) {
    this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
  stopEvent(event) {
    return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
};
function renderDescs(parentDOM, descs, view) {
  let dom = parentDOM.firstChild, written = false;
  for (let i = 0; i < descs.length; i++) {
    let desc = descs[i], childDOM = desc.dom;
    if (childDOM.parentNode == parentDOM) {
      while (childDOM != dom) {
        dom = rm(dom);
        written = true;
      }
      dom = dom.nextSibling;
    } else {
      written = true;
      parentDOM.insertBefore(childDOM, dom);
    }
    if (desc instanceof MarkViewDesc) {
      let pos = dom ? dom.previousSibling : parentDOM.lastChild;
      renderDescs(desc.contentDOM, desc.children, view);
      dom = pos ? pos.nextSibling : parentDOM.firstChild;
    }
  }
  while (dom) {
    dom = rm(dom);
    written = true;
  }
  if (written && view.trackWrites == parentDOM)
    view.trackWrites = null;
}
var OuterDecoLevel = function(nodeName) {
  if (nodeName)
    this.nodeName = nodeName;
};
OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null);
var noDeco = [new OuterDecoLevel()];
function computeOuterDeco(outerDeco, node, needsWrap) {
  if (outerDeco.length == 0)
    return noDeco;
  let top2 = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top2];
  for (let i = 0; i < outerDeco.length; i++) {
    let attrs = outerDeco[i].type.attrs;
    if (!attrs)
      continue;
    if (attrs.nodeName)
      result.push(top2 = new OuterDecoLevel(attrs.nodeName));
    for (let name in attrs) {
      let val = attrs[name];
      if (val == null)
        continue;
      if (needsWrap && result.length == 1)
        result.push(top2 = new OuterDecoLevel(node.isInline ? "span" : "div"));
      if (name == "class")
        top2.class = (top2.class ? top2.class + " " : "") + val;
      else if (name == "style")
        top2.style = (top2.style ? top2.style + ";" : "") + val;
      else if (name != "nodeName")
        top2[name] = val;
    }
  }
  return result;
}
function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
  if (prevComputed == noDeco && curComputed == noDeco)
    return nodeDOM;
  let curDOM = nodeDOM;
  for (let i = 0; i < curComputed.length; i++) {
    let deco = curComputed[i], prev = prevComputed[i];
    if (i) {
      let parent;
      if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {
        curDOM = parent;
      } else {
        parent = document.createElement(deco.nodeName);
        parent.pmIsDeco = true;
        parent.appendChild(curDOM);
        prev = noDeco[0];
        curDOM = parent;
      }
    }
    patchAttributes(curDOM, prev || noDeco[0], deco);
  }
  return curDOM;
}
function patchAttributes(dom, prev, cur) {
  for (let name in prev)
    if (name != "class" && name != "style" && name != "nodeName" && !(name in cur))
      dom.removeAttribute(name);
  for (let name in cur)
    if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name])
      dom.setAttribute(name, cur[name]);
  if (prev.class != cur.class) {
    let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : [];
    let curList = cur.class ? cur.class.split(" ").filter(Boolean) : [];
    for (let i = 0; i < prevList.length; i++)
      if (curList.indexOf(prevList[i]) == -1)
        dom.classList.remove(prevList[i]);
    for (let i = 0; i < curList.length; i++)
      if (prevList.indexOf(curList[i]) == -1)
        dom.classList.add(curList[i]);
    if (dom.classList.length == 0)
      dom.removeAttribute("class");
  }
  if (prev.style != cur.style) {
    if (prev.style) {
      let prop2 = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m;
      while (m = prop2.exec(prev.style))
        dom.style.removeProperty(m[1]);
    }
    if (cur.style)
      dom.style.cssText += cur.style;
  }
}
function applyOuterDeco(dom, deco, node) {
  return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));
}
function sameOuterDeco(a, b) {
  if (a.length != b.length)
    return false;
  for (let i = 0; i < a.length; i++)
    if (!a[i].type.eq(b[i].type))
      return false;
  return true;
}
function rm(dom) {
  let next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
}
var ViewTreeUpdater = class {
  constructor(top2, lock, view) {
    this.lock = lock;
    this.view = view;
    this.index = 0;
    this.stack = [];
    this.changed = false;
    this.top = top2;
    this.preMatch = preMatch(top2.node.content, top2);
  }
  // Destroy and remove the children between the given indices in
  // `this.top`.
  destroyBetween(start, end) {
    if (start == end)
      return;
    for (let i = start; i < end; i++)
      this.top.children[i].destroy();
    this.top.children.splice(start, end - start);
    this.changed = true;
  }
  // Destroy all remaining children in `this.top`.
  destroyRest() {
    this.destroyBetween(this.index, this.top.children.length);
  }
  // Sync the current stack of mark descs with the given array of
  // marks, reusing existing mark descs when possible.
  syncToMarks(marks, inline, view, parentIndex) {
    let keep = 0, depth = this.stack.length >> 1;
    let maxKeep = Math.min(depth, marks.length);
    while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
      keep++;
    while (keep < depth) {
      this.destroyRest();
      this.top.dirty = NOT_DIRTY;
      this.index = this.stack.pop();
      this.top = this.stack.pop();
      depth--;
    }
    while (depth < marks.length) {
      this.stack.push(this.top, this.index + 1);
      let found2 = -1, scanTo = this.top.children.length;
      if (parentIndex < this.preMatch.index)
        scanTo = Math.min(this.index + 3, scanTo);
      for (let i = this.index; i < scanTo; i++) {
        let next = this.top.children[i];
        if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {
          found2 = i;
          break;
        }
      }
      if (found2 > -1) {
        if (found2 > this.index) {
          this.changed = true;
          this.destroyBetween(this.index, found2);
        }
        this.top = this.top.children[this.index];
      } else {
        let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);
        this.top.children.splice(this.index, 0, markDesc);
        this.top = markDesc;
        this.changed = true;
      }
      this.index = 0;
      depth++;
    }
  }
  // Try to find a node desc matching the given data. Skip over it and
  // return true when successful.
  findNodeMatch(node, outerDeco, innerDeco, index2) {
    let found2 = -1, targetDesc;
    if (index2 >= this.preMatch.index && (targetDesc = this.preMatch.matches[index2 - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) {
      found2 = this.top.children.indexOf(targetDesc, this.index);
    } else {
      for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {
        let child = this.top.children[i];
        if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {
          found2 = i;
          break;
        }
      }
    }
    if (found2 < 0)
      return false;
    this.destroyBetween(this.index, found2);
    this.index++;
    return true;
  }
  updateNodeAt(node, outerDeco, innerDeco, index2, view) {
    let child = this.top.children[index2];
    if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)
      child.dirty = CONTENT_DIRTY;
    if (!child.update(node, outerDeco, innerDeco, view))
      return false;
    this.destroyBetween(this.index, index2);
    this.index++;
    return true;
  }
  findIndexWithChild(domNode) {
    for (; ; ) {
      let parent = domNode.parentNode;
      if (!parent)
        return -1;
      if (parent == this.top.contentDOM) {
        let desc = domNode.pmViewDesc;
        if (desc)
          for (let i = this.index; i < this.top.children.length; i++) {
            if (this.top.children[i] == desc)
              return i;
          }
        return -1;
      }
      domNode = parent;
    }
  }
  // Try to update the next node, if any, to the given data. Checks
  // pre-matches to avoid overwriting nodes that could still be used.
  updateNextNode(node, outerDeco, innerDeco, view, index2, pos) {
    for (let i = this.index; i < this.top.children.length; i++) {
      let next = this.top.children[i];
      if (next instanceof NodeViewDesc) {
        let preMatch2 = this.preMatch.matched.get(next);
        if (preMatch2 != null && preMatch2 != index2)
          return false;
        let nextDOM = next.dom, updated;
        let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));
        if (!locked && next.update(node, outerDeco, innerDeco, view)) {
          this.destroyBetween(this.index, i);
          if (next.dom != nextDOM)
            this.changed = true;
          this.index++;
          return true;
        } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {
          this.destroyBetween(this.index, i);
          this.top.children[this.index] = updated;
          if (updated.contentDOM) {
            updated.dirty = CONTENT_DIRTY;
            updated.updateChildren(view, pos + 1);
            updated.dirty = NOT_DIRTY;
          }
          this.changed = true;
          this.index++;
          return true;
        }
        break;
      }
    }
    return false;
  }
  // When a node with content is replaced by a different node with
  // identical content, move over its children.
  recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {
    if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))
      return null;
    let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
    if (wrapper.contentDOM) {
      wrapper.children = next.children;
      next.children = [];
      for (let ch of wrapper.children)
        ch.parent = wrapper;
    }
    next.destroy();
    return wrapper;
  }
  // Insert the node as a newly created node desc.
  addNode(node, outerDeco, innerDeco, view, pos) {
    let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
    if (desc.contentDOM)
      desc.updateChildren(view, pos + 1);
    this.top.children.splice(this.index++, 0, desc);
    this.changed = true;
  }
  placeWidget(widget, view, pos) {
    let next = this.index < this.top.children.length ? this.top.children[this.index] : null;
    if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {
      this.index++;
    } else {
      let desc = new WidgetViewDesc(this.top, widget, view, pos);
      this.top.children.splice(this.index++, 0, desc);
      this.changed = true;
    }
  }
  // Make sure a textblock looks and behaves correctly in
  // contentEditable.
  addTextblockHacks() {
    let lastChild = this.top.children[this.index - 1], parent = this.top;
    while (lastChild instanceof MarkViewDesc) {
      parent = lastChild;
      lastChild = parent.children[parent.children.length - 1];
    }
    if (!lastChild || // Empty textblock
    !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) {
      if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false")
        this.addHackNode("IMG", parent);
      this.addHackNode("BR", this.top);
    }
  }
  addHackNode(nodeName, parent) {
    if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {
      this.index++;
    } else {
      let dom = document.createElement(nodeName);
      if (nodeName == "IMG") {
        dom.className = "ProseMirror-separator";
        dom.alt = "";
      }
      if (nodeName == "BR")
        dom.className = "ProseMirror-trailingBreak";
      let hack = new TrailingHackViewDesc(this.top, [], dom, null);
      if (parent != this.top)
        parent.children.push(hack);
      else
        parent.children.splice(this.index++, 0, hack);
      this.changed = true;
    }
  }
  isLocked(node) {
    return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));
  }
};
function preMatch(frag, parentDesc) {
  let curDesc = parentDesc, descI = curDesc.children.length;
  let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches3 = [];
  outer: while (fI > 0) {
    let desc;
    for (; ; ) {
      if (descI) {
        let next = curDesc.children[descI - 1];
        if (next instanceof MarkViewDesc) {
          curDesc = next;
          descI = next.children.length;
        } else {
          desc = next;
          descI--;
          break;
        }
      } else if (curDesc == parentDesc) {
        break outer;
      } else {
        descI = curDesc.parent.children.indexOf(curDesc);
        curDesc = curDesc.parent;
      }
    }
    let node = desc.node;
    if (!node)
      continue;
    if (node != frag.child(fI - 1))
      break;
    --fI;
    matched.set(desc, fI);
    matches3.push(desc);
  }
  return { index: fI, matched, matches: matches3.reverse() };
}
function compareSide(a, b) {
  return a.type.side - b.type.side;
}
function iterDeco(parent, deco, onWidget, onNode) {
  let locals = deco.locals(parent), offset = 0;
  if (locals.length == 0) {
    for (let i = 0; i < parent.childCount; i++) {
      let child = parent.child(i);
      onNode(child, locals, deco.forChild(offset, child), i);
      offset += child.nodeSize;
    }
    return;
  }
  let decoIndex = 0, active = [], restNode = null;
  for (let parentIndex = 0; ; ) {
    let widget, widgets;
    while (decoIndex < locals.length && locals[decoIndex].to == offset) {
      let next = locals[decoIndex++];
      if (next.widget) {
        if (!widget)
          widget = next;
        else
          (widgets || (widgets = [widget])).push(next);
      }
    }
    if (widget) {
      if (widgets) {
        widgets.sort(compareSide);
        for (let i = 0; i < widgets.length; i++)
          onWidget(widgets[i], parentIndex, !!restNode);
      } else {
        onWidget(widget, parentIndex, !!restNode);
      }
    }
    let child, index2;
    if (restNode) {
      index2 = -1;
      child = restNode;
      restNode = null;
    } else if (parentIndex < parent.childCount) {
      index2 = parentIndex;
      child = parent.child(parentIndex++);
    } else {
      break;
    }
    for (let i = 0; i < active.length; i++)
      if (active[i].to <= offset)
        active.splice(i--, 1);
    while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)
      active.push(locals[decoIndex++]);
    let end = offset + child.nodeSize;
    if (child.isText) {
      let cutAt = end;
      if (decoIndex < locals.length && locals[decoIndex].from < cutAt)
        cutAt = locals[decoIndex].from;
      for (let i = 0; i < active.length; i++)
        if (active[i].to < cutAt)
          cutAt = active[i].to;
      if (cutAt < end) {
        restNode = child.cut(cutAt - offset);
        child = child.cut(0, cutAt - offset);
        end = cutAt;
        index2 = -1;
      }
    } else {
      while (decoIndex < locals.length && locals[decoIndex].to < end)
        decoIndex++;
    }
    let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice();
    onNode(child, outerDeco, deco.forChild(offset, child), index2);
    offset = end;
  }
}
function iosHacks(dom) {
  if (dom.nodeName == "UL" || dom.nodeName == "OL") {
    let oldCSS = dom.style.cssText;
    dom.style.cssText = oldCSS + "; list-style: square !important";
    window.getComputedStyle(dom).listStyle;
    dom.style.cssText = oldCSS;
  }
}
function findTextInFragment(frag, text2, from2, to) {
  for (let i = 0, pos = 0; i < frag.childCount && pos <= to; ) {
    let child = frag.child(i++), childStart = pos;
    pos += child.nodeSize;
    if (!child.isText)
      continue;
    let str = child.text;
    while (i < frag.childCount) {
      let next = frag.child(i++);
      pos += next.nodeSize;
      if (!next.isText)
        break;
      str += next.text;
    }
    if (pos >= from2) {
      if (pos >= to && str.slice(to - text2.length - childStart, to - childStart) == text2)
        return to - text2.length;
      let found2 = childStart < to ? str.lastIndexOf(text2, to - childStart - 1) : -1;
      if (found2 >= 0 && found2 + text2.length + childStart >= from2)
        return childStart + found2;
      if (from2 == to && str.length >= to + text2.length - childStart && str.slice(to - childStart, to - childStart + text2.length) == text2)
        return to;
    }
  }
  return -1;
}
function replaceNodes(nodes, from2, to, view, replacement) {
  let result = [];
  for (let i = 0, off2 = 0; i < nodes.length; i++) {
    let child = nodes[i], start = off2, end = off2 += child.size;
    if (start >= to || end <= from2) {
      result.push(child);
    } else {
      if (start < from2)
        result.push(child.slice(0, from2 - start, view));
      if (replacement) {
        result.push(replacement);
        replacement = void 0;
      }
      if (end > to)
        result.push(child.slice(to - start, child.size, view));
    }
  }
  return result;
}
function selectionFromDOM(view, origin = null) {
  let domSel = view.domSelectionRange(), doc3 = view.state.doc;
  if (!domSel.focusNode)
    return null;
  let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;
  let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);
  if (head < 0)
    return null;
  let $head = doc3.resolve(head), anchor, selection;
  if (selectionCollapsed(domSel)) {
    anchor = head;
    while (nearestDesc && !nearestDesc.node)
      nearestDesc = nearestDesc.parent;
    let nearestDescNode = nearestDesc.node;
    if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
      let pos = nearestDesc.posBefore;
      selection = new NodeSelection(head == pos ? $head : doc3.resolve(pos));
    }
  } else {
    if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {
      let min = head, max = head;
      for (let i = 0; i < domSel.rangeCount; i++) {
        let range2 = domSel.getRangeAt(i);
        min = Math.min(min, view.docView.posFromDOM(range2.startContainer, range2.startOffset, 1));
        max = Math.max(max, view.docView.posFromDOM(range2.endContainer, range2.endOffset, -1));
      }
      if (min < 0)
        return null;
      [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];
      $head = doc3.resolve(head);
    } else {
      anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);
    }
    if (anchor < 0)
      return null;
  }
  let $anchor = doc3.resolve(anchor);
  if (!selection) {
    let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
    selection = selectionBetween(view, $anchor, $head, bias);
  }
  return selection;
}
function editorOwnsSelection(view) {
  return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);
}
function selectionToDOM(view, force = false) {
  let sel = view.state.selection;
  syncNodeSelection(view, sel);
  if (!editorOwnsSelection(view))
    return;
  if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {
    let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;
    if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {
      view.input.mouseDown.delayedSelectionSync = true;
      view.domObserver.setCurSelection();
      return;
    }
  }
  view.domObserver.disconnectSelection();
  if (view.cursorWrapper) {
    selectCursorWrapper(view);
  } else {
    let { anchor, head } = sel, resetEditableFrom, resetEditableTo;
    if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {
      if (!sel.$from.parent.inlineContent)
        resetEditableFrom = temporarilyEditableNear(view, sel.from);
      if (!sel.empty && !sel.$from.parent.inlineContent)
        resetEditableTo = temporarilyEditableNear(view, sel.to);
    }
    view.docView.setSelection(anchor, head, view, force);
    if (brokenSelectBetweenUneditable) {
      if (resetEditableFrom)
        resetEditable(resetEditableFrom);
      if (resetEditableTo)
        resetEditable(resetEditableTo);
    }
    if (sel.visible) {
      view.dom.classList.remove("ProseMirror-hideselection");
    } else {
      view.dom.classList.add("ProseMirror-hideselection");
      if ("onselectionchange" in document)
        removeClassOnSelectionChange(view);
    }
  }
  view.domObserver.setCurSelection();
  view.domObserver.connectSelection();
}
var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;
function temporarilyEditableNear(view, pos) {
  let { node, offset } = view.docView.domFromPos(pos, 0);
  let after = offset < node.childNodes.length ? node.childNodes[offset] : null;
  let before = offset ? node.childNodes[offset - 1] : null;
  if (safari && after && after.contentEditable == "false")
    return setEditable(after);
  if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) {
    if (after)
      return setEditable(after);
    else if (before)
      return setEditable(before);
  }
}
function setEditable(element) {
  element.contentEditable = "true";
  if (safari && element.draggable) {
    element.draggable = false;
    element.wasDraggable = true;
  }
  return element;
}
function resetEditable(element) {
  element.contentEditable = "false";
  if (element.wasDraggable) {
    element.draggable = true;
    element.wasDraggable = null;
  }
}
function removeClassOnSelectionChange(view) {
  let doc3 = view.dom.ownerDocument;
  doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard);
  let domSel = view.domSelectionRange();
  let node = domSel.anchorNode, offset = domSel.anchorOffset;
  doc3.addEventListener("selectionchange", view.input.hideSelectionGuard = () => {
    if (domSel.anchorNode != node || domSel.anchorOffset != offset) {
      doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard);
      setTimeout(() => {
        if (!editorOwnsSelection(view) || view.state.selection.visible)
          view.dom.classList.remove("ProseMirror-hideselection");
      }, 20);
    }
  });
}
function selectCursorWrapper(view) {
  let domSel = view.domSelection();
  if (!domSel)
    return;
  let node = view.cursorWrapper.dom, img = node.nodeName == "IMG";
  if (img)
    domSel.collapse(node.parentNode, domIndex(node) + 1);
  else
    domSel.collapse(node, 0);
  if (!img && !view.state.selection.visible && ie && ie_version <= 11) {
    node.disabled = true;
    node.disabled = false;
  }
}
function syncNodeSelection(view, sel) {
  if (sel instanceof NodeSelection) {
    let desc = view.docView.descAt(sel.from);
    if (desc != view.lastSelectedViewDesc) {
      clearNodeSelection(view);
      if (desc)
        desc.selectNode();
      view.lastSelectedViewDesc = desc;
    }
  } else {
    clearNodeSelection(view);
  }
}
function clearNodeSelection(view) {
  if (view.lastSelectedViewDesc) {
    if (view.lastSelectedViewDesc.parent)
      view.lastSelectedViewDesc.deselectNode();
    view.lastSelectedViewDesc = void 0;
  }
}
function selectionBetween(view, $anchor, $head, bias) {
  return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias);
}
function hasFocusAndSelection(view) {
  if (view.editable && !view.hasFocus())
    return false;
  return hasSelection(view);
}
function hasSelection(view) {
  let sel = view.domSelectionRange();
  if (!sel.anchorNode)
    return false;
  try {
    return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));
  } catch (_) {
    return false;
  }
}
function anchorInRightPlace(view) {
  let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);
  let domSel = view.domSelectionRange();
  return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
}
function moveSelectionBlock(state, dir) {
  let { $anchor, $head } = state.selection;
  let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
  let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
  return $start && Selection.findFrom($start, dir);
}
function apply(view, sel) {
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
  return true;
}
function selectHorizontally(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection) {
    if (mods.indexOf("s") > -1) {
      let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;
      if (!node || node.isText || !node.isLeaf)
        return false;
      let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));
      return apply(view, new TextSelection(sel.$anchor, $newHead));
    } else if (!sel.empty) {
      return false;
    } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
      let next = moveSelectionBlock(view.state, dir);
      if (next && next instanceof NodeSelection)
        return apply(view, next);
      return false;
    } else if (!(mac && mods.indexOf("m") > -1)) {
      let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;
      if (!node || node.isText)
        return false;
      let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;
      if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))
        return false;
      if (NodeSelection.isSelectable(node)) {
        return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));
      } else if (webkit) {
        return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));
      } else {
        return false;
      }
    }
  } else if (sel instanceof NodeSelection && sel.node.isInline) {
    return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));
  } else {
    let next = moveSelectionBlock(view.state, dir);
    if (next)
      return apply(view, next);
    return false;
  }
}
function nodeLen(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function isIgnorable(dom, dir) {
  let desc = dom.pmViewDesc;
  return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR");
}
function skipIgnoredNodes(view, dir) {
  return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);
}
function skipIgnoredNodesBefore(view) {
  let sel = view.domSelectionRange();
  let node = sel.focusNode, offset = sel.focusOffset;
  if (!node)
    return;
  let moveNode, moveOffset, force = false;
  if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))
    force = true;
  for (; ; ) {
    if (offset > 0) {
      if (node.nodeType != 1) {
        break;
      } else {
        let before = node.childNodes[offset - 1];
        if (isIgnorable(before, -1)) {
          moveNode = node;
          moveOffset = --offset;
        } else if (before.nodeType == 3) {
          node = before;
          offset = node.nodeValue.length;
        } else
          break;
      }
    } else if (isBlockNode(node)) {
      break;
    } else {
      let prev = node.previousSibling;
      while (prev && isIgnorable(prev, -1)) {
        moveNode = node.parentNode;
        moveOffset = domIndex(prev);
        prev = prev.previousSibling;
      }
      if (!prev) {
        node = node.parentNode;
        if (node == view.dom)
          break;
        offset = 0;
      } else {
        node = prev;
        offset = nodeLen(node);
      }
    }
  }
  if (force)
    setSelFocus(view, node, offset);
  else if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
function skipIgnoredNodesAfter(view) {
  let sel = view.domSelectionRange();
  let node = sel.focusNode, offset = sel.focusOffset;
  if (!node)
    return;
  let len = nodeLen(node);
  let moveNode, moveOffset;
  for (; ; ) {
    if (offset < len) {
      if (node.nodeType != 1)
        break;
      let after = node.childNodes[offset];
      if (isIgnorable(after, 1)) {
        moveNode = node;
        moveOffset = ++offset;
      } else
        break;
    } else if (isBlockNode(node)) {
      break;
    } else {
      let next = node.nextSibling;
      while (next && isIgnorable(next, 1)) {
        moveNode = next.parentNode;
        moveOffset = domIndex(next) + 1;
        next = next.nextSibling;
      }
      if (!next) {
        node = node.parentNode;
        if (node == view.dom)
          break;
        offset = len = 0;
      } else {
        node = next;
        offset = 0;
        len = nodeLen(node);
      }
    }
  }
  if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
function isBlockNode(dom) {
  let desc = dom.pmViewDesc;
  return desc && desc.node && desc.node.isBlock;
}
function textNodeAfter(node, offset) {
  while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
  while (node && offset < node.childNodes.length) {
    let next = node.childNodes[offset];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node = next;
    offset = 0;
  }
}
function textNodeBefore(node, offset) {
  while (node && !offset && !hasBlockDesc(node)) {
    offset = domIndex(node);
    node = node.parentNode;
  }
  while (node && offset) {
    let next = node.childNodes[offset - 1];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node = next;
    offset = node.childNodes.length;
  }
}
function setSelFocus(view, node, offset) {
  if (node.nodeType != 3) {
    let before, after;
    if (after = textNodeAfter(node, offset)) {
      node = after;
      offset = 0;
    } else if (before = textNodeBefore(node, offset)) {
      node = before;
      offset = before.nodeValue.length;
    }
  }
  let sel = view.domSelection();
  if (!sel)
    return;
  if (selectionCollapsed(sel)) {
    let range2 = document.createRange();
    range2.setEnd(node, offset);
    range2.setStart(node, offset);
    sel.removeAllRanges();
    sel.addRange(range2);
  } else if (sel.extend) {
    sel.extend(node, offset);
  }
  view.domObserver.setCurSelection();
  let { state } = view;
  setTimeout(() => {
    if (view.state == state)
      selectionToDOM(view);
  }, 50);
}
function findDirection(view, pos) {
  let $pos = view.state.doc.resolve(pos);
  if (!(chrome || windows) && $pos.parent.inlineContent) {
    let coords = view.coordsAtPos(pos);
    if (pos > $pos.start()) {
      let before = view.coordsAtPos(pos - 1);
      let mid2 = (before.top + before.bottom) / 2;
      if (mid2 > coords.top && mid2 < coords.bottom && Math.abs(before.left - coords.left) > 1)
        return before.left < coords.left ? "ltr" : "rtl";
    }
    if (pos < $pos.end()) {
      let after = view.coordsAtPos(pos + 1);
      let mid2 = (after.top + after.bottom) / 2;
      if (mid2 > coords.top && mid2 < coords.bottom && Math.abs(after.left - coords.left) > 1)
        return after.left > coords.left ? "ltr" : "rtl";
    }
  }
  let computed = getComputedStyle(view.dom).direction;
  return computed == "rtl" ? "rtl" : "ltr";
}
function selectVertically(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1)
    return false;
  if (mac && mods.indexOf("m") > -1)
    return false;
  let { $from, $to } = sel;
  if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
    let next = moveSelectionBlock(view.state, dir);
    if (next && next instanceof NodeSelection)
      return apply(view, next);
  }
  if (!$from.parent.inlineContent) {
    let side = dir < 0 ? $from : $to;
    let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);
    return beyond ? apply(view, beyond) : false;
  }
  return false;
}
function stopNativeHorizontalDelete(view, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return true;
  let { $head, $anchor, empty: empty3 } = view.state.selection;
  if (!$head.sameParent($anchor))
    return true;
  if (!empty3)
    return false;
  if (view.endOfTextblock(dir > 0 ? "forward" : "backward"))
    return true;
  let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);
  if (nextNode && !nextNode.isText) {
    let tr = view.state.tr;
    if (dir < 0)
      tr.delete($head.pos - nextNode.nodeSize, $head.pos);
    else
      tr.delete($head.pos, $head.pos + nextNode.nodeSize);
    view.dispatch(tr);
    return true;
  }
  return false;
}
function switchEditable(view, node, state) {
  view.domObserver.stop();
  node.contentEditable = state;
  view.domObserver.start();
}
function safariDownArrowBug(view) {
  if (!safari || view.state.selection.$head.parentOffset > 0)
    return false;
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") {
    let child = focusNode.firstChild;
    switchEditable(view, child, "true");
    setTimeout(() => switchEditable(view, child, "false"), 20);
  }
  return false;
}
function getMods(event) {
  let result = "";
  if (event.ctrlKey)
    result += "c";
  if (event.metaKey)
    result += "m";
  if (event.altKey)
    result += "a";
  if (event.shiftKey)
    result += "s";
  return result;
}
function captureKeyDown(view, event) {
  let code2 = event.keyCode, mods = getMods(event);
  if (code2 == 8 || mac && code2 == 72 && mods == "c") {
    return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);
  } else if (code2 == 46 && !event.shiftKey || mac && code2 == 68 && mods == "c") {
    return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);
  } else if (code2 == 13 || code2 == 27) {
    return true;
  } else if (code2 == 37 || mac && code2 == 66 && mods == "c") {
    let dir = code2 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code2 == 39 || mac && code2 == 70 && mods == "c") {
    let dir = code2 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code2 == 38 || mac && code2 == 80 && mods == "c") {
    return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);
  } else if (code2 == 40 || mac && code2 == 78 && mods == "c") {
    return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);
  } else if (mods == (mac ? "m" : "c") && (code2 == 66 || code2 == 73 || code2 == 89 || code2 == 90)) {
    return true;
  }
  return false;
}
function serializeForClipboard(view, slice2) {
  view.someProp("transformCopied", (f) => {
    slice2 = f(slice2, view);
  });
  let context = [], { content, openStart, openEnd } = slice2;
  while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {
    openStart--;
    openEnd--;
    let node = content.firstChild;
    context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);
    content = node.content;
  }
  let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema);
  let doc3 = detachedDoc(), wrap2 = doc3.createElement("div");
  wrap2.appendChild(serializer.serializeFragment(content, { document: doc3 }));
  let firstChild = wrap2.firstChild, needsWrap, wrappers = 0;
  while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
    for (let i = needsWrap.length - 1; i >= 0; i--) {
      let wrapper = doc3.createElement(needsWrap[i]);
      while (wrap2.firstChild)
        wrapper.appendChild(wrap2.firstChild);
      wrap2.appendChild(wrapper);
      wrappers++;
    }
    firstChild = wrap2.firstChild;
  }
  if (firstChild && firstChild.nodeType == 1)
    firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`);
  let text2 = view.someProp("clipboardTextSerializer", (f) => f(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n");
  return { dom: wrap2, text: text2, slice: slice2 };
}
function parseFromClipboard(view, text2, html2, plainText, $context) {
  let inCode = $context.parent.type.spec.code;
  let dom, slice2;
  if (!html2 && !text2)
    return null;
  let asText = !!text2 && (plainText || inCode || !html2);
  if (asText) {
    view.someProp("transformPastedText", (f) => {
      text2 = f(text2, inCode || plainText, view);
    });
    if (inCode) {
      slice2 = new Slice(Fragment.from(view.state.schema.text(text2.replace(/\r\n?/g, "\n"))), 0, 0);
      view.someProp("transformPasted", (f) => {
        slice2 = f(slice2, view, true);
      });
      return slice2;
    }
    let parsed = view.someProp("clipboardTextParser", (f) => f(text2, $context, plainText, view));
    if (parsed) {
      slice2 = parsed;
    } else {
      let marks = $context.marks();
      let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);
      dom = document.createElement("div");
      text2.split(/(?:\r\n?|\n)+/).forEach((block2) => {
        let p = dom.appendChild(document.createElement("p"));
        if (block2)
          p.appendChild(serializer.serializeNode(schema.text(block2, marks)));
      });
    }
  } else {
    view.someProp("transformPastedHTML", (f) => {
      html2 = f(html2, view);
    });
    dom = readHTML(html2);
    if (webkit)
      restoreReplacedSpaces(dom);
  }
  let contextNode = dom && dom.querySelector("[data-pm-slice]");
  let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "");
  if (sliceData && sliceData[3])
    for (let i = +sliceData[3]; i > 0; i--) {
      let child = dom.firstChild;
      while (child && child.nodeType != 1)
        child = child.nextSibling;
      if (!child)
        break;
      dom = child;
    }
  if (!slice2) {
    let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema);
    slice2 = parser.parseSlice(dom, {
      preserveWhitespace: !!(asText || sliceData),
      context: $context,
      ruleFromNode(dom2) {
        if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName))
          return { ignore: true };
        return null;
      }
    });
  }
  if (sliceData) {
    slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]);
  } else {
    slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true);
    if (slice2.openStart || slice2.openEnd) {
      let openStart = 0, openEnd = 0;
      for (let node = slice2.content.firstChild; openStart < slice2.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) {
      }
      for (let node = slice2.content.lastChild; openEnd < slice2.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) {
      }
      slice2 = closeSlice(slice2, openStart, openEnd);
    }
  }
  view.someProp("transformPasted", (f) => {
    slice2 = f(slice2, view, asText);
  });
  return slice2;
}
var inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;
function normalizeSiblings(fragment, $context) {
  if (fragment.childCount < 2)
    return fragment;
  for (let d = $context.depth; d >= 0; d--) {
    let parent = $context.node(d);
    let match = parent.contentMatchAt($context.index(d));
    let lastWrap, result = [];
    fragment.forEach((node) => {
      if (!result)
        return;
      let wrap2 = match.findWrapping(node.type), inLast;
      if (!wrap2)
        return result = null;
      if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) {
        result[result.length - 1] = inLast;
      } else {
        if (result.length)
          result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);
        let wrapped = withWrappers(node, wrap2);
        result.push(wrapped);
        match = match.matchType(wrapped.type);
        lastWrap = wrap2;
      }
    });
    if (result)
      return Fragment.from(result);
  }
  return fragment;
}
function withWrappers(node, wrap2, from2 = 0) {
  for (let i = wrap2.length - 1; i >= from2; i--)
    node = wrap2[i].create(null, Fragment.from(node));
  return node;
}
function addToSibling(wrap2, lastWrap, node, sibling, depth) {
  if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) {
    let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1);
    if (inner)
      return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));
    let match = sibling.contentMatchAt(sibling.childCount);
    if (match.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1]))
      return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1))));
  }
}
function closeRight(node, depth) {
  if (depth == 0)
    return node;
  let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));
  let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);
  return node.copy(fragment.append(fill));
}
function closeRange(fragment, side, from2, to, depth, openEnd) {
  let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;
  if (fragment.childCount > 1)
    openEnd = 0;
  if (depth < to - 1)
    inner = closeRange(inner, side, from2, to, depth + 1, openEnd);
  if (depth >= from2)
    inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));
  return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));
}
function closeSlice(slice2, openStart, openEnd) {
  if (openStart < slice2.openStart)
    slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd);
  if (openEnd < slice2.openEnd)
    slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd);
  return slice2;
}
var wrapMap = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
var _detachedDoc = null;
function detachedDoc() {
  return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title"));
}
var _policy = null;
function maybeWrapTrusted(html2) {
  let trustedTypes = window.trustedTypes;
  if (!trustedTypes)
    return html2;
  if (!_policy)
    _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s });
  return _policy.createHTML(html2);
}
function readHTML(html2) {
  let metas = /^(\s*<meta [^>]*>)*/.exec(html2);
  if (metas)
    html2 = html2.slice(metas[0].length);
  let elt = detachedDoc().createElement("div");
  let firstTag = /<([a-z][^>\s]+)/i.exec(html2), wrap2;
  if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()])
    html2 = wrap2.map((n) => "<" + n + ">").join("") + html2 + wrap2.map((n) => "</" + n + ">").reverse().join("");
  elt.innerHTML = maybeWrapTrusted(html2);
  if (wrap2)
    for (let i = 0; i < wrap2.length; i++)
      elt = elt.querySelector(wrap2[i]) || elt;
  return elt;
}
function restoreReplacedSpaces(dom) {
  let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space");
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i];
    if (node.childNodes.length == 1 && node.textContent == "\xA0" && node.parentNode)
      node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node);
  }
}
function addContext(slice2, context) {
  if (!slice2.size)
    return slice2;
  let schema = slice2.content.firstChild.type.schema, array;
  try {
    array = JSON.parse(context);
  } catch (e) {
    return slice2;
  }
  let { content, openStart, openEnd } = slice2;
  for (let i = array.length - 2; i >= 0; i -= 2) {
    let type = schema.nodes[array[i]];
    if (!type || type.hasRequiredAttrs())
      break;
    content = Fragment.from(type.create(array[i + 1], content));
    openStart++;
    openEnd++;
  }
  return new Slice(content, openStart, openEnd);
}
var handlers = {};
var editHandlers = {};
var passiveHandlers = { touchstart: true, touchmove: true };
var InputState = class {
  constructor() {
    this.shiftKey = false;
    this.mouseDown = null;
    this.lastKeyCode = null;
    this.lastKeyCodeTime = 0;
    this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 };
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastIOSEnter = 0;
    this.lastIOSEnterFallbackTimeout = -1;
    this.lastFocus = 0;
    this.lastTouch = 0;
    this.lastChromeDelete = 0;
    this.composing = false;
    this.compositionNode = null;
    this.composingTimeout = -1;
    this.compositionNodes = [];
    this.compositionEndedAt = -2e8;
    this.compositionID = 1;
    this.badSafariComposition = false;
    this.compositionPendingChanges = 0;
    this.domChangeCount = 0;
    this.eventHandlers = /* @__PURE__ */ Object.create(null);
    this.hideSelectionGuard = null;
  }
};
function initInput(view) {
  for (let event in handlers) {
    let handler = handlers[event];
    view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => {
      if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers)))
        handler(view, event2);
    }, passiveHandlers[event] ? { passive: true } : void 0);
  }
  if (safari)
    view.dom.addEventListener("input", () => null);
  ensureListeners(view);
}
function setSelectionOrigin(view, origin) {
  view.input.lastSelectionOrigin = origin;
  view.input.lastSelectionTime = Date.now();
}
function destroyInput(view) {
  view.domObserver.stop();
  for (let type in view.input.eventHandlers)
    view.dom.removeEventListener(type, view.input.eventHandlers[type]);
  clearTimeout(view.input.composingTimeout);
  clearTimeout(view.input.lastIOSEnterFallbackTimeout);
}
function ensureListeners(view) {
  view.someProp("handleDOMEvents", (currentHandlers) => {
    for (let type in currentHandlers)
      if (!view.input.eventHandlers[type])
        view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event));
  });
}
function runCustomHandler(view, event) {
  return view.someProp("handleDOMEvents", (handlers2) => {
    let handler = handlers2[event.type];
    return handler ? handler(view, event) || event.defaultPrevented : false;
  });
}
function eventBelongsToView(view, event) {
  if (!event.bubbles)
    return true;
  if (event.defaultPrevented)
    return false;
  for (let node = event.target; node != view.dom; node = node.parentNode)
    if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event))
      return false;
  return true;
}
function dispatchEvent(view, event) {
  if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers)))
    handlers[event.type](view, event);
}
editHandlers.keydown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.keyCode == 16 || event.shiftKey;
  if (inOrNearComposition(view, event))
    return;
  view.input.lastKeyCode = event.keyCode;
  view.input.lastKeyCodeTime = Date.now();
  if (android && chrome && event.keyCode == 13)
    return;
  if (event.keyCode != 229)
    view.domObserver.forceFlush();
  if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
    let now = Date.now();
    view.input.lastIOSEnter = now;
    view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
      if (view.input.lastIOSEnter == now) {
        view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")));
        view.input.lastIOSEnter = 0;
      }
    }, 200);
  } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "key");
  }
};
editHandlers.keyup = (view, event) => {
  if (event.keyCode == 16)
    view.input.shiftKey = false;
};
editHandlers.keypress = (view, _event) => {
  let event = _event;
  if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac && event.metaKey)
    return;
  if (view.someProp("handleKeyPress", (f) => f(view, event))) {
    event.preventDefault();
    return;
  }
  let sel = view.state.selection;
  if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {
    let text2 = String.fromCharCode(event.charCode);
    let deflt = () => view.state.tr.insertText(text2).scrollIntoView();
    if (!/[\r\n]/.test(text2) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text2, deflt)))
      view.dispatch(deflt());
    event.preventDefault();
  }
};
function eventCoords(event) {
  return { left: event.clientX, top: event.clientY };
}
function isNear(event, click) {
  let dx = click.x - event.clientX, dy = click.y - event.clientY;
  return dx * dx + dy * dy < 100;
}
function runHandlerOnContext(view, propName, pos, inside, event) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    if (view.someProp(propName, (f) => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false)))
      return true;
  }
  return false;
}
function updateSelection(view, selection, origin) {
  if (!view.focused)
    view.focus();
  if (view.state.selection.eq(selection))
    return;
  let tr = view.state.tr.setSelection(selection);
  if (origin == "pointer")
    tr.setMeta("pointer", true);
  view.dispatch(tr);
}
function selectClickedLeaf(view, inside) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;
  if (node && node.isAtom && NodeSelection.isSelectable(node)) {
    updateSelection(view, new NodeSelection($pos), "pointer");
    return true;
  }
  return false;
}
function selectClickedNode(view, inside) {
  if (inside == -1)
    return false;
  let sel = view.state.selection, selectedNode, selectAt;
  if (sel instanceof NodeSelection)
    selectedNode = sel.node;
  let $pos = view.state.doc.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    if (NodeSelection.isSelectable(node)) {
      if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)
        selectAt = $pos.before(sel.$from.depth);
      else
        selectAt = $pos.before(i);
      break;
    }
  }
  if (selectAt != null) {
    updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer");
    return true;
  } else {
    return false;
  }
}
function handleSingleClick(view, pos, inside, event, selectNode2) {
  return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode2 ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
}
function handleDoubleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event));
}
function handleTripleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event);
}
function defaultTripleClick(view, inside, event) {
  if (event.button != 0)
    return false;
  let doc3 = view.state.doc;
  if (inside == -1) {
    if (doc3.inlineContent) {
      updateSelection(view, TextSelection.create(doc3, 0, doc3.content.size), "pointer");
      return true;
    }
    return false;
  }
  let $pos = doc3.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    let nodePos = $pos.before(i);
    if (node.inlineContent)
      updateSelection(view, TextSelection.create(doc3, nodePos + 1, nodePos + 1 + node.content.size), "pointer");
    else if (NodeSelection.isSelectable(node))
      updateSelection(view, NodeSelection.create(doc3, nodePos), "pointer");
    else
      continue;
    return true;
  }
}
function forceDOMFlush(view) {
  return endComposition(view);
}
var selectNodeModifier = mac ? "metaKey" : "ctrlKey";
handlers.mousedown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.shiftKey;
  let flushed = forceDOMFlush(view);
  let now = Date.now(), type = "singleClick";
  if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) {
    if (view.input.lastClick.type == "singleClick")
      type = "doubleClick";
    else if (view.input.lastClick.type == "doubleClick")
      type = "tripleClick";
  }
  view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };
  let pos = view.posAtCoords(eventCoords(event));
  if (!pos)
    return;
  if (type == "singleClick") {
    if (view.input.mouseDown)
      view.input.mouseDown.done();
    view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);
  } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "pointer");
  }
};
var MouseDown = class {
  constructor(view, pos, event, flushed) {
    this.view = view;
    this.pos = pos;
    this.event = event;
    this.flushed = flushed;
    this.delayedSelectionSync = false;
    this.mightDrag = null;
    this.startDoc = view.state.doc;
    this.selectNode = !!event[selectNodeModifier];
    this.allowDefault = event.shiftKey;
    let targetNode, targetPos;
    if (pos.inside > -1) {
      targetNode = view.state.doc.nodeAt(pos.inside);
      targetPos = pos.inside;
    } else {
      let $pos = view.state.doc.resolve(pos.pos);
      targetNode = $pos.parent;
      targetPos = $pos.depth ? $pos.before() : 0;
    }
    const target2 = flushed ? null : event.target;
    const targetDesc = target2 ? view.docView.nearestDesc(target2, true) : null;
    this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null;
    let { selection } = view.state;
    if (event.button == 0 && (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos))
      this.mightDrag = {
        node: targetNode,
        pos: targetPos,
        addAttr: !!(this.target && !this.target.draggable),
        setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable"))
      };
    if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.draggable = true;
      if (this.mightDrag.setUneditable)
        setTimeout(() => {
          if (this.view.input.mouseDown == this)
            this.target.setAttribute("contentEditable", "false");
        }, 20);
      this.view.domObserver.start();
    }
    view.root.addEventListener("mouseup", this.up = this.up.bind(this));
    view.root.addEventListener("mousemove", this.move = this.move.bind(this));
    setSelectionOrigin(view, "pointer");
  }
  done() {
    this.view.root.removeEventListener("mouseup", this.up);
    this.view.root.removeEventListener("mousemove", this.move);
    if (this.mightDrag && this.target) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.removeAttribute("draggable");
      if (this.mightDrag.setUneditable)
        this.target.removeAttribute("contentEditable");
      this.view.domObserver.start();
    }
    if (this.delayedSelectionSync)
      setTimeout(() => selectionToDOM(this.view));
    this.view.input.mouseDown = null;
  }
  up(event) {
    this.done();
    if (!this.view.dom.contains(event.target))
      return;
    let pos = this.pos;
    if (this.view.state.doc != this.startDoc)
      pos = this.view.posAtCoords(eventCoords(event));
    this.updateAllowDefault(event);
    if (this.allowDefault || !pos) {
      setSelectionOrigin(this.view, "pointer");
    } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
      event.preventDefault();
    } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
    safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
    // cursor, but still report that the node is selected
    // when asked through getSelection. You'll then get a
    // situation where clicking at the point where that
    // (hidden) cursor is doesn't change the selection, and
    // thus doesn't get a reaction from ProseMirror. This
    // works around that.
    chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) {
      updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer");
      event.preventDefault();
    } else {
      setSelectionOrigin(this.view, "pointer");
    }
  }
  move(event) {
    this.updateAllowDefault(event);
    setSelectionOrigin(this.view, "pointer");
    if (event.buttons == 0)
      this.done();
  }
  updateAllowDefault(event) {
    if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4))
      this.allowDefault = true;
  }
};
handlers.touchstart = (view) => {
  view.input.lastTouch = Date.now();
  forceDOMFlush(view);
  setSelectionOrigin(view, "pointer");
};
handlers.touchmove = (view) => {
  view.input.lastTouch = Date.now();
  setSelectionOrigin(view, "pointer");
};
handlers.contextmenu = (view) => forceDOMFlush(view);
function inOrNearComposition(view, event) {
  if (view.composing)
    return true;
  if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {
    view.input.compositionEndedAt = -2e8;
    return true;
  }
  return false;
}
var timeoutComposition = android ? 5e3 : -1;
editHandlers.compositionstart = editHandlers.compositionupdate = (view) => {
  if (!view.composing) {
    view.domObserver.flush();
    let { state } = view, $pos = state.selection.$to;
    if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows && selectionBeforeUneditable(view))) {
      view.markCursor = view.state.storedMarks || $pos.marks();
      endComposition(view, true);
      view.markCursor = null;
    } else {
      endComposition(view, !state.selection.empty);
      if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
        let sel = view.domSelectionRange();
        for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) {
          let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];
          if (!before)
            break;
          if (before.nodeType == 3) {
            let sel2 = view.domSelection();
            if (sel2)
              sel2.collapse(before, before.nodeValue.length);
            break;
          } else {
            node = before;
            offset = -1;
          }
        }
      }
    }
    view.input.composing = true;
  }
  scheduleComposeEnd(view, timeoutComposition);
};
function selectionBeforeUneditable(view) {
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length)
    return false;
  let next = focusNode.childNodes[focusOffset];
  return next.nodeType == 1 && next.contentEditable == "false";
}
editHandlers.compositionend = (view, event) => {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = event.timeStamp;
    view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;
    view.input.compositionNode = null;
    if (view.input.badSafariComposition)
      view.domObserver.forceFlush();
    else if (view.input.compositionPendingChanges)
      Promise.resolve().then(() => view.domObserver.flush());
    view.input.compositionID++;
    scheduleComposeEnd(view, 20);
  }
};
function scheduleComposeEnd(view, delay) {
  clearTimeout(view.input.composingTimeout);
  if (delay > -1)
    view.input.composingTimeout = setTimeout(() => endComposition(view), delay);
}
function clearComposition(view) {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = timestampFromCustomEvent();
  }
  while (view.input.compositionNodes.length > 0)
    view.input.compositionNodes.pop().markParentsDirty();
}
function findCompositionNode(view) {
  let sel = view.domSelectionRange();
  if (!sel.focusNode)
    return null;
  let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);
  let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);
  if (textBefore && textAfter && textBefore != textAfter) {
    let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;
    if (textBefore == lastChanged || textAfter == lastChanged)
      return lastChanged;
    if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {
      return textAfter;
    } else if (view.input.compositionNode == textAfter) {
      let descBefore = textBefore.pmViewDesc;
      if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))
        return textAfter;
    }
  }
  return textBefore || textAfter;
}
function timestampFromCustomEvent() {
  let event = document.createEvent("Event");
  event.initEvent("event", true, true);
  return event.timeStamp;
}
function endComposition(view, restarting = false) {
  if (android && view.domObserver.flushingSoon >= 0)
    return;
  view.domObserver.forceFlush();
  clearComposition(view);
  if (restarting || view.docView && view.docView.dirty) {
    let sel = selectionFromDOM(view), cur = view.state.selection;
    if (sel && !sel.eq(cur))
      view.dispatch(view.state.tr.setSelection(sel));
    else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)
      view.dispatch(view.state.tr.deleteSelection());
    else
      view.updateState(view.state);
    return true;
  }
  return false;
}
function captureCopy(view, dom) {
  if (!view.dom.parentNode)
    return;
  let wrap2 = view.dom.parentNode.appendChild(document.createElement("div"));
  wrap2.appendChild(dom);
  wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px";
  let sel = getSelection(), range2 = document.createRange();
  range2.selectNodeContents(dom);
  view.dom.blur();
  sel.removeAllRanges();
  sel.addRange(range2);
  setTimeout(() => {
    if (wrap2.parentNode)
      wrap2.parentNode.removeChild(wrap2);
    view.focus();
  }, 50);
}
var brokenClipboardAPI = ie && ie_version < 15 || ios && webkit_version < 604;
handlers.copy = editHandlers.cut = (view, _event) => {
  let event = _event;
  let sel = view.state.selection, cut = event.type == "cut";
  if (sel.empty)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let slice2 = sel.content(), { dom, text: text2 } = serializeForClipboard(view, slice2);
  if (data) {
    event.preventDefault();
    data.clearData();
    data.setData("text/html", dom.innerHTML);
    data.setData("text/plain", text2);
  } else {
    captureCopy(view, dom);
  }
  if (cut)
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
};
function sliceSingleNode(slice2) {
  return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null;
}
function capturePaste(view, event) {
  if (!view.dom.parentNode)
    return;
  let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;
  let target2 = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div"));
  if (!plainText)
    target2.contentEditable = "true";
  target2.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target2.focus();
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  setTimeout(() => {
    view.focus();
    if (target2.parentNode)
      target2.parentNode.removeChild(target2);
    if (plainText)
      doPaste(view, target2.value, null, plain, event);
    else
      doPaste(view, target2.textContent, target2.innerHTML, plain, event);
  }, 50);
}
function doPaste(view, text2, html2, preferPlain, event) {
  let slice2 = parseFromClipboard(view, text2, html2, preferPlain, view.state.selection.$from);
  if (view.someProp("handlePaste", (f) => f(view, event, slice2 || Slice.empty)))
    return true;
  if (!slice2)
    return false;
  let singleNode = sliceSingleNode(slice2);
  let tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2);
  view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
  return true;
}
function getText(clipboardData) {
  let text2 = clipboardData.getData("text/plain") || clipboardData.getData("Text");
  if (text2)
    return text2;
  let uris = clipboardData.getData("text/uri-list");
  return uris ? uris.replace(/\r?\n/g, " ") : "";
}
editHandlers.paste = (view, _event) => {
  let event = _event;
  if (view.composing && !android)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event))
    event.preventDefault();
  else
    capturePaste(view, event);
};
var Dragging = class {
  constructor(slice2, move, node) {
    this.slice = slice2;
    this.move = move;
    this.node = node;
  }
};
var dragCopyModifier = mac ? "altKey" : "ctrlKey";
function dragMoves(view, event) {
  let copy3;
  view.someProp("dragCopies", (test) => {
    copy3 = copy3 || test(event);
  });
  return copy3 != null ? !copy3 : !event[dragCopyModifier];
}
handlers.dragstart = (view, _event) => {
  let event = _event;
  let mouseDown = view.input.mouseDown;
  if (mouseDown)
    mouseDown.done();
  if (!event.dataTransfer)
    return;
  let sel = view.state.selection;
  let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));
  let node;
  if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;
  else if (mouseDown && mouseDown.mightDrag) {
    node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);
  } else if (event.target && event.target.nodeType == 1) {
    let desc = view.docView.nearestDesc(event.target, true);
    if (desc && desc.node.type.spec.draggable && desc != view.docView)
      node = NodeSelection.create(view.state.doc, desc.posBefore);
  }
  let draggedSlice = (node || view.state.selection).content();
  let { dom, text: text2, slice: slice2 } = serializeForClipboard(view, draggedSlice);
  if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)
    event.dataTransfer.clearData();
  event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);
  event.dataTransfer.effectAllowed = "copyMove";
  if (!brokenClipboardAPI)
    event.dataTransfer.setData("text/plain", text2);
  view.dragging = new Dragging(slice2, dragMoves(view, event), node);
};
handlers.dragend = (view) => {
  let dragging = view.dragging;
  window.setTimeout(() => {
    if (view.dragging == dragging)
      view.dragging = null;
  }, 50);
};
editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();
editHandlers.drop = (view, event) => {
  try {
    handleDrop(view, event, view.dragging);
  } finally {
    view.dragging = null;
  }
};
function handleDrop(view, event, dragging) {
  if (!event.dataTransfer)
    return;
  let eventPos = view.posAtCoords(eventCoords(event));
  if (!eventPos)
    return;
  let $mouse = view.state.doc.resolve(eventPos.pos);
  let slice2 = dragging && dragging.slice;
  if (slice2) {
    view.someProp("transformPasted", (f) => {
      slice2 = f(slice2, view, false);
    });
  } else {
    slice2 = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse);
  }
  let move = !!(dragging && dragMoves(view, event));
  if (view.someProp("handleDrop", (f) => f(view, event, slice2 || Slice.empty, move))) {
    event.preventDefault();
    return;
  }
  if (!slice2)
    return;
  event.preventDefault();
  let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos;
  if (insertPos == null)
    insertPos = $mouse.pos;
  let tr = view.state.tr;
  if (move) {
    let { node } = dragging;
    if (node)
      node.replace(tr);
    else
      tr.deleteSelection();
  }
  let pos = tr.mapping.map(insertPos);
  let isNode = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1;
  let beforeInsert = tr.doc;
  if (isNode)
    tr.replaceRangeWith(pos, pos, slice2.content.firstChild);
  else
    tr.replaceRange(pos, pos, slice2);
  if (tr.doc.eq(beforeInsert))
    return;
  let $pos = tr.doc.resolve(pos);
  if (isNode && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) {
    tr.setSelection(new NodeSelection($pos));
  } else {
    let end = tr.mapping.map(insertPos);
    tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);
    tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));
  }
  view.focus();
  view.dispatch(tr.setMeta("uiEvent", "drop"));
}
handlers.focus = (view) => {
  view.input.lastFocus = Date.now();
  if (!view.focused) {
    view.domObserver.stop();
    view.dom.classList.add("ProseMirror-focused");
    view.domObserver.start();
    view.focused = true;
    setTimeout(() => {
      if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))
        selectionToDOM(view);
    }, 20);
  }
};
handlers.blur = (view, _event) => {
  let event = _event;
  if (view.focused) {
    view.domObserver.stop();
    view.dom.classList.remove("ProseMirror-focused");
    view.domObserver.start();
    if (event.relatedTarget && view.dom.contains(event.relatedTarget))
      view.domObserver.currentSelection.clear();
    view.focused = false;
  }
};
handlers.beforeinput = (view, _event) => {
  let event = _event;
  if (chrome && android && event.inputType == "deleteContentBackward") {
    view.domObserver.flushSoon();
    let { domChangeCount } = view.input;
    setTimeout(() => {
      if (view.input.domChangeCount != domChangeCount)
        return;
      view.dom.blur();
      view.focus();
      if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace"))))
        return;
      let { $cursor } = view.state.selection;
      if ($cursor && $cursor.pos > 0)
        view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
    }, 50);
  }
};
for (let prop2 in editHandlers)
  handlers[prop2] = editHandlers[prop2];
function compareObjs(a, b) {
  if (a == b)
    return true;
  for (let p in a)
    if (a[p] !== b[p])
      return false;
  for (let p in b)
    if (!(p in a))
      return false;
  return true;
}
var WidgetType = class _WidgetType {
  constructor(toDOM, spec) {
    this.toDOM = toDOM;
    this.spec = spec || noSpec;
    this.side = this.spec.side || 0;
  }
  map(mapping, span, offset, oldOffset) {
    let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);
    return deleted ? null : new Decoration(pos - offset, pos - offset, this);
  }
  valid() {
    return true;
  }
  eq(other) {
    return this == other || other instanceof _WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec));
  }
  destroy(node) {
    if (this.spec.destroy)
      this.spec.destroy(node);
  }
};
var InlineType = class _InlineType {
  constructor(attrs, spec) {
    this.attrs = attrs;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from2 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;
    let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;
    return from2 >= to ? null : new Decoration(from2, to, this);
  }
  valid(_, span) {
    return span.from < span.to;
  }
  eq(other) {
    return this == other || other instanceof _InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  static is(span) {
    return span.type instanceof _InlineType;
  }
  destroy() {
  }
};
var NodeType2 = class _NodeType {
  constructor(attrs, spec) {
    this.attrs = attrs;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from2 = mapping.mapResult(span.from + oldOffset, 1);
    if (from2.deleted)
      return null;
    let to = mapping.mapResult(span.to + oldOffset, -1);
    if (to.deleted || to.pos <= from2.pos)
      return null;
    return new Decoration(from2.pos - offset, to.pos - offset, this);
  }
  valid(node, span) {
    let { index: index2, offset } = node.content.findIndex(span.from), child;
    return offset == span.from && !(child = node.child(index2)).isText && offset + child.nodeSize == span.to;
  }
  eq(other) {
    return this == other || other instanceof _NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  destroy() {
  }
};
var Decoration = class _Decoration {
  /**
  @internal
  */
  constructor(from2, to, type) {
    this.from = from2;
    this.to = to;
    this.type = type;
  }
  /**
  @internal
  */
  copy(from2, to) {
    return new _Decoration(from2, to, this.type);
  }
  /**
  @internal
  */
  eq(other, offset = 0) {
    return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;
  }
  /**
  @internal
  */
  map(mapping, offset, oldOffset) {
    return this.type.map(mapping, this, offset, oldOffset);
  }
  /**
  Creates a widget decoration, which is a DOM node that's shown in
  the document at the given position. It is recommended that you
  delay rendering the widget by passing a function that will be
  called when the widget is actually drawn in a view, but you can
  also directly pass a DOM node. `getPos` can be used to find the
  widget's current document position.
  */
  static widget(pos, toDOM, spec) {
    return new _Decoration(pos, pos, new WidgetType(toDOM, spec));
  }
  /**
  Creates an inline decoration, which adds the given attributes to
  each inline node between `from` and `to`.
  */
  static inline(from2, to, attrs, spec) {
    return new _Decoration(from2, to, new InlineType(attrs, spec));
  }
  /**
  Creates a node decoration. `from` and `to` should point precisely
  before and after a node in the document. That node, and only that
  node, will receive the given attributes.
  */
  static node(from2, to, attrs, spec) {
    return new _Decoration(from2, to, new NodeType2(attrs, spec));
  }
  /**
  The spec provided when creating this decoration. Can be useful
  if you've stored extra information in that object.
  */
  get spec() {
    return this.type.spec;
  }
  /**
  @internal
  */
  get inline() {
    return this.type instanceof InlineType;
  }
  /**
  @internal
  */
  get widget() {
    return this.type instanceof WidgetType;
  }
};
var none = [];
var noSpec = {};
var DecorationSet = class _DecorationSet {
  /**
  @internal
  */
  constructor(local, children) {
    this.local = local.length ? local : none;
    this.children = children.length ? children : none;
  }
  /**
  Create a set of decorations, using the structure of the given
  document. This will consume (modify) the `decorations` array, so
  you must make a copy if you want need to preserve that.
  */
  static create(doc3, decorations) {
    return decorations.length ? buildTree(decorations, doc3, 0, noSpec) : empty;
  }
  /**
  Find all decorations in this set which touch the given range
  (including decorations that start or end directly at the
  boundaries) and match the given predicate on their spec. When
  `start` and `end` are omitted, all decorations in the set are
  considered. When `predicate` isn't given, all decorations are
  assumed to match.
  */
  find(start, end, predicate) {
    let result = [];
    this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);
    return result;
  }
  findInner(start, end, result, offset, predicate) {
    for (let i = 0; i < this.local.length; i++) {
      let span = this.local[i];
      if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))
        result.push(span.copy(span.from + offset, span.to + offset));
    }
    for (let i = 0; i < this.children.length; i += 3) {
      if (this.children[i] < end && this.children[i + 1] > start) {
        let childOff = this.children[i] + 1;
        this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);
      }
    }
  }
  /**
  Map the set of decorations in response to a change in the
  document.
  */
  map(mapping, doc3, options) {
    if (this == empty || mapping.maps.length == 0)
      return this;
    return this.mapInner(mapping, doc3, 0, 0, options || noSpec);
  }
  /**
  @internal
  */
  mapInner(mapping, node, offset, oldOffset, options) {
    let newLocal;
    for (let i = 0; i < this.local.length; i++) {
      let mapped = this.local[i].map(mapping, offset, oldOffset);
      if (mapped && mapped.type.valid(node, mapped))
        (newLocal || (newLocal = [])).push(mapped);
      else if (options.onRemove)
        options.onRemove(this.local[i].spec);
    }
    if (this.children.length)
      return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);
    else
      return newLocal ? new _DecorationSet(newLocal.sort(byPos), none) : empty;
  }
  /**
  Add the given array of decorations to the ones in the set,
  producing a new set. Consumes the `decorations` array. Needs
  access to the current document to create the appropriate tree
  structure.
  */
  add(doc3, decorations) {
    if (!decorations.length)
      return this;
    if (this == empty)
      return _DecorationSet.create(doc3, decorations);
    return this.addInner(doc3, decorations, 0);
  }
  addInner(doc3, decorations, offset) {
    let children, childIndex = 0;
    doc3.forEach((childNode, childOffset) => {
      let baseOffset = childOffset + offset, found2;
      if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset)))
        return;
      if (!children)
        children = this.children.slice();
      while (childIndex < children.length && children[childIndex] < childOffset)
        childIndex += 3;
      if (children[childIndex] == childOffset)
        children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1);
      else
        children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec));
      childIndex += 3;
    });
    let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);
    for (let i = 0; i < local.length; i++)
      if (!local[i].type.valid(doc3, local[i]))
        local.splice(i--, 1);
    return new _DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);
  }
  /**
  Create a new set that contains the decorations in this set, minus
  the ones in the given array.
  */
  remove(decorations) {
    if (decorations.length == 0 || this == empty)
      return this;
    return this.removeInner(decorations, 0);
  }
  removeInner(decorations, offset) {
    let children = this.children, local = this.local;
    for (let i = 0; i < children.length; i += 3) {
      let found2;
      let from2 = children[i] + offset, to = children[i + 1] + offset;
      for (let j = 0, span; j < decorations.length; j++)
        if (span = decorations[j]) {
          if (span.from > from2 && span.to < to) {
            decorations[j] = null;
            (found2 || (found2 = [])).push(span);
          }
        }
      if (!found2)
        continue;
      if (children == this.children)
        children = this.children.slice();
      let removed = children[i + 2].removeInner(found2, from2 + 1);
      if (removed != empty) {
        children[i + 2] = removed;
      } else {
        children.splice(i, 3);
        i -= 3;
      }
    }
    if (local.length) {
      for (let i = 0, span; i < decorations.length; i++)
        if (span = decorations[i]) {
          for (let j = 0; j < local.length; j++)
            if (local[j].eq(span, offset)) {
              if (local == this.local)
                local = this.local.slice();
              local.splice(j--, 1);
            }
        }
    }
    if (children == this.children && local == this.local)
      return this;
    return local.length || children.length ? new _DecorationSet(local, children) : empty;
  }
  forChild(offset, node) {
    if (this == empty)
      return this;
    if (node.isLeaf)
      return _DecorationSet.empty;
    let child, local;
    for (let i = 0; i < this.children.length; i += 3)
      if (this.children[i] >= offset) {
        if (this.children[i] == offset)
          child = this.children[i + 2];
        break;
      }
    let start = offset + 1, end = start + node.content.size;
    for (let i = 0; i < this.local.length; i++) {
      let dec = this.local[i];
      if (dec.from < end && dec.to > start && dec.type instanceof InlineType) {
        let from2 = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;
        if (from2 < to)
          (local || (local = [])).push(dec.copy(from2, to));
      }
    }
    if (local) {
      let localSet = new _DecorationSet(local.sort(byPos), none);
      return child ? new DecorationGroup([localSet, child]) : localSet;
    }
    return child || empty;
  }
  /**
  @internal
  */
  eq(other) {
    if (this == other)
      return true;
    if (!(other instanceof _DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length)
      return false;
    for (let i = 0; i < this.local.length; i++)
      if (!this.local[i].eq(other.local[i]))
        return false;
    for (let i = 0; i < this.children.length; i += 3)
      if (this.children[i] != other.children[i] || this.children[i + 1] != other.children[i + 1] || !this.children[i + 2].eq(other.children[i + 2]))
        return false;
    return true;
  }
  /**
  @internal
  */
  locals(node) {
    return removeOverlap(this.localsInner(node));
  }
  /**
  @internal
  */
  localsInner(node) {
    if (this == empty)
      return none;
    if (node.inlineContent || !this.local.some(InlineType.is))
      return this.local;
    let result = [];
    for (let i = 0; i < this.local.length; i++) {
      if (!(this.local[i].type instanceof InlineType))
        result.push(this.local[i]);
    }
    return result;
  }
  forEachSet(f) {
    f(this);
  }
};
DecorationSet.empty = new DecorationSet([], []);
DecorationSet.removeOverlap = removeOverlap;
var empty = DecorationSet.empty;
var DecorationGroup = class _DecorationGroup {
  constructor(members) {
    this.members = members;
  }
  map(mapping, doc3) {
    const mappedDecos = this.members.map((member) => member.map(mapping, doc3, noSpec));
    return _DecorationGroup.from(mappedDecos);
  }
  forChild(offset, child) {
    if (child.isLeaf)
      return DecorationSet.empty;
    let found2 = [];
    for (let i = 0; i < this.members.length; i++) {
      let result = this.members[i].forChild(offset, child);
      if (result == empty)
        continue;
      if (result instanceof _DecorationGroup)
        found2 = found2.concat(result.members);
      else
        found2.push(result);
    }
    return _DecorationGroup.from(found2);
  }
  eq(other) {
    if (!(other instanceof _DecorationGroup) || other.members.length != this.members.length)
      return false;
    for (let i = 0; i < this.members.length; i++)
      if (!this.members[i].eq(other.members[i]))
        return false;
    return true;
  }
  locals(node) {
    let result, sorted = true;
    for (let i = 0; i < this.members.length; i++) {
      let locals = this.members[i].localsInner(node);
      if (!locals.length)
        continue;
      if (!result) {
        result = locals;
      } else {
        if (sorted) {
          result = result.slice();
          sorted = false;
        }
        for (let j = 0; j < locals.length; j++)
          result.push(locals[j]);
      }
    }
    return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;
  }
  // Create a group for the given array of decoration sets, or return
  // a single set when possible.
  static from(members) {
    switch (members.length) {
      case 0:
        return empty;
      case 1:
        return members[0];
      default:
        return new _DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));
    }
  }
  forEachSet(f) {
    for (let i = 0; i < this.members.length; i++)
      this.members[i].forEachSet(f);
  }
};
function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {
  let children = oldChildren.slice();
  for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {
    let moved = 0;
    mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {
      let dSize = newEnd - newStart - (oldEnd - oldStart);
      for (let i2 = 0; i2 < children.length; i2 += 3) {
        let end = children[i2 + 1];
        if (end < 0 || oldStart > end + baseOffset - moved)
          continue;
        let start = children[i2] + baseOffset - moved;
        if (oldEnd >= start) {
          children[i2 + 1] = oldStart <= start ? -2 : -1;
        } else if (oldStart >= baseOffset && dSize) {
          children[i2] += dSize;
          children[i2 + 1] += dSize;
        }
      }
      moved += dSize;
    });
    baseOffset = mapping.maps[i].map(baseOffset, -1);
  }
  let mustRebuild = false;
  for (let i = 0; i < children.length; i += 3)
    if (children[i + 1] < 0) {
      if (children[i + 1] == -2) {
        mustRebuild = true;
        children[i + 1] = -1;
        continue;
      }
      let from2 = mapping.map(oldChildren[i] + oldOffset), fromLocal = from2 - offset;
      if (fromLocal < 0 || fromLocal >= node.content.size) {
        mustRebuild = true;
        continue;
      }
      let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;
      let { index: index2, offset: childOffset } = node.content.findIndex(fromLocal);
      let childNode = node.maybeChild(index2);
      if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
        let mapped = children[i + 2].mapInner(mapping, childNode, from2 + 1, oldChildren[i] + oldOffset + 1, options);
        if (mapped != empty) {
          children[i] = fromLocal;
          children[i + 1] = toLocal;
          children[i + 2] = mapped;
        } else {
          children[i + 1] = -2;
          mustRebuild = true;
        }
      } else {
        mustRebuild = true;
      }
    }
  if (mustRebuild) {
    let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);
    let built = buildTree(decorations, node, 0, options);
    newLocal = built.local;
    for (let i = 0; i < children.length; i += 3)
      if (children[i + 1] < 0) {
        children.splice(i, 3);
        i -= 3;
      }
    for (let i = 0, j = 0; i < built.children.length; i += 3) {
      let from2 = built.children[i];
      while (j < children.length && children[j] < from2)
        j += 3;
      children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);
    }
  }
  return new DecorationSet(newLocal.sort(byPos), children);
}
function moveSpans(spans, offset) {
  if (!offset || !spans.length)
    return spans;
  let result = [];
  for (let i = 0; i < spans.length; i++) {
    let span = spans[i];
    result.push(new Decoration(span.from + offset, span.to + offset, span.type));
  }
  return result;
}
function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {
  function gather(set, oldOffset2) {
    for (let i = 0; i < set.local.length; i++) {
      let mapped = set.local[i].map(mapping, offset, oldOffset2);
      if (mapped)
        decorations.push(mapped);
      else if (options.onRemove)
        options.onRemove(set.local[i].spec);
    }
    for (let i = 0; i < set.children.length; i += 3)
      gather(set.children[i + 2], set.children[i] + oldOffset2 + 1);
  }
  for (let i = 0; i < children.length; i += 3)
    if (children[i + 1] == -1)
      gather(children[i + 2], oldChildren[i] + oldOffset + 1);
  return decorations;
}
function takeSpansForNode(spans, node, offset) {
  if (node.isLeaf)
    return null;
  let end = offset + node.nodeSize, found2 = null;
  for (let i = 0, span; i < spans.length; i++) {
    if ((span = spans[i]) && span.from > offset && span.to < end) {
      (found2 || (found2 = [])).push(span);
      spans[i] = null;
    }
  }
  return found2;
}
function withoutNulls(array) {
  let result = [];
  for (let i = 0; i < array.length; i++)
    if (array[i] != null)
      result.push(array[i]);
  return result;
}
function buildTree(spans, node, offset, options) {
  let children = [], hasNulls = false;
  node.forEach((childNode, localStart) => {
    let found2 = takeSpansForNode(spans, childNode, localStart + offset);
    if (found2) {
      hasNulls = true;
      let subtree = buildTree(found2, childNode, offset + localStart + 1, options);
      if (subtree != empty)
        children.push(localStart, localStart + childNode.nodeSize, subtree);
    }
  });
  let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);
  for (let i = 0; i < locals.length; i++)
    if (!locals[i].type.valid(node, locals[i])) {
      if (options.onRemove)
        options.onRemove(locals[i].spec);
      locals.splice(i--, 1);
    }
  return locals.length || children.length ? new DecorationSet(locals, children) : empty;
}
function byPos(a, b) {
  return a.from - b.from || a.to - b.to;
}
function removeOverlap(spans) {
  let working = spans;
  for (let i = 0; i < working.length - 1; i++) {
    let span = working[i];
    if (span.from != span.to)
      for (let j = i + 1; j < working.length; j++) {
        let next = working[j];
        if (next.from == span.from) {
          if (next.to != span.to) {
            if (working == spans)
              working = spans.slice();
            working[j] = next.copy(next.from, span.to);
            insertAhead(working, j + 1, next.copy(span.to, next.to));
          }
          continue;
        } else {
          if (next.from < span.to) {
            if (working == spans)
              working = spans.slice();
            working[i] = span.copy(span.from, next.from);
            insertAhead(working, j, span.copy(next.from, span.to));
          }
          break;
        }
      }
  }
  return working;
}
function insertAhead(array, i, deco) {
  while (i < array.length && byPos(deco, array[i]) > 0)
    i++;
  array.splice(i, 0, deco);
}
function viewDecorations(view) {
  let found2 = [];
  view.someProp("decorations", (f) => {
    let result = f(view.state);
    if (result && result != empty)
      found2.push(result);
  });
  if (view.cursorWrapper)
    found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
  return DecorationGroup.from(found2);
}
var observeOptions = {
  childList: true,
  characterData: true,
  characterDataOldValue: true,
  attributes: true,
  attributeOldValue: true,
  subtree: true
};
var useCharData = ie && ie_version <= 11;
var SelectionState = class {
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  set(sel) {
    this.anchorNode = sel.anchorNode;
    this.anchorOffset = sel.anchorOffset;
    this.focusNode = sel.focusNode;
    this.focusOffset = sel.focusOffset;
  }
  clear() {
    this.anchorNode = this.focusNode = null;
  }
  eq(sel) {
    return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
  }
};
var DOMObserver = class {
  constructor(view, handleDOMChange) {
    this.view = view;
    this.handleDOMChange = handleDOMChange;
    this.queue = [];
    this.flushingSoon = -1;
    this.observer = null;
    this.currentSelection = new SelectionState();
    this.onCharData = null;
    this.suppressingSelectionUpdates = false;
    this.lastChangedTextNode = null;
    this.observer = window.MutationObserver && new window.MutationObserver((mutations) => {
      for (let i = 0; i < mutations.length; i++)
        this.queue.push(mutations[i]);
      if (ie && ie_version <= 11 && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) {
        this.flushSoon();
      } else if (safari && view.composing && mutations.some((m) => m.type == "childList" && m.target.nodeName == "TR")) {
        view.input.badSafariComposition = true;
        this.flushSoon();
      } else {
        this.flush();
      }
    });
    if (useCharData) {
      this.onCharData = (e) => {
        this.queue.push({ target: e.target, type: "characterData", oldValue: e.prevValue });
        this.flushSoon();
      };
    }
    this.onSelectionChange = this.onSelectionChange.bind(this);
  }
  flushSoon() {
    if (this.flushingSoon < 0)
      this.flushingSoon = window.setTimeout(() => {
        this.flushingSoon = -1;
        this.flush();
      }, 20);
  }
  forceFlush() {
    if (this.flushingSoon > -1) {
      window.clearTimeout(this.flushingSoon);
      this.flushingSoon = -1;
      this.flush();
    }
  }
  start() {
    if (this.observer) {
      this.observer.takeRecords();
      this.observer.observe(this.view.dom, observeOptions);
    }
    if (this.onCharData)
      this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.connectSelection();
  }
  stop() {
    if (this.observer) {
      let take = this.observer.takeRecords();
      if (take.length) {
        for (let i = 0; i < take.length; i++)
          this.queue.push(take[i]);
        window.setTimeout(() => this.flush(), 20);
      }
      this.observer.disconnect();
    }
    if (this.onCharData)
      this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
    this.disconnectSelection();
  }
  connectSelection() {
    this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
  }
  disconnectSelection() {
    this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
  }
  suppressSelectionUpdates() {
    this.suppressingSelectionUpdates = true;
    setTimeout(() => this.suppressingSelectionUpdates = false, 50);
  }
  onSelectionChange() {
    if (!hasFocusAndSelection(this.view))
      return;
    if (this.suppressingSelectionUpdates)
      return selectionToDOM(this.view);
    if (ie && ie_version <= 11 && !this.view.state.selection.empty) {
      let sel = this.view.domSelectionRange();
      if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
        return this.flushSoon();
    }
    this.flush();
  }
  setCurSelection() {
    this.currentSelection.set(this.view.domSelectionRange());
  }
  ignoreSelectionChange(sel) {
    if (!sel.focusNode)
      return true;
    let ancestors = /* @__PURE__ */ new Set(), container;
    for (let scan = sel.focusNode; scan; scan = parentNode(scan))
      ancestors.add(scan);
    for (let scan = sel.anchorNode; scan; scan = parentNode(scan))
      if (ancestors.has(scan)) {
        container = scan;
        break;
      }
    let desc = container && this.view.docView.nearestDesc(container);
    if (desc && desc.ignoreMutation({
      type: "selection",
      target: container.nodeType == 3 ? container.parentNode : container
    })) {
      this.setCurSelection();
      return true;
    }
  }
  pendingRecords() {
    if (this.observer)
      for (let mut of this.observer.takeRecords())
        this.queue.push(mut);
    return this.queue;
  }
  flush() {
    let { view } = this;
    if (!view.docView || this.flushingSoon > -1)
      return;
    let mutations = this.pendingRecords();
    if (mutations.length)
      this.queue = [];
    let sel = view.domSelectionRange();
    let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);
    let from2 = -1, to = -1, typeOver = false, added = [];
    if (view.editable) {
      for (let i = 0; i < mutations.length; i++) {
        let result = this.registerMutation(mutations[i], added);
        if (result) {
          from2 = from2 < 0 ? result.from : Math.min(result.from, from2);
          to = to < 0 ? result.to : Math.max(result.to, to);
          if (result.typeOver)
            typeOver = true;
        }
      }
    }
    if (added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) {
      for (let node of added)
        if (node.nodeName == "BR" && node.parentNode) {
          let after = node.nextSibling;
          while (after && after.nodeType == 1) {
            if (after.contentEditable == "false") {
              node.parentNode.removeChild(node);
              break;
            }
            after = after.firstChild;
          }
        }
    } else if (gecko && added.length) {
      let brs = added.filter((n) => n.nodeName == "BR");
      if (brs.length == 2) {
        let [a, b] = brs;
        if (a.parentNode && a.parentNode.parentNode == b.parentNode)
          b.remove();
        else
          a.remove();
      } else {
        let { focusNode } = this.currentSelection;
        for (let br of brs) {
          let parent = br.parentNode;
          if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent))
            br.remove();
        }
      }
    }
    let readSel = null;
    if (from2 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {
      view.input.lastFocus = 0;
      selectionToDOM(view);
      this.currentSelection.set(sel);
      view.scrollToSelection();
    } else if (from2 > -1 || newSel) {
      if (from2 > -1) {
        view.docView.markDirty(from2, to);
        checkCSS(view);
      }
      if (view.input.badSafariComposition) {
        view.input.badSafariComposition = false;
        fixUpBadSafariComposition(view, added);
      }
      this.handleDOMChange(from2, to, typeOver, added);
      if (view.docView && view.docView.dirty)
        view.updateState(view.state);
      else if (!this.currentSelection.eq(sel))
        selectionToDOM(view);
      this.currentSelection.set(sel);
    }
  }
  registerMutation(mut, added) {
    if (added.indexOf(mut.target) > -1)
      return null;
    let desc = this.view.docView.nearestDesc(mut.target);
    if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
    mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))
      return null;
    if (!desc || desc.ignoreMutation(mut))
      return null;
    if (mut.type == "childList") {
      for (let i = 0; i < mut.addedNodes.length; i++) {
        let node = mut.addedNodes[i];
        added.push(node);
        if (node.nodeType == 3)
          this.lastChangedTextNode = node;
      }
      if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))
        return { from: desc.posBefore, to: desc.posAfter };
      let prev = mut.previousSibling, next = mut.nextSibling;
      if (ie && ie_version <= 11 && mut.addedNodes.length) {
        for (let i = 0; i < mut.addedNodes.length; i++) {
          let { previousSibling, nextSibling } = mut.addedNodes[i];
          if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)
            prev = previousSibling;
          if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)
            next = nextSibling;
        }
      }
      let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
      let from2 = desc.localPosFromDOM(mut.target, fromOffset, -1);
      let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length;
      let to = desc.localPosFromDOM(mut.target, toOffset, 1);
      return { from: from2, to };
    } else if (mut.type == "attributes") {
      return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };
    } else {
      this.lastChangedTextNode = mut.target;
      return {
        from: desc.posAtStart,
        to: desc.posAtEnd,
        // An event was generated for a text change that didn't change
        // any text. Mark the dom change to fall back to assuming the
        // selection was typed over with an identical value if it can't
        // find another change.
        typeOver: mut.target.nodeValue == mut.oldValue
      };
    }
  }
};
var cssChecked = /* @__PURE__ */ new WeakMap();
var cssCheckWarned = false;
function checkCSS(view) {
  if (cssChecked.has(view))
    return;
  cssChecked.set(view, null);
  if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {
    view.requiresGeckoHackNode = gecko;
    if (cssCheckWarned)
      return;
    console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
    cssCheckWarned = true;
  }
}
function rangeToSelectionRange(view, range2) {
  let anchorNode = range2.startContainer, anchorOffset = range2.startOffset;
  let focusNode = range2.endContainer, focusOffset = range2.endOffset;
  let currentAnchor = view.domAtPos(view.state.selection.anchor);
  if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
function safariShadowSelectionRange(view, selection) {
  if (selection.getComposedRanges) {
    let range2 = selection.getComposedRanges(view.root)[0];
    if (range2)
      return rangeToSelectionRange(view, range2);
  }
  let found2;
  function read(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    found2 = event.getTargetRanges()[0];
  }
  view.dom.addEventListener("beforeinput", read, true);
  document.execCommand("indent");
  view.dom.removeEventListener("beforeinput", read, true);
  return found2 ? rangeToSelectionRange(view, found2) : null;
}
function blockParent(view, node) {
  for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {
    let desc = view.docView.nearestDesc(p, true);
    if (desc && desc.node.isBlock)
      return p;
  }
  return null;
}
function fixUpBadSafariComposition(view, addedNodes) {
  var _a;
  let { focusNode, focusOffset } = view.domSelectionRange();
  for (let node of addedNodes) {
    if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == "TR") {
      let nextCell = node.nextSibling;
      while (nextCell && (nextCell.nodeName != "TD" && nextCell.nodeName != "TH"))
        nextCell = nextCell.nextSibling;
      if (nextCell) {
        let parent = nextCell;
        for (; ; ) {
          let first = parent.firstChild;
          if (!first || first.nodeType != 1 || first.contentEditable == "false" || /^(BR|IMG)$/.test(first.nodeName))
            break;
          parent = first;
        }
        parent.insertBefore(node, parent.firstChild);
        if (focusNode == node)
          view.domSelection().collapse(node, focusOffset);
      } else {
        node.parentNode.removeChild(node);
      }
    }
  }
}
function parseBetween(view, from_, to_) {
  let { node: parent, fromOffset, toOffset, from: from2, to } = view.docView.parseRange(from_, to_);
  let domSel = view.domSelectionRange();
  let find;
  let anchor = domSel.anchorNode;
  if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {
    find = [{ node: anchor, offset: domSel.anchorOffset }];
    if (!selectionCollapsed(domSel))
      find.push({ node: domSel.focusNode, offset: domSel.focusOffset });
  }
  if (chrome && view.input.lastKeyCode === 8) {
    for (let off2 = toOffset; off2 > fromOffset; off2--) {
      let node = parent.childNodes[off2 - 1], desc = node.pmViewDesc;
      if (node.nodeName == "BR" && !desc) {
        toOffset = off2;
        break;
      }
      if (!desc || desc.size)
        break;
    }
  }
  let startDoc = view.state.doc;
  let parser = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema);
  let $from = startDoc.resolve(from2);
  let sel = null, doc3 = parser.parse(parent, {
    topNode: $from.parent,
    topMatch: $from.parent.contentMatchAt($from.index()),
    topOpen: true,
    from: fromOffset,
    to: toOffset,
    preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true,
    findPositions: find,
    ruleFromNode,
    context: $from
  });
  if (find && find[0].pos != null) {
    let anchor2 = find[0].pos, head = find[1] && find[1].pos;
    if (head == null)
      head = anchor2;
    sel = { anchor: anchor2 + from2, head: head + from2 };
  }
  return { doc: doc3, sel, from: from2, to };
}
function ruleFromNode(dom) {
  let desc = dom.pmViewDesc;
  if (desc) {
    return desc.parseRule();
  } else if (dom.nodeName == "BR" && dom.parentNode) {
    if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
      let skip = document.createElement("div");
      skip.appendChild(document.createElement("li"));
      return { skip };
    } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
      return { ignore: true };
    }
  } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
    return { ignore: true };
  }
  return null;
}
var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;
function readDOMChange(view, from2, to, typeOver, addedNodes) {
  let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);
  view.input.compositionPendingChanges = 0;
  if (from2 < 0) {
    let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;
    let newSel = selectionFromDOM(view, origin);
    if (newSel && !view.state.selection.eq(newSel)) {
      if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))))
        return;
      let tr = view.state.tr.setSelection(newSel);
      if (origin == "pointer")
        tr.setMeta("pointer", true);
      else if (origin == "key")
        tr.scrollIntoView();
      if (compositionID)
        tr.setMeta("composition", compositionID);
      view.dispatch(tr);
    }
    return;
  }
  let $before = view.state.doc.resolve(from2);
  let shared = $before.sharedDepth(to);
  from2 = $before.before(shared + 1);
  to = view.state.doc.resolve(to).after(shared + 1);
  let sel = view.state.selection;
  let parse = parseBetween(view, from2, to);
  let doc3 = view.state.doc, compare = doc3.slice(parse.from, parse.to);
  let preferredPos, preferredSide;
  if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {
    preferredPos = view.state.selection.to;
    preferredSide = "end";
  } else {
    preferredPos = view.state.selection.from;
    preferredSide = "start";
  }
  view.input.lastKeyCode = null;
  let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);
  if (change)
    view.input.domChangeCount++;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (!change) {
    if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {
      change = { start: sel.from, endA: sel.to, endB: sel.to };
    } else {
      if (parse.sel) {
        let sel2 = resolveSelection(view, view.state.doc, parse.sel);
        if (sel2 && !sel2.eq(view.state.selection)) {
          let tr = view.state.tr.setSelection(sel2);
          if (compositionID)
            tr.setMeta("composition", compositionID);
          view.dispatch(tr);
        }
      }
      return;
    }
  }
  if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) {
    if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse.from) {
      change.start = view.state.selection.from;
    } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse.to) {
      change.endB += view.state.selection.to - change.endA;
      change.endA = view.state.selection.to;
    }
  }
  if (ie && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == " \xA0") {
    change.start--;
    change.endA--;
    change.endB--;
  }
  let $from = parse.doc.resolveNoCache(change.start - parse.from);
  let $to = parse.doc.resolveNoCache(change.endB - parse.from);
  let $fromA = doc3.resolve(change.start);
  let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (view.state.selection.anchor > change.start && looksLikeBackspace(doc3, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) {
    if (android && chrome)
      view.domObserver.suppressSelectionUpdates();
    return;
  }
  if (chrome && change.endB == change.start)
    view.input.lastChromeDelete = Date.now();
  if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {
    change.endB -= 2;
    $to = parse.doc.resolveNoCache(change.endB - parse.from);
    setTimeout(() => {
      view.someProp("handleKeyDown", function(f) {
        return f(view, keyEvent(13, "Enter"));
      });
    }, 20);
  }
  let chFrom = change.start, chTo = change.endA;
  let mkTr = (base2) => {
    let tr = base2 || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));
    if (parse.sel) {
      let sel2 = resolveSelection(view, tr.doc, parse.sel);
      if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr.mapping.map(chTo) - 1) || ie && sel2.empty && sel2.head == chFrom))
        tr.setSelection(sel2);
    }
    if (compositionID)
      tr.setMeta("composition", compositionID);
    return tr.scrollIntoView();
  };
  let markChange;
  if (inlineChange) {
    if ($from.pos == $to.pos) {
      if (ie && ie_version <= 11 && $from.parentOffset == 0) {
        view.domObserver.suppressSelectionUpdates();
        setTimeout(() => selectionToDOM(view), 20);
      }
      let tr = mkTr(view.state.tr.delete(chFrom, chTo));
      let marks = doc3.resolve(change.start).marksAcross(doc3.resolve(change.endA));
      if (marks)
        tr.ensureMarks(marks);
      view.dispatch(tr);
    } else if (
      // Adding or removing a mark
      change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))
    ) {
      let tr = mkTr(view.state.tr);
      if (markChange.type == "add")
        tr.addMark(chFrom, chTo, markChange.mark);
      else
        tr.removeMark(chFrom, chTo, markChange.mark);
      view.dispatch(tr);
    } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
      let text2 = $from.parent.textBetween($from.parentOffset, $to.parentOffset);
      let deflt = () => mkTr(view.state.tr.insertText(text2, chFrom, chTo));
      if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text2, deflt)))
        view.dispatch(deflt());
    } else {
      view.dispatch(mkTr());
    }
  } else {
    view.dispatch(mkTr());
  }
}
function resolveSelection(view, doc3, parsedSel) {
  if (Math.max(parsedSel.anchor, parsedSel.head) > doc3.content.size)
    return null;
  return selectionBetween(view, doc3.resolve(parsedSel.anchor), doc3.resolve(parsedSel.head));
}
function isMarkChange(cur, prev) {
  let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;
  let added = curMarks, removed = prevMarks, type, mark, update;
  for (let i = 0; i < prevMarks.length; i++)
    added = prevMarks[i].removeFromSet(added);
  for (let i = 0; i < curMarks.length; i++)
    removed = curMarks[i].removeFromSet(removed);
  if (added.length == 1 && removed.length == 0) {
    mark = added[0];
    type = "add";
    update = (node) => node.mark(mark.addToSet(node.marks));
  } else if (added.length == 0 && removed.length == 1) {
    mark = removed[0];
    type = "remove";
    update = (node) => node.mark(mark.removeFromSet(node.marks));
  } else {
    return null;
  }
  let updated = [];
  for (let i = 0; i < prev.childCount; i++)
    updated.push(update(prev.child(i)));
  if (Fragment.from(updated).eq(cur))
    return { mark, type };
}
function looksLikeBackspace(old, start, end, $newStart, $newEnd) {
  if (
    // The content must have shrunk
    end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
    skipClosingAndOpening($newStart, true, false) < $newEnd.pos
  )
    return false;
  let $start = old.resolve(start);
  if (!$newStart.parent.isTextblock) {
    let after = $start.nodeAfter;
    return after != null && end == start + after.nodeSize;
  }
  if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)
    return false;
  let $next = old.resolve(skipClosingAndOpening($start, true, true));
  if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end)
    return false;
  return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
}
function skipClosingAndOpening($pos, fromEnd, mayOpen) {
  let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;
  while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
    depth--;
    end++;
    fromEnd = false;
  }
  if (mayOpen) {
    let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));
    while (next && !next.isLeaf) {
      next = next.firstChild;
      end++;
    }
  }
  return end;
}
function findDiff(a, b, pos, preferredPos, preferredSide) {
  let start = a.findDiffStart(b, pos);
  if (start == null)
    return null;
  let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size);
  if (preferredSide == "end") {
    let adjust = Math.max(0, start - Math.min(endA, endB));
    preferredPos -= endA + adjust - start;
  }
  if (endA < start && a.size < b.size) {
    let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;
    start -= move;
    if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1)))
      start += move ? 1 : -1;
    endB = start + (endB - endA);
    endA = start;
  } else if (endB < start) {
    let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;
    start -= move;
    if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1)))
      start += move ? 1 : -1;
    endA = start + (endA - endB);
    endB = start;
  }
  return { start, endA, endB };
}
function isSurrogatePair(str) {
  if (str.length != 2)
    return false;
  let a = str.charCodeAt(0), b = str.charCodeAt(1);
  return a >= 56320 && a <= 57343 && b >= 55296 && b <= 56319;
}
var EditorView = class {
  /**
  Create a view. `place` may be a DOM node that the editor should
  be appended to, a function that will place it into the document,
  or an object whose `mount` property holds the node to use as the
  document container. If it is `null`, the editor will not be
  added to the document.
  */
  constructor(place, props) {
    this._root = null;
    this.focused = false;
    this.trackWrites = null;
    this.mounted = false;
    this.markCursor = null;
    this.cursorWrapper = null;
    this.lastSelectedViewDesc = void 0;
    this.input = new InputState();
    this.prevDirectPlugins = [];
    this.pluginViews = [];
    this.requiresGeckoHackNode = false;
    this.dragging = null;
    this._props = props;
    this.state = props.state;
    this.directPlugins = props.plugins || [];
    this.directPlugins.forEach(checkStateComponent);
    this.dispatch = this.dispatch.bind(this);
    this.dom = place && place.mount || document.createElement("div");
    if (place) {
      if (place.appendChild)
        place.appendChild(this.dom);
      else if (typeof place == "function")
        place(this.dom);
      else if (place.mount)
        this.mounted = true;
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    this.nodeViews = buildNodeViews(this);
    this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
    this.domObserver = new DOMObserver(this, (from2, to, typeOver, added) => readDOMChange(this, from2, to, typeOver, added));
    this.domObserver.start();
    initInput(this);
    this.updatePluginViews();
  }
  /**
  Holds `true` when a
  [composition](https://w3c.github.io/uievents/#events-compositionevents)
  is active.
  */
  get composing() {
    return this.input.composing;
  }
  /**
  The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).
  */
  get props() {
    if (this._props.state != this.state) {
      let prev = this._props;
      this._props = {};
      for (let name in prev)
        this._props[name] = prev[name];
      this._props.state = this.state;
    }
    return this._props;
  }
  /**
  Update the view's props. Will immediately cause an update to
  the DOM.
  */
  update(props) {
    if (props.handleDOMEvents != this._props.handleDOMEvents)
      ensureListeners(this);
    let prevProps = this._props;
    this._props = props;
    if (props.plugins) {
      props.plugins.forEach(checkStateComponent);
      this.directPlugins = props.plugins;
    }
    this.updateStateInner(props.state, prevProps);
  }
  /**
  Update the view by updating existing props object with the object
  given as argument. Equivalent to `view.update(Object.assign({},
  view.props, props))`.
  */
  setProps(props) {
    let updated = {};
    for (let name in this._props)
      updated[name] = this._props[name];
    updated.state = this.state;
    for (let name in props)
      updated[name] = props[name];
    this.update(updated);
  }
  /**
  Update the editor's `state` prop, without touching any of the
  other props.
  */
  updateState(state) {
    this.updateStateInner(state, this._props);
  }
  updateStateInner(state, prevProps) {
    var _a;
    let prev = this.state, redraw = false, updateSel = false;
    if (state.storedMarks && this.composing) {
      clearComposition(this);
      updateSel = true;
    }
    this.state = state;
    let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;
    if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
      let nodeViews = buildNodeViews(this);
      if (changedNodeViews(nodeViews, this.nodeViews)) {
        this.nodeViews = nodeViews;
        redraw = true;
      }
    }
    if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
      ensureListeners(this);
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);
    let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
    let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
    if (updateDoc || !state.selection.eq(prev.selection))
      updateSel = true;
    let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);
    if (updateSel) {
      this.domObserver.stop();
      let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);
      if (updateDoc) {
        let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null;
        if (this.composing)
          this.input.compositionNode = findCompositionNode(this);
        if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
          this.docView.updateOuterDeco(outerDeco);
          this.docView.destroy();
          this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
        }
        if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))
          forceSelUpdate = true;
      }
      if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) {
        selectionToDOM(this, forceSelUpdate);
      } else {
        syncNodeSelection(this, state.selection);
        this.domObserver.setCurSelection();
      }
      this.domObserver.start();
    }
    this.updatePluginViews(prev);
    if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))
      this.updateDraggedNode(this.dragging, prev);
    if (scroll == "reset") {
      this.dom.scrollTop = 0;
    } else if (scroll == "to selection") {
      this.scrollToSelection();
    } else if (oldScrollPos) {
      resetScrollPos(oldScrollPos);
    }
  }
  /**
  @internal
  */
  scrollToSelection() {
    let startDOM = this.domSelectionRange().focusNode;
    if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ;
    else if (this.someProp("handleScrollToSelection", (f) => f(this))) ;
    else if (this.state.selection instanceof NodeSelection) {
      let target2 = this.docView.domAfterPos(this.state.selection.from);
      if (target2.nodeType == 1)
        scrollRectIntoView(this, target2.getBoundingClientRect(), startDOM);
    } else {
      scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);
    }
  }
  destroyPluginViews() {
    let view;
    while (view = this.pluginViews.pop())
      if (view.destroy)
        view.destroy();
  }
  updatePluginViews(prevState) {
    if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
      this.prevDirectPlugins = this.directPlugins;
      this.destroyPluginViews();
      for (let i = 0; i < this.directPlugins.length; i++) {
        let plugin = this.directPlugins[i];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
      for (let i = 0; i < this.state.plugins.length; i++) {
        let plugin = this.state.plugins[i];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
    } else {
      for (let i = 0; i < this.pluginViews.length; i++) {
        let pluginView = this.pluginViews[i];
        if (pluginView.update)
          pluginView.update(this, prevState);
      }
    }
  }
  updateDraggedNode(dragging, prev) {
    let sel = dragging.node, found2 = -1;
    if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {
      found2 = sel.from;
    } else {
      let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);
      let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos);
      if (moved == sel.node)
        found2 = movedPos;
    }
    this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2));
  }
  someProp(propName, f) {
    let prop2 = this._props && this._props[propName], value;
    if (prop2 != null && (value = f ? f(prop2) : prop2))
      return value;
    for (let i = 0; i < this.directPlugins.length; i++) {
      let prop3 = this.directPlugins[i].props[propName];
      if (prop3 != null && (value = f ? f(prop3) : prop3))
        return value;
    }
    let plugins = this.state.plugins;
    if (plugins)
      for (let i = 0; i < plugins.length; i++) {
        let prop3 = plugins[i].props[propName];
        if (prop3 != null && (value = f ? f(prop3) : prop3))
          return value;
      }
  }
  /**
  Query whether the view has focus.
  */
  hasFocus() {
    if (ie) {
      let node = this.root.activeElement;
      if (node == this.dom)
        return true;
      if (!node || !this.dom.contains(node))
        return false;
      while (node && this.dom != node && this.dom.contains(node)) {
        if (node.contentEditable == "false")
          return false;
        node = node.parentElement;
      }
      return true;
    }
    return this.root.activeElement == this.dom;
  }
  /**
  Focus the editor.
  */
  focus() {
    this.domObserver.stop();
    if (this.editable)
      focusPreventScroll(this.dom);
    selectionToDOM(this);
    this.domObserver.start();
  }
  /**
  Get the document root in which the editor exists. This will
  usually be the top-level `document`, but might be a [shadow
  DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
  root if the editor is inside one.
  */
  get root() {
    let cached = this._root;
    if (cached == null)
      for (let search = this.dom.parentNode; search; search = search.parentNode) {
        if (search.nodeType == 9 || search.nodeType == 11 && search.host) {
          if (!search.getSelection)
            Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();
          return this._root = search;
        }
      }
    return cached || document;
  }
  /**
  When an existing editor view is moved to a new document or
  shadow tree, call this to make it recompute its root.
  */
  updateRoot() {
    this._root = null;
  }
  /**
  Given a pair of viewport coordinates, return the document
  position that corresponds to them. May return null if the given
  coordinates aren't inside of the editor. When an object is
  returned, its `pos` property is the position nearest to the
  coordinates, and its `inside` property holds the position of the
  inner node that the position falls inside of, or -1 if it is at
  the top level, not in any node.
  */
  posAtCoords(coords) {
    return posAtCoords(this, coords);
  }
  /**
  Returns the viewport rectangle at a given document position.
  `left` and `right` will be the same number, as this returns a
  flat cursor-ish rectangle. If the position is between two things
  that aren't directly adjacent, `side` determines which element
  is used. When < 0, the element before the position is used,
  otherwise the element after.
  */
  coordsAtPos(pos, side = 1) {
    return coordsAtPos(this, pos, side);
  }
  /**
  Find the DOM position that corresponds to the given document
  position. When `side` is negative, find the position as close as
  possible to the content before the position. When positive,
  prefer positions close to the content after the position. When
  zero, prefer as shallow a position as possible.
  
  Note that you should **not** mutate the editor's internal DOM,
  only inspect it (and even that is usually not necessary).
  */
  domAtPos(pos, side = 0) {
    return this.docView.domFromPos(pos, side);
  }
  /**
  Find the DOM node that represents the document node after the
  given position. May return `null` when the position doesn't point
  in front of a node or if the node is inside an opaque node view.
  
  This is intended to be able to call things like
  `getBoundingClientRect` on that DOM node. Do **not** mutate the
  editor DOM directly, or add styling this way, since that will be
  immediately overriden by the editor as it redraws the node.
  */
  nodeDOM(pos) {
    let desc = this.docView.descAt(pos);
    return desc ? desc.nodeDOM : null;
  }
  /**
  Find the document position that corresponds to a given DOM
  position. (Whenever possible, it is preferable to inspect the
  document structure directly, rather than poking around in the
  DOM, but sometimes—for example when interpreting an event
  target—you don't have a choice.)
  
  The `bias` parameter can be used to influence which side of a DOM
  node to use when the position is inside a leaf node.
  */
  posAtDOM(node, offset, bias = -1) {
    let pos = this.docView.posFromDOM(node, offset, bias);
    if (pos == null)
      throw new RangeError("DOM position not inside the editor");
    return pos;
  }
  /**
  Find out whether the selection is at the end of a textblock when
  moving in a given direction. When, for example, given `"left"`,
  it will return true if moving left from the current cursor
  position would leave that position's parent textblock. Will apply
  to the view's current state by default, but it is possible to
  pass a different state.
  */
  endOfTextblock(dir, state) {
    return endOfTextblock(this, state || this.state, dir);
  }
  /**
  Run the editor's paste logic with the given HTML string. The
  `event`, if given, will be passed to the
  [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.
  */
  pasteHTML(html2, event) {
    return doPaste(this, "", html2, false, event || new ClipboardEvent("paste"));
  }
  /**
  Run the editor's paste logic with the given plain-text input.
  */
  pasteText(text2, event) {
    return doPaste(this, text2, null, true, event || new ClipboardEvent("paste"));
  }
  /**
  Serialize the given slice as it would be if it was copied from
  this editor. Returns a DOM element that contains a
  representation of the slice as its children, a textual
  representation, and the transformed slice (which can be
  different from the given input due to hooks like
  [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).
  */
  serializeForClipboard(slice2) {
    return serializeForClipboard(this, slice2);
  }
  /**
  Removes the editor from the DOM and destroys all [node
  views](https://prosemirror.net/docs/ref/#view.NodeView).
  */
  destroy() {
    if (!this.docView)
      return;
    destroyInput(this);
    this.destroyPluginViews();
    if (this.mounted) {
      this.docView.update(this.state.doc, [], viewDecorations(this), this);
      this.dom.textContent = "";
    } else if (this.dom.parentNode) {
      this.dom.parentNode.removeChild(this.dom);
    }
    this.docView.destroy();
    this.docView = null;
    clearReusedRange();
  }
  /**
  This is true when the view has been
  [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be
  used anymore).
  */
  get isDestroyed() {
    return this.docView == null;
  }
  /**
  Used for testing.
  */
  dispatchEvent(event) {
    return dispatchEvent(this, event);
  }
  /**
  @internal
  */
  domSelectionRange() {
    let sel = this.domSelection();
    if (!sel)
      return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
    return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;
  }
  /**
  @internal
  */
  domSelection() {
    return this.root.getSelection();
  }
};
EditorView.prototype.dispatch = function(tr) {
  let dispatchTransaction = this._props.dispatchTransaction;
  if (dispatchTransaction)
    dispatchTransaction.call(this, tr);
  else
    this.updateState(this.state.apply(tr));
};
function computeDocDeco(view) {
  let attrs = /* @__PURE__ */ Object.create(null);
  attrs.class = "ProseMirror";
  attrs.contenteditable = String(view.editable);
  view.someProp("attributes", (value) => {
    if (typeof value == "function")
      value = value(view.state);
    if (value)
      for (let attr in value) {
        if (attr == "class")
          attrs.class += " " + value[attr];
        else if (attr == "style")
          attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr];
        else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName")
          attrs[attr] = String(value[attr]);
      }
  });
  if (!attrs.translate)
    attrs.translate = "no";
  return [Decoration.node(0, view.state.doc.content.size, attrs)];
}
function updateCursorWrapper(view) {
  if (view.markCursor) {
    let dom = document.createElement("img");
    dom.className = "ProseMirror-separator";
    dom.setAttribute("mark-placeholder", "true");
    dom.setAttribute("alt", "");
    view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };
  } else {
    view.cursorWrapper = null;
  }
}
function getEditable(view) {
  return !view.someProp("editable", (value) => value(view.state) === false);
}
function selectionContextChanged(sel1, sel2) {
  let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
  return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
}
function buildNodeViews(view) {
  let result = /* @__PURE__ */ Object.create(null);
  function add(obj) {
    for (let prop2 in obj)
      if (!Object.prototype.hasOwnProperty.call(result, prop2))
        result[prop2] = obj[prop2];
  }
  view.someProp("nodeViews", add);
  view.someProp("markViews", add);
  return result;
}
function changedNodeViews(a, b) {
  let nA = 0, nB = 0;
  for (let prop2 in a) {
    if (a[prop2] != b[prop2])
      return true;
    nA++;
  }
  for (let _ in b)
    nB++;
  return nA != nB;
}
function checkStateComponent(plugin) {
  if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
    throw new RangeError("Plugins passed directly to the view must not have a state component");
}

// node_modules/w3c-keyname/index.js
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 mac2 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
var i;
for (i = 1; i <= 24; i++) base[i + 111] = "F" + i;
var i;
for (i = 65; i <= 90; i++) {
  base[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
}
var i;
for (code2 in base) if (!shift.hasOwnProperty(code2)) shift[code2] = base[code2];
var code2;
function keyName(event) {
  var ignoreKey = mac2 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
  var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
  if (name == "Esc") name = "Escape";
  if (name == "Del") name = "Delete";
  if (name == "Left") name = "ArrowLeft";
  if (name == "Up") name = "ArrowUp";
  if (name == "Right") name = "ArrowRight";
  if (name == "Down") name = "ArrowDown";
  return name;
}

// node_modules/prosemirror-keymap/dist/index.js
var mac3 = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
var windows2 = typeof navigator != "undefined" && /Win/.test(navigator.platform);
function normalizeKeyName(name) {
  let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift2, meta;
  for (let i = 0; i < parts.length - 1; i++) {
    let mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (mac3)
        meta = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta)
    result = "Meta-" + result;
  if (shift2)
    result = "Shift-" + result;
  return result;
}
function normalize(map3) {
  let copy3 = /* @__PURE__ */ Object.create(null);
  for (let prop2 in map3)
    copy3[normalizeKeyName(prop2)] = map3[prop2];
  return copy3;
}
function modifiers(name, event, shift2 = true) {
  if (event.altKey)
    name = "Alt-" + name;
  if (event.ctrlKey)
    name = "Ctrl-" + name;
  if (event.metaKey)
    name = "Meta-" + name;
  if (shift2 && event.shiftKey)
    name = "Shift-" + name;
  return name;
}
function keymap(bindings) {
  return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
}
function keydownHandler(bindings) {
  let map3 = normalize(bindings);
  return function(view, event) {
    let name = keyName(event), baseName, direct = map3[modifiers(name, event)];
    if (direct && direct(view.state, view.dispatch, view))
      return true;
    if (name.length == 1 && name != " ") {
      if (event.shiftKey) {
        let noShift = map3[modifiers(name, event, false)];
        if (noShift && noShift(view.state, view.dispatch, view))
          return true;
      }
      if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
      !(windows2 && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) {
        let fromCode = map3[modifiers(baseName, event)];
        if (fromCode && fromCode(view.state, view.dispatch, view))
          return true;
      }
    }
    return false;
  };
}

// node_modules/prosemirror-commands/dist/index.js
var deleteSelection = (state, dispatch) => {
  if (state.selection.empty)
    return false;
  if (dispatch)
    dispatch(state.tr.deleteSelection().scrollIntoView());
  return true;
};
function atBlockStart(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
    return null;
  return $cursor;
}
var joinBackward = (state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  if (!$cut) {
    let range2 = $cursor.blockRange(), target2 = range2 && liftTarget(range2);
    if (target2 == null)
      return false;
    if (dispatch)
      dispatch(state.tr.lift(range2, target2).scrollIntoView());
    return true;
  }
  let before = $cut.nodeBefore;
  if (deleteBarrier(state, $cut, dispatch, -1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) {
    for (let depth = $cursor.depth; ; depth--) {
      let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);
      if (delStep && delStep.slice.size < delStep.to - delStep.from) {
        if (dispatch) {
          let tr = state.tr.step(delStep);
          tr.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));
          dispatch(tr.scrollIntoView());
        }
        return true;
      }
      if (depth == 1 || $cursor.node(depth - 1).childCount > 1)
        break;
    }
  }
  if (before.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
    return true;
  }
  return false;
};
function textblockAt(node, side, only = false) {
  for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
    if (scan.isTextblock)
      return true;
    if (only && scan.childCount != 1)
      return false;
  }
  return false;
}
var selectNodeBackward = (state, dispatch, view) => {
  let { $head, empty: empty3 } = state.selection, $cut = $head;
  if (!empty3)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
      return false;
    $cut = findCutBefore($head);
  }
  let node = $cut && $cut.nodeBefore;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
  return true;
};
function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i = $pos.depth - 1; i >= 0; i--) {
      if ($pos.index(i) > 0)
        return $pos.doc.resolve($pos.before(i + 1));
      if ($pos.node(i).type.spec.isolating)
        break;
    }
  return null;
}
function atBlockEnd(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
    return null;
  return $cursor;
}
var joinForward = (state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  if (!$cut)
    return false;
  let after = $cut.nodeAfter;
  if (deleteBarrier(state, $cut, dispatch, 1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr = state.tr.step(delStep);
        tr.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));
        dispatch(tr.scrollIntoView());
      }
      return true;
    }
  }
  if (after.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
    return true;
  }
  return false;
};
var selectNodeForward = (state, dispatch, view) => {
  let { $head, empty: empty3 } = state.selection, $cut = $head;
  if (!empty3)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
      return false;
    $cut = findCutAfter($head);
  }
  let node = $cut && $cut.nodeAfter;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  return true;
};
function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i = $pos.depth - 1; i >= 0; i--) {
      let parent = $pos.node(i);
      if ($pos.index(i) + 1 < parent.childCount)
        return $pos.doc.resolve($pos.after(i + 1));
      if (parent.type.spec.isolating)
        break;
    }
  return null;
}
var newlineInCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  if (dispatch)
    dispatch(state.tr.insertText("\n").scrollIntoView());
  return true;
};
function defaultBlockAt(match) {
  for (let i = 0; i < match.edgeCount; i++) {
    let { type } = match.edge(i);
    if (type.isTextblock && !type.hasRequiredAttrs())
      return type;
  }
  return null;
}
var exitCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));
  if (!type || !above.canReplaceWith(after, after, type))
    return false;
  if (dispatch) {
    let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));
    dispatch(tr.scrollIntoView());
  }
  return true;
};
var createParagraphNear = (state, dispatch) => {
  let sel = state.selection, { $from, $to } = sel;
  if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
    return false;
  let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
  if (!type || !type.isTextblock)
    return false;
  if (dispatch) {
    let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    let tr = state.tr.insert(side, type.createAndFill());
    tr.setSelection(TextSelection.create(tr.doc, side + 1));
    dispatch(tr.scrollIntoView());
  }
  return true;
};
var liftEmptyBlock = (state, dispatch) => {
  let { $cursor } = state.selection;
  if (!$cursor || $cursor.parent.content.size)
    return false;
  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    let before = $cursor.before();
    if (canSplit(state.doc, before)) {
      if (dispatch)
        dispatch(state.tr.split(before).scrollIntoView());
      return true;
    }
  }
  let range2 = $cursor.blockRange(), target2 = range2 && liftTarget(range2);
  if (target2 == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range2, target2).scrollIntoView());
  return true;
};
function splitBlockAs(splitNode) {
  return (state, dispatch) => {
    let { $from, $to } = state.selection;
    if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
      if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
        return false;
      if (dispatch)
        dispatch(state.tr.split($from.pos).scrollIntoView());
      return true;
    }
    if (!$from.depth)
      return false;
    let types = [];
    let splitDepth, deflt, atEnd = false, atStart = false;
    for (let d = $from.depth; ; d--) {
      let node = $from.node(d);
      if (node.isBlock) {
        atEnd = $from.end(d) == $from.pos + ($from.depth - d);
        atStart = $from.start(d) == $from.pos - ($from.depth - d);
        deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));
        let splitType = splitNode && splitNode($to.parent, atEnd, $from);
        types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));
        splitDepth = d;
        break;
      } else {
        if (d == 1)
          return false;
        types.unshift(null);
      }
    }
    let tr = state.tr;
    if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
      tr.deleteSelection();
    let splitPos = tr.mapping.map($from.pos);
    let can = canSplit(tr.doc, splitPos, types.length, types);
    if (!can) {
      types[0] = deflt ? { type: deflt } : null;
      can = canSplit(tr.doc, splitPos, types.length, types);
    }
    if (!can)
      return false;
    tr.split(splitPos, types.length, types);
    if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {
      let first = tr.mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);
      if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))
        tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt);
    }
    if (dispatch)
      dispatch(tr.scrollIntoView());
    return true;
  };
}
var splitBlock = splitBlockAs();
var selectAll = (state, dispatch) => {
  if (dispatch)
    dispatch(state.tr.setSelection(new AllSelection(state.doc)));
  return true;
};
function joinMaybeClear(state, $pos, dispatch) {
  let before = $pos.nodeBefore, after = $pos.nodeAfter, index2 = $pos.index();
  if (!before || !after || !before.type.compatibleContent(after.type))
    return false;
  if (!before.content.size && $pos.parent.canReplace(index2 - 1, index2)) {
    if (dispatch)
      dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
    return true;
  }
  if (!$pos.parent.canReplace(index2, index2 + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))
    return false;
  if (dispatch)
    dispatch(state.tr.join($pos.pos).scrollIntoView());
  return true;
}
function deleteBarrier(state, $cut, dispatch, dir) {
  let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;
  let isolated = before.type.spec.isolating || after.type.spec.isolating;
  if (!isolated && joinMaybeClear(state, $cut, dispatch))
    return true;
  let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) {
    if (dispatch) {
      let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty;
      for (let i = conn.length - 1; i >= 0; i--)
        wrap2 = Fragment.from(conn[i].create(null, wrap2));
      wrap2 = Fragment.from(before.copy(wrap2));
      let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true));
      let $joinAt = tr.doc.resolve(end + 2 * conn.length);
      if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr.doc, $joinAt.pos))
        tr.join($joinAt.pos);
      dispatch(tr.scrollIntoView());
    }
    return true;
  }
  let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1);
  let range2 = selAfter && selAfter.$from.blockRange(selAfter.$to), target2 = range2 && liftTarget(range2);
  if (target2 != null && target2 >= $cut.depth) {
    if (dispatch)
      dispatch(state.tr.lift(range2, target2).scrollIntoView());
    return true;
  }
  if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
    let at = before, wrap2 = [];
    for (; ; ) {
      wrap2.push(at);
      if (at.isTextblock)
        break;
      at = at.lastChild;
    }
    let afterText = after, afterDepth = 1;
    for (; !afterText.isTextblock; afterText = afterText.firstChild)
      afterDepth++;
    if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
      if (dispatch) {
        let end = Fragment.empty;
        for (let i = wrap2.length - 1; i >= 0; i--)
          end = Fragment.from(wrap2[i].copy(end));
        let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true));
        dispatch(tr.scrollIntoView());
      }
      return true;
    }
  }
  return false;
}
function selectTextblockSide(side) {
  return function(state, dispatch) {
    let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
    let depth = $pos.depth;
    while ($pos.node(depth).isInline) {
      if (!depth)
        return false;
      depth--;
    }
    if (!$pos.node(depth).isTextblock)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
    return true;
  };
}
var selectTextblockStart = selectTextblockSide(-1);
var selectTextblockEnd = selectTextblockSide(1);
function wrapIn(nodeType, attrs = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range2 = $from.blockRange($to), wrapping = range2 && findWrapping(range2, nodeType, attrs);
    if (!wrapping)
      return false;
    if (dispatch)
      dispatch(state.tr.wrap(range2, wrapping).scrollIntoView());
    return true;
  };
}
function setBlockType2(nodeType, attrs = null) {
  return function(state, dispatch) {
    let applicable = false;
    for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {
      let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i];
      state.doc.nodesBetween(from2, to, (node, pos) => {
        if (applicable)
          return false;
        if (!node.isTextblock || node.hasMarkup(nodeType, attrs))
          return;
        if (node.type == nodeType) {
          applicable = true;
        } else {
          let $pos = state.doc.resolve(pos), index2 = $pos.index();
          applicable = $pos.parent.canReplaceWith(index2, index2 + 1, nodeType);
        }
      });
    }
    if (!applicable)
      return false;
    if (dispatch) {
      let tr = state.tr;
      for (let i = 0; i < state.selection.ranges.length; i++) {
        let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i];
        tr.setBlockType(from2, to, nodeType, attrs);
      }
      dispatch(tr.scrollIntoView());
    }
    return true;
  };
}
function markApplies(doc3, ranges, type, enterAtoms) {
  for (let i = 0; i < ranges.length; i++) {
    let { $from, $to } = ranges[i];
    let can = $from.depth == 0 ? doc3.inlineContent && doc3.type.allowsMarkType(type) : false;
    doc3.nodesBetween($from.pos, $to.pos, (node, pos) => {
      if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)
        return false;
      can = node.inlineContent && node.type.allowsMarkType(type);
    });
    if (can)
      return true;
  }
  return false;
}
function removeInlineAtoms(ranges) {
  let result = [];
  for (let i = 0; i < ranges.length; i++) {
    let { $from, $to } = ranges[i];
    $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
      if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {
        if (pos + 1 > $from.pos)
          result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));
        $from = $from.doc.resolve(pos + 1 + node.content.size);
        return false;
      }
    });
    if ($from.pos < $to.pos)
      result.push(new SelectionRange($from, $to));
  }
  return result;
}
function toggleMark(markType, attrs = null, options) {
  let removeWhenPresent = (options && options.removeWhenPresent) !== false;
  let enterAtoms = (options && options.enterInlineAtoms) !== false;
  let dropSpace = !(options && options.includeWhitespace);
  return function(state, dispatch) {
    let { empty: empty3, $cursor, ranges } = state.selection;
    if (empty3 && !$cursor || !markApplies(state.doc, ranges, markType, enterAtoms))
      return false;
    if (dispatch) {
      if ($cursor) {
        if (markType.isInSet(state.storedMarks || $cursor.marks()))
          dispatch(state.tr.removeStoredMark(markType));
        else
          dispatch(state.tr.addStoredMark(markType.create(attrs)));
      } else {
        let add, tr = state.tr;
        if (!enterAtoms)
          ranges = removeInlineAtoms(ranges);
        if (removeWhenPresent) {
          add = !ranges.some((r) => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));
        } else {
          add = !ranges.every((r) => {
            let missing = false;
            tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {
              if (missing)
                return false;
              missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) && !(node.isText && /^\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));
            });
            return !missing;
          });
        }
        for (let i = 0; i < ranges.length; i++) {
          let { $from, $to } = ranges[i];
          if (!add) {
            tr.removeMark($from.pos, $to.pos, markType);
          } else {
            let from2 = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;
            let spaceStart = dropSpace && start && start.isText ? /^\s*/.exec(start.text)[0].length : 0;
            let spaceEnd = dropSpace && end && end.isText ? /\s*$/.exec(end.text)[0].length : 0;
            if (from2 + spaceStart < to) {
              from2 += spaceStart;
              to -= spaceEnd;
            }
            tr.addMark(from2, to, markType.create(attrs));
          }
        }
        dispatch(tr.scrollIntoView());
      }
    }
    return true;
  };
}
function chainCommands(...commands) {
  return function(state, dispatch, view) {
    for (let i = 0; i < commands.length; i++)
      if (commands[i](state, dispatch, view))
        return true;
    return false;
  };
}
var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
var del = chainCommands(deleteSelection, joinForward, selectNodeForward);
var pcBaseKeymap = {
  "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
  "Mod-Enter": exitCode,
  "Backspace": backspace,
  "Mod-Backspace": backspace,
  "Shift-Backspace": backspace,
  "Delete": del,
  "Mod-Delete": del,
  "Mod-a": selectAll
};
var macBaseKeymap = {
  "Ctrl-h": pcBaseKeymap["Backspace"],
  "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  "Ctrl-d": pcBaseKeymap["Delete"],
  "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  "Alt-d": pcBaseKeymap["Mod-Delete"],
  "Ctrl-a": selectTextblockStart,
  "Ctrl-e": selectTextblockEnd
};
for (let key in pcBaseKeymap)
  macBaseKeymap[key] = pcBaseKeymap[key];
var mac4 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;
var baseKeymap = mac4 ? macBaseKeymap : pcBaseKeymap;

// node_modules/prosemirror-inputrules/dist/index.js
var InputRule = class {
  /**
  Create an input rule. The rule applies when the user typed
  something and the text directly in front of the cursor matches
  `match`, which should end with `$`.
  
  The `handler` can be a string, in which case the matched text, or
  the first matched group in the regexp, is replaced by that
  string.
  
  Or a it can be a function, which will be called with the match
  array produced by
  [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
  as well as the start and end of the matched range, and which can
  return a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) that describes the
  rule's effect, or null to indicate the input was not handled.
  */
  constructor(match, handler, options = {}) {
    this.match = match;
    this.match = match;
    this.handler = typeof handler == "string" ? stringHandler(handler) : handler;
    this.undoable = options.undoable !== false;
    this.inCode = options.inCode || false;
    this.inCodeMark = options.inCodeMark !== false;
  }
};
function stringHandler(string) {
  return function(state, match, start, end) {
    let insert = string;
    if (match[1]) {
      let offset = match[0].lastIndexOf(match[1]);
      insert += match[0].slice(offset + match[1].length);
      start += offset;
      let cutOff = start - end;
      if (cutOff > 0) {
        insert = match[0].slice(offset - cutOff, offset) + insert;
        start = end;
      }
    }
    return state.tr.insertText(insert, start, end);
  };
}
var MAX_MATCH = 500;
function inputRules({ rules }) {
  let plugin = new Plugin({
    state: {
      init() {
        return null;
      },
      apply(tr, prev) {
        let stored = tr.getMeta(this);
        if (stored)
          return stored;
        return tr.selectionSet || tr.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput(view, from2, to, text2) {
        return run(view, from2, to, text2, rules, plugin);
      },
      handleDOMEvents: {
        compositionend: (view) => {
          setTimeout(() => {
            let { $cursor } = view.state.selection;
            if ($cursor)
              run(view, $cursor.pos, $cursor.pos, "", rules, plugin);
          });
        }
      }
    },
    isInputRules: true
  });
  return plugin;
}
function run(view, from2, to, text2, rules, plugin) {
  if (view.composing)
    return false;
  let state = view.state, $from = state.doc.resolve(from2);
  let textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, null, "\uFFFC") + text2;
  for (let i = 0; i < rules.length; i++) {
    let rule = rules[i];
    if (!rule.inCodeMark && $from.marks().some((m) => m.type.spec.code))
      continue;
    if ($from.parent.type.spec.code) {
      if (!rule.inCode)
        continue;
    } else if (rule.inCode === "only") {
      continue;
    }
    let match = rule.match.exec(textBefore);
    if (!match || match[0].length < text2.length)
      continue;
    let startPos = from2 - (match[0].length - text2.length);
    if (!rule.inCodeMark) {
      let hasMark = false;
      state.doc.nodesBetween(startPos, $from.pos, (node) => {
        if (node.isInline && node.marks.some((m) => m.type.spec.code))
          hasMark = true;
      });
      if (hasMark)
        continue;
    }
    let tr = rule.handler(state, match, startPos, to);
    if (!tr)
      continue;
    if (rule.undoable)
      tr.setMeta(plugin, { transform: tr, from: from2, to, text: text2 });
    view.dispatch(tr);
    return true;
  }
  return false;
}
var undoInputRule = (state, dispatch) => {
  let plugins = state.plugins;
  for (let i = 0; i < plugins.length; i++) {
    let plugin = plugins[i], undoable;
    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
      if (dispatch) {
        let tr = state.tr, toUndo = undoable.transform;
        for (let j = toUndo.steps.length - 1; j >= 0; j--)
          tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
        if (undoable.text) {
          let marks = tr.doc.resolve(undoable.from).marks();
          tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
        } else {
          tr.delete(undoable.from, undoable.to);
        }
        dispatch(tr);
      }
      return true;
    }
  }
  return false;
};
var emDash = new InputRule(/--$/, "\u2014", { inCodeMark: false });
var ellipsis = new InputRule(/\.\.\.$/, "\u2026", { inCodeMark: false });
var openDoubleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/, "\u201C", { inCodeMark: false });
var closeDoubleQuote = new InputRule(/"$/, "\u201D", { inCodeMark: false });
var openSingleQuote = new InputRule(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/, "\u2018", { inCodeMark: false });
var closeSingleQuote = new InputRule(/'$/, "\u2019", { inCodeMark: false });

// node_modules/rope-sequence/dist/index.js
var GOOD_LEAF_SIZE = 200;
var RopeSequence = function RopeSequence2() {
};
RopeSequence.prototype.append = function append(other) {
  if (!other.length) {
    return this;
  }
  other = RopeSequence.from(other);
  return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
};
RopeSequence.prototype.prepend = function prepend(other) {
  if (!other.length) {
    return this;
  }
  return RopeSequence.from(other).append(this);
};
RopeSequence.prototype.appendInner = function appendInner(other) {
  return new Append(this, other);
};
RopeSequence.prototype.slice = function slice(from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 >= to) {
    return RopeSequence.empty;
  }
  return this.sliceInner(Math.max(0, from2), Math.min(this.length, to));
};
RopeSequence.prototype.get = function get(i) {
  if (i < 0 || i >= this.length) {
    return void 0;
  }
  return this.getInner(i);
};
RopeSequence.prototype.forEach = function forEach(f, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 <= to) {
    this.forEachInner(f, from2, to, 0);
  } else {
    this.forEachInvertedInner(f, from2, to, 0);
  }
};
RopeSequence.prototype.map = function map(f, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  var result = [];
  this.forEach(function(elt, i) {
    return result.push(f(elt, i));
  }, from2, to);
  return result;
};
RopeSequence.from = function from(values) {
  if (values instanceof RopeSequence) {
    return values;
  }
  return values && values.length ? new Leaf(values) : RopeSequence.empty;
};
var Leaf = /* @__PURE__ */ (function(RopeSequence3) {
  function Leaf2(values) {
    RopeSequence3.call(this);
    this.values = values;
  }
  if (RopeSequence3) Leaf2.__proto__ = RopeSequence3;
  Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Leaf2.prototype.constructor = Leaf2;
  var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } };
  Leaf2.prototype.flatten = function flatten() {
    return this.values;
  };
  Leaf2.prototype.sliceInner = function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    return new Leaf2(this.values.slice(from2, to));
  };
  Leaf2.prototype.getInner = function getInner(i) {
    return this.values[i];
  };
  Leaf2.prototype.forEachInner = function forEachInner(f, from2, to, start) {
    for (var i = from2; i < to; i++) {
      if (f(this.values[i], start + i) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) {
    for (var i = from2 - 1; i >= to; i--) {
      if (f(this.values[i], start + i) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.leafAppend = function leafAppend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(this.values.concat(other.flatten()));
    }
  };
  Leaf2.prototype.leafPrepend = function leafPrepend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(other.flatten().concat(this.values));
    }
  };
  prototypeAccessors.length.get = function() {
    return this.values.length;
  };
  prototypeAccessors.depth.get = function() {
    return 0;
  };
  Object.defineProperties(Leaf2.prototype, prototypeAccessors);
  return Leaf2;
})(RopeSequence);
RopeSequence.empty = new Leaf([]);
var Append = /* @__PURE__ */ (function(RopeSequence3) {
  function Append2(left, right) {
    RopeSequence3.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }
  if (RopeSequence3) Append2.__proto__ = RopeSequence3;
  Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Append2.prototype.constructor = Append2;
  Append2.prototype.flatten = function flatten() {
    return this.left.flatten().concat(this.right.flatten());
  };
  Append2.prototype.getInner = function getInner(i) {
    return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);
  };
  Append2.prototype.forEachInner = function forEachInner(f, from2, to, start) {
    var leftLen = this.left.length;
    if (from2 < leftLen && this.left.forEachInner(f, from2, Math.min(to, leftLen), start) === false) {
      return false;
    }
    if (to > leftLen && this.right.forEachInner(f, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) {
      return false;
    }
  };
  Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) {
    var leftLen = this.left.length;
    if (from2 > leftLen && this.right.forEachInvertedInner(f, from2 - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) {
      return false;
    }
    if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from2, leftLen), to, start) === false) {
      return false;
    }
  };
  Append2.prototype.sliceInner = function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    var leftLen = this.left.length;
    if (to <= leftLen) {
      return this.left.slice(from2, to);
    }
    if (from2 >= leftLen) {
      return this.right.slice(from2 - leftLen, to - leftLen);
    }
    return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen));
  };
  Append2.prototype.leafAppend = function leafAppend(other) {
    var inner = this.right.leafAppend(other);
    if (inner) {
      return new Append2(this.left, inner);
    }
  };
  Append2.prototype.leafPrepend = function leafPrepend(other) {
    var inner = this.left.leafPrepend(other);
    if (inner) {
      return new Append2(inner, this.right);
    }
  };
  Append2.prototype.appendInner = function appendInner2(other) {
    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {
      return new Append2(this.left, new Append2(this.right, other));
    }
    return new Append2(this, other);
  };
  return Append2;
})(RopeSequence);
var dist_default2 = RopeSequence;

// node_modules/prosemirror-history/dist/index.js
var max_empty_items = 500;
var Branch = class _Branch {
  constructor(items, eventCount) {
    this.items = items;
    this.eventCount = eventCount;
  }
  // Pop the latest event off the branch's history and apply it
  // to a document transform.
  popEvent(state, preserveItems) {
    if (this.eventCount == 0)
      return null;
    let end = this.items.length;
    for (; ; end--) {
      let next = this.items.get(end - 1);
      if (next.selection) {
        --end;
        break;
      }
    }
    let remap, mapFrom;
    if (preserveItems) {
      remap = this.remapping(end, this.items.length);
      mapFrom = remap.maps.length;
    }
    let transform = state.tr;
    let selection, remaining;
    let addAfter = [], addBefore = [];
    this.items.forEach((item2, i) => {
      if (!item2.step) {
        if (!remap) {
          remap = this.remapping(end, i + 1);
          mapFrom = remap.maps.length;
        }
        mapFrom--;
        addBefore.push(item2);
        return;
      }
      if (remap) {
        addBefore.push(new Item(item2.map));
        let step = item2.step.map(remap.slice(mapFrom)), map3;
        if (step && transform.maybeStep(step).doc) {
          map3 = transform.mapping.maps[transform.mapping.maps.length - 1];
          addAfter.push(new Item(map3, void 0, void 0, addAfter.length + addBefore.length));
        }
        mapFrom--;
        if (map3)
          remap.appendMap(map3, mapFrom);
      } else {
        transform.maybeStep(item2.step);
      }
      if (item2.selection) {
        selection = remap ? item2.selection.map(remap.slice(mapFrom)) : item2.selection;
        remaining = new _Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);
        return false;
      }
    }, this.items.length, 0);
    return { remaining, transform, selection };
  }
  // Create a new branch with the given transform added.
  addTransform(transform, selection, histOptions, preserveItems) {
    let newItems = [], eventCount = this.eventCount;
    let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
    for (let i = 0; i < transform.steps.length; i++) {
      let step = transform.steps[i].invert(transform.docs[i]);
      let item2 = new Item(transform.mapping.maps[i], step, selection), merged;
      if (merged = lastItem && lastItem.merge(item2)) {
        item2 = merged;
        if (i)
          newItems.pop();
        else
          oldItems = oldItems.slice(0, oldItems.length - 1);
      }
      newItems.push(item2);
      if (selection) {
        eventCount++;
        selection = void 0;
      }
      if (!preserveItems)
        lastItem = item2;
    }
    let overflow = eventCount - histOptions.depth;
    if (overflow > DEPTH_OVERFLOW) {
      oldItems = cutOffEvents(oldItems, overflow);
      eventCount -= overflow;
    }
    return new _Branch(oldItems.append(newItems), eventCount);
  }
  remapping(from2, to) {
    let maps = new Mapping();
    this.items.forEach((item2, i) => {
      let mirrorPos = item2.mirrorOffset != null && i - item2.mirrorOffset >= from2 ? maps.maps.length - item2.mirrorOffset : void 0;
      maps.appendMap(item2.map, mirrorPos);
    }, from2, to);
    return maps;
  }
  addMaps(array) {
    if (this.eventCount == 0)
      return this;
    return new _Branch(this.items.append(array.map((map3) => new Item(map3))), this.eventCount);
  }
  // When the collab module receives remote changes, the history has
  // to know about those, so that it can adjust the steps that were
  // rebased on top of the remote changes, and include the position
  // maps for the remote changes in its array of items.
  rebased(rebasedTransform, rebasedCount) {
    if (!this.eventCount)
      return this;
    let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);
    let mapping = rebasedTransform.mapping;
    let newUntil = rebasedTransform.steps.length;
    let eventCount = this.eventCount;
    this.items.forEach((item2) => {
      if (item2.selection)
        eventCount--;
    }, start);
    let iRebased = rebasedCount;
    this.items.forEach((item2) => {
      let pos = mapping.getMirror(--iRebased);
      if (pos == null)
        return;
      newUntil = Math.min(newUntil, pos);
      let map3 = mapping.maps[pos];
      if (item2.step) {
        let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
        let selection = item2.selection && item2.selection.map(mapping.slice(iRebased + 1, pos));
        if (selection)
          eventCount++;
        rebasedItems.push(new Item(map3, step, selection));
      } else {
        rebasedItems.push(new Item(map3));
      }
    }, start);
    let newMaps = [];
    for (let i = rebasedCount; i < newUntil; i++)
      newMaps.push(new Item(mapping.maps[i]));
    let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);
    let branch = new _Branch(items, eventCount);
    if (branch.emptyItemCount() > max_empty_items)
      branch = branch.compress(this.items.length - rebasedItems.length);
    return branch;
  }
  emptyItemCount() {
    let count = 0;
    this.items.forEach((item2) => {
      if (!item2.step)
        count++;
    });
    return count;
  }
  // Compressing a branch means rewriting it to push the air (map-only
  // items) out. During collaboration, these naturally accumulate
  // because each remote change adds one. The `upto` argument is used
  // to ensure that only the items below a given level are compressed,
  // because `rebased` relies on a clean, untouched set of items in
  // order to associate old items with rebased steps.
  compress(upto = this.items.length) {
    let remap = this.remapping(0, upto), mapFrom = remap.maps.length;
    let items = [], events = 0;
    this.items.forEach((item2, i) => {
      if (i >= upto) {
        items.push(item2);
        if (item2.selection)
          events++;
      } else if (item2.step) {
        let step = item2.step.map(remap.slice(mapFrom)), map3 = step && step.getMap();
        mapFrom--;
        if (map3)
          remap.appendMap(map3, mapFrom);
        if (step) {
          let selection = item2.selection && item2.selection.map(remap.slice(mapFrom));
          if (selection)
            events++;
          let newItem = new Item(map3.invert(), step, selection), merged, last2 = items.length - 1;
          if (merged = items.length && items[last2].merge(newItem))
            items[last2] = merged;
          else
            items.push(newItem);
        }
      } else if (item2.map) {
        mapFrom--;
      }
    }, this.items.length, 0);
    return new _Branch(dist_default2.from(items.reverse()), events);
  }
};
Branch.empty = new Branch(dist_default2.empty, 0);
function cutOffEvents(items, n) {
  let cutPoint;
  items.forEach((item2, i) => {
    if (item2.selection && n-- == 0) {
      cutPoint = i;
      return false;
    }
  });
  return items.slice(cutPoint);
}
var Item = class _Item {
  constructor(map3, step, selection, mirrorOffset) {
    this.map = map3;
    this.step = step;
    this.selection = selection;
    this.mirrorOffset = mirrorOffset;
  }
  merge(other) {
    if (this.step && other.step && !other.selection) {
      let step = other.step.merge(this.step);
      if (step)
        return new _Item(step.getMap().invert(), step, this.selection);
    }
  }
};
var HistoryState = class {
  constructor(done, undone, prevRanges, prevTime, prevComposition) {
    this.done = done;
    this.undone = undone;
    this.prevRanges = prevRanges;
    this.prevTime = prevTime;
    this.prevComposition = prevComposition;
  }
};
var DEPTH_OVERFLOW = 20;
function applyTransaction(history2, state, tr, options) {
  let historyTr = tr.getMeta(historyKey), rebased;
  if (historyTr)
    return historyTr.historyState;
  if (tr.getMeta(closeHistoryKey))
    history2 = new HistoryState(history2.done, history2.undone, null, 0, -1);
  let appended = tr.getMeta("appendedTransaction");
  if (tr.steps.length == 0) {
    return history2;
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo)
      return new HistoryState(history2.done.addTransform(tr, void 0, options, mustPreserveItems(state)), history2.undone, rangesFor(tr.mapping.maps), history2.prevTime, history2.prevComposition);
    else
      return new HistoryState(history2.done, history2.undone.addTransform(tr, void 0, options, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition);
  } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    let composition = tr.getMeta("composition");
    let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history2.prevRanges));
    let prevRanges = appended ? mapRanges(history2.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);
    return new HistoryState(history2.done.addTransform(tr, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history2.prevComposition : composition);
  } else if (rebased = tr.getMeta("rebased")) {
    return new HistoryState(history2.done.rebased(tr, rebased), history2.undone.rebased(tr, rebased), mapRanges(history2.prevRanges, tr.mapping), history2.prevTime, history2.prevComposition);
  } else {
    return new HistoryState(history2.done.addMaps(tr.mapping.maps), history2.undone.addMaps(tr.mapping.maps), mapRanges(history2.prevRanges, tr.mapping), history2.prevTime, history2.prevComposition);
  }
}
function isAdjacentTo(transform, prevRanges) {
  if (!prevRanges)
    return false;
  if (!transform.docChanged)
    return true;
  let adjacent = false;
  transform.mapping.maps[0].forEach((start, end) => {
    for (let i = 0; i < prevRanges.length; i += 2)
      if (start <= prevRanges[i + 1] && end >= prevRanges[i])
        adjacent = true;
  });
  return adjacent;
}
function rangesFor(maps) {
  let result = [];
  for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)
    maps[i].forEach((_from, _to, from2, to) => result.push(from2, to));
  return result;
}
function mapRanges(ranges, mapping) {
  if (!ranges)
    return null;
  let result = [];
  for (let i = 0; i < ranges.length; i += 2) {
    let from2 = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);
    if (from2 <= to)
      result.push(from2, to);
  }
  return result;
}
function histTransaction(history2, state, redo2) {
  let preserveItems = mustPreserveItems(state);
  let histOptions = historyKey.get(state).spec.config;
  let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems);
  if (!pop)
    return null;
  let selection = pop.selection.resolve(pop.transform.doc);
  let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
  let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1);
  return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist });
}
var cachedPreserveItems = false;
var cachedPreserveItemsPlugins = null;
function mustPreserveItems(state) {
  let plugins = state.plugins;
  if (cachedPreserveItemsPlugins != plugins) {
    cachedPreserveItems = false;
    cachedPreserveItemsPlugins = plugins;
    for (let i = 0; i < plugins.length; i++)
      if (plugins[i].spec.historyPreserveItems) {
        cachedPreserveItems = true;
        break;
      }
  }
  return cachedPreserveItems;
}
var historyKey = new PluginKey("history");
var closeHistoryKey = new PluginKey("closeHistory");
function history(config = {}) {
  config = {
    depth: config.depth || 100,
    newGroupDelay: config.newGroupDelay || 500
  };
  return new Plugin({
    key: historyKey,
    state: {
      init() {
        return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
      },
      apply(tr, hist, state) {
        return applyTransaction(hist, state, tr, config);
      }
    },
    config,
    props: {
      handleDOMEvents: {
        beforeinput(view, e) {
          let inputType = e.inputType;
          let command = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null;
          if (!command || !view.editable)
            return false;
          e.preventDefault();
          return command(view.state, view.dispatch);
        }
      }
    }
  });
}
function buildCommand(redo2, scroll) {
  return (state, dispatch) => {
    let hist = historyKey.getState(state);
    if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0)
      return false;
    if (dispatch) {
      let tr = histTransaction(hist, state, redo2);
      if (tr)
        dispatch(scroll ? tr.scrollIntoView() : tr);
    }
    return true;
  };
}
var undo = buildCommand(false, true);
var redo = buildCommand(true, true);
var undoNoScroll = buildCommand(false, false);
var redoNoScroll = buildCommand(true, false);
function undoDepth(state) {
  let hist = historyKey.getState(state);
  return hist ? hist.done.eventCount : 0;
}

// node_modules/@toast-ui/editor/dist/esm/index.js
var extendStatics$1 = function(d, b) {
  extendStatics$1 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
  };
  return extendStatics$1(d, b);
};
function __extends$1(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics$1(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$1 = function() {
  __assign$1 = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign$1.apply(this, arguments);
};
function __spreadArray$1(to, from2, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from2.length, ar; i < l; i++) {
    if (ar || !(i in from2)) {
      if (!ar) ar = Array.prototype.slice.call(from2, 0, i);
      ar[i] = from2[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from2));
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function forEachOwnProperties$2(obj, iteratee, context) {
  var key;
  context = context || null;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (iteratee.call(context, obj[key], key, obj) === false) {
        break;
      }
    }
  }
}
var forEachOwnProperties_1 = forEachOwnProperties$2;
function extend(target2, objects) {
  var hasOwnProp = Object.prototype.hasOwnProperty;
  var source, prop2, i, len;
  for (i = 1, len = arguments.length; i < len; i += 1) {
    source = arguments[i];
    for (prop2 in source) {
      if (hasOwnProp.call(source, prop2)) {
        target2[prop2] = source[prop2];
      }
    }
  }
  return target2;
}
var extend_1 = extend;
function isString$3(obj) {
  return typeof obj === "string" || obj instanceof String;
}
var isString_1 = isString$3;
function isArray$3(obj) {
  return obj instanceof Array;
}
var isArray_1 = isArray$3;
function forEachArray$3(arr, iteratee, context) {
  var index2 = 0;
  var len = arr.length;
  context = context || null;
  for (; index2 < len; index2 += 1) {
    if (iteratee.call(context, arr[index2], index2, arr) === false) {
      break;
    }
  }
}
var forEachArray_1 = forEachArray$3;
var isArray$2 = isArray_1;
var forEachArray$2 = forEachArray_1;
var forEachOwnProperties$1 = forEachOwnProperties_1;
function forEach$4(obj, iteratee, context) {
  if (isArray$2(obj)) {
    forEachArray$2(obj, iteratee, context);
  } else {
    forEachOwnProperties$1(obj, iteratee, context);
  }
}
var forEach_1 = forEach$4;
var isString$2 = isString_1;
var forEach$3 = forEach_1;
function css(element, key, value) {
  var style = element.style;
  if (isString$2(key)) {
    style[key] = value;
    return;
  }
  forEach$3(key, function(v, k) {
    style[k] = v;
  });
}
var css_1 = css;
var isArray$1 = isArray_1;
function inArray$4(searchElement, array, startIndex) {
  var i;
  var length;
  startIndex = startIndex || 0;
  if (!isArray$1(array)) {
    return -1;
  }
  if (Array.prototype.indexOf) {
    return Array.prototype.indexOf.call(array, searchElement, startIndex);
  }
  length = array.length;
  for (i = startIndex; startIndex >= 0 && i < length; i += 1) {
    if (array[i] === searchElement) {
      return i;
    }
  }
  return -1;
}
var inArray_1 = inArray$4;
function isUndefined$4(obj) {
  return obj === void 0;
}
var isUndefined_1 = isUndefined$4;
var isUndefined$3 = isUndefined_1;
function getClass$3(element) {
  if (!element || !element.className) {
    return "";
  }
  if (isUndefined$3(element.className.baseVal)) {
    return element.className;
  }
  return element.className.baseVal;
}
var getClass_1 = getClass$3;
var isArray = isArray_1;
var isUndefined$2 = isUndefined_1;
function setClassName$2(element, cssClass) {
  cssClass = isArray(cssClass) ? cssClass.join(" ") : cssClass;
  cssClass = cssClass.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
  if (isUndefined$2(element.className.baseVal)) {
    element.className = cssClass;
    return;
  }
  element.className.baseVal = cssClass;
}
var _setClassName = setClassName$2;
var forEach$2 = forEach_1;
var inArray$3 = inArray_1;
var getClass$2 = getClass_1;
var setClassName$1 = _setClassName;
function addClass(element) {
  var cssClass = Array.prototype.slice.call(arguments, 1);
  var classList = element.classList;
  var newClass = [];
  var origin;
  if (classList) {
    forEach$2(cssClass, function(name) {
      element.classList.add(name);
    });
    return;
  }
  origin = getClass$2(element);
  if (origin) {
    cssClass = [].concat(origin.split(/\s+/), cssClass);
  }
  forEach$2(cssClass, function(cls2) {
    if (inArray$3(cls2, newClass) < 0) {
      newClass.push(cls2);
    }
  });
  setClassName$1(element, newClass);
}
var addClass_1 = addClass;
var forEachArray$1 = forEachArray_1;
var inArray$2 = inArray_1;
var getClass$1 = getClass_1;
var setClassName = _setClassName;
function removeClass(element) {
  var cssClass = Array.prototype.slice.call(arguments, 1);
  var classList = element.classList;
  var origin, newClass;
  if (classList) {
    forEachArray$1(cssClass, function(name) {
      classList.remove(name);
    });
    return;
  }
  origin = getClass$1(element).split(/\s+/);
  newClass = [];
  forEachArray$1(origin, function(name) {
    if (inArray$2(name, cssClass) < 0) {
      newClass.push(name);
    }
  });
  setClassName(element, newClass);
}
var removeClass_1 = removeClass;
function isNumber(obj) {
  return typeof obj === "number" || obj instanceof Number;
}
var isNumber_1 = isNumber;
function isNull$1(obj) {
  return obj === null;
}
var isNull_1 = isNull$1;
var forEachOwnProperties = forEachOwnProperties_1;
function imagePing$1(url, trackingInfo) {
  var trackingElement = document.createElement("img");
  var queryString = "";
  forEachOwnProperties(trackingInfo, function(value, key) {
    queryString += "&" + key + "=" + value;
  });
  queryString = queryString.substring(1);
  trackingElement.src = url + "?" + queryString;
  trackingElement.style.display = "none";
  document.body.appendChild(trackingElement);
  document.body.removeChild(trackingElement);
  return trackingElement;
}
var imagePing_1 = imagePing$1;
var isUndefined$1 = isUndefined_1;
var imagePing = imagePing_1;
var ms7days = 7 * 24 * 60 * 60 * 1e3;
function isExpired(date) {
  var now = (/* @__PURE__ */ new Date()).getTime();
  return now - date > ms7days;
}
function sendHostname(appName, trackingId) {
  var url = "https://www.google-analytics.com/collect";
  var hostname = location.hostname;
  var hitType = "event";
  var eventCategory = "use";
  var applicationKeyForStorage = "TOAST UI " + appName + " for " + hostname + ": Statistics";
  var date = window.localStorage.getItem(applicationKeyForStorage);
  if (!isUndefined$1(window.tui) && window.tui.usageStatistics === false) {
    return;
  }
  if (date && !isExpired(date)) {
    return;
  }
  window.localStorage.setItem(applicationKeyForStorage, (/* @__PURE__ */ new Date()).getTime());
  setTimeout(function() {
    if (document.readyState === "interactive" || document.readyState === "complete") {
      imagePing(url, {
        v: 1,
        t: hitType,
        tid: trackingId,
        cid: hostname,
        dp: hostname,
        dh: appName,
        el: appName,
        ec: eventCategory
      });
    }
  }, 1e3);
}
var sendHostname_1 = sendHostname;
/Mac/.test(navigator.platform);
var reSpaceMoreThanOne = /[\u0020]+/g;
var reEscapeChars$1 = /[>(){}[\]+-.!#|]/g;
var reEscapeHTML = /<([a-zA-Z_][a-zA-Z0-9\-._]*)(\s|[^\\>])*\/?>|<(\/)([a-zA-Z_][a-zA-Z0-9\-._]*)\s*\/?>|<!--[^-]+-->|<([a-zA-Z_][a-zA-Z0-9\-.:/]*)>/g;
var reEscapeBackSlash = /\\[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~\\]/g;
var reEscapePairedChars = /[*_~`]/g;
var reMdImageSyntax = /!\[.*\]\(.*\)/g;
var reEscapedCharInLinkSyntax = /[[\]]/g;
var reEscapeBackSlashInSentence = /(?:^|[^\\])\\(?!\\)/g;
var XMLSPECIAL$1 = '[&<>"]';
var reXmlSpecial$1 = new RegExp(XMLSPECIAL$1, "g");
function replaceUnsafeChar$1(char) {
  switch (char) {
    case "&":
      return "&amp;";
    case "<":
      return "&lt;";
    case ">":
      return "&gt;";
    case '"':
      return "&quot;";
    default:
      return char;
  }
}
function escapeXml$1(text2) {
  if (reXmlSpecial$1.test(text2)) {
    return text2.replace(reXmlSpecial$1, replaceUnsafeChar$1);
  }
  return text2;
}
function sendHostName() {
  sendHostname_1("editor", "UA-129966929-1");
}
function includes(arr, targetItem) {
  return arr.indexOf(targetItem) !== -1;
}
var availableLinkAttributes = ["rel", "target", "hreflang", "type"];
var reMarkdownTextToEscapeMap = {
  codeblock: /(^ {4}[^\n]+\n*)+/,
  thematicBreak: /^ *((\* *){3,}|(- *){3,} *|(_ *){3,}) */,
  atxHeading: /^(#{1,6}) +[\s\S]+/,
  seTextheading: /^([^\n]+)\n *(=|-){2,} */,
  blockquote: /^( *>[^\n]+.*)+/,
  list: /^ *(\*+|-+|\d+\.) [\s\S]+/,
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? */,
  link: /!?\[.*\]\(.*\)/,
  reflink: /!?\[.*\]\s*\[([^\]]*)\]/,
  verticalBar: /\u007C/,
  fencedCodeblock: /^((`|~){3,})/
};
function sanitizeLinkAttribute(attribute) {
  if (!attribute) {
    return null;
  }
  var linkAttributes = {};
  availableLinkAttributes.forEach(function(key) {
    if (!isUndefined_1(attribute[key])) {
      linkAttributes[key] = attribute[key];
    }
  });
  return linkAttributes;
}
function repeat$1(text2, count) {
  var result = "";
  for (var i = 0; i < count; i += 1) {
    result += text2;
  }
  return result;
}
function isNeedEscapeText(text2) {
  var needEscape = false;
  forEachOwnProperties_1(reMarkdownTextToEscapeMap, function(reMarkdownTextToEscape) {
    if (reMarkdownTextToEscape.test(text2)) {
      needEscape = true;
    }
    return !needEscape;
  });
  return needEscape;
}
function escapeTextForLink(text2) {
  var imageSyntaxRanges = [];
  var result = reMdImageSyntax.exec(text2);
  while (result) {
    imageSyntaxRanges.push([result.index, result.index + result[0].length]);
    result = reMdImageSyntax.exec(text2);
  }
  return text2.replace(reEscapedCharInLinkSyntax, function(matched, offset) {
    var isDelimiter = imageSyntaxRanges.some(function(range2) {
      return offset > range2[0] && offset < range2[1];
    });
    return isDelimiter ? matched : "\\" + matched;
  });
}
function escape$1(text2) {
  var aheadReplacer = function(matched) {
    return "\\" + matched;
  };
  var behindReplacer = function(matched) {
    return matched + "\\";
  };
  var escapedText = text2.replace(reSpaceMoreThanOne, " ");
  if (reEscapeBackSlash.test(escapedText)) {
    escapedText = escapedText.replace(reEscapeBackSlash, aheadReplacer);
  }
  if (reEscapeBackSlashInSentence.test(escapedText)) {
    escapedText = escapedText.replace(reEscapeBackSlashInSentence, behindReplacer);
  }
  escapedText = escapedText.replace(reEscapePairedChars, aheadReplacer);
  if (reEscapeHTML.test(escapedText)) {
    escapedText = escapedText.replace(reEscapeHTML, aheadReplacer);
  }
  if (isNeedEscapeText(escapedText)) {
    escapedText = escapedText.replace(reEscapeChars$1, aheadReplacer);
  }
  return escapedText;
}
function quote(text2) {
  var result;
  if (text2.indexOf('"') === -1) {
    result = '""';
  } else {
    result = text2.indexOf("'") === -1 ? "''" : "()";
  }
  return result[0] + text2 + result[1];
}
function isNil(value) {
  return isNull_1(value) || isUndefined_1(value);
}
function shallowEqual(o1, o2) {
  if (o1 === null && o1 === o2) {
    return true;
  }
  if (typeof o1 !== "object" || typeof o2 !== "object" || isNil(o1) || isNil(o2)) {
    return o1 === o2;
  }
  for (var key in o1) {
    if (o1[key] !== o2[key]) {
      return false;
    }
  }
  for (var key in o2) {
    if (!(key in o1)) {
      return false;
    }
  }
  return true;
}
function last$1(arr) {
  return arr[arr.length - 1];
}
function between$1(value, min, max) {
  return value >= min && value <= max;
}
function isObject$1(obj) {
  return typeof obj === "object" && obj !== null;
}
function deepMergedCopy(targetObj, obj) {
  var resultObj = __assign$1({}, targetObj);
  if (targetObj && obj) {
    Object.keys(obj).forEach(function(prop2) {
      if (isObject$1(resultObj[prop2])) {
        if (Array.isArray(obj[prop2])) {
          resultObj[prop2] = deepCopyArray(obj[prop2]);
        } else if (resultObj.hasOwnProperty(prop2)) {
          resultObj[prop2] = deepMergedCopy(resultObj[prop2], obj[prop2]);
        } else {
          resultObj[prop2] = deepCopy(obj[prop2]);
        }
      } else {
        resultObj[prop2] = obj[prop2];
      }
    });
  }
  return resultObj;
}
function deepCopyArray(items) {
  return items.map(function(item2) {
    if (isObject$1(item2)) {
      return Array.isArray(item2) ? deepCopyArray(item2) : deepCopy(item2);
    }
    return item2;
  });
}
function deepCopy(obj) {
  var keys2 = Object.keys(obj);
  if (!keys2.length) {
    return obj;
  }
  return keys2.reduce(function(acc, prop2) {
    if (isObject$1(obj[prop2])) {
      acc[prop2] = Array.isArray(obj[prop2]) ? deepCopyArray(obj[prop2]) : deepCopy(obj[prop2]);
    } else {
      acc[prop2] = obj[prop2];
    }
    return acc;
  }, {});
}
function assign(targetObj, obj) {
  if (obj === void 0) {
    obj = {};
  }
  Object.keys(obj).forEach(function(prop2) {
    if (targetObj.hasOwnProperty(prop2) && typeof targetObj[prop2] === "object") {
      if (Array.isArray(obj[prop2])) {
        targetObj[prop2] = obj[prop2];
      } else {
        assign(targetObj[prop2], obj[prop2]);
      }
    } else {
      targetObj[prop2] = obj[prop2];
    }
  });
  return targetObj;
}
function getSortedNumPair(valueA, valueB) {
  return valueA > valueB ? [valueB, valueA] : [valueA, valueB];
}
var forEachArray = forEachArray_1;
function toArray$1(arrayLike) {
  var arr;
  try {
    arr = Array.prototype.slice.call(arrayLike);
  } catch (e) {
    arr = [];
    forEachArray(arrayLike, function(value) {
      arr.push(value);
    });
  }
  return arr;
}
var toArray_1 = toArray$1;
function createParagraph(schema, content) {
  var paragraph2 = schema.nodes.paragraph;
  if (!content) {
    return paragraph2.createAndFill();
  }
  return paragraph2.create(null, isString_1(content) ? schema.text(content) : content);
}
function createTextNode$1(schema, text2, marks) {
  return schema.text(text2, marks);
}
function createTextSelection(tr, from2, to) {
  if (to === void 0) {
    to = from2;
  }
  var contentSize = tr.doc.content.size;
  var size = contentSize > 0 ? contentSize - 1 : 1;
  return TextSelection.create(tr.doc, Math.min(from2, size), Math.min(to, size));
}
function addParagraph(tr, _a, schema) {
  var pos = _a.pos;
  tr.replaceWith(pos, pos, createParagraph(schema));
  return tr.setSelection(createTextSelection(tr, pos + 1));
}
function replaceTextNode(_a) {
  var state = _a.state, from2 = _a.from, startIndex = _a.startIndex, endIndex = _a.endIndex, createText = _a.createText;
  var tr = state.tr, doc3 = state.doc, schema = state.schema;
  for (var i = startIndex; i <= endIndex; i += 1) {
    var _b = doc3.child(i), nodeSize2 = _b.nodeSize, textContent = _b.textContent, content = _b.content;
    var text2 = createText(textContent);
    var node = text2 ? createTextNode$1(schema, text2) : Fragment.empty;
    var mappedFrom = tr.mapping.map(from2);
    var mappedTo = mappedFrom + content.size;
    tr.replaceWith(mappedFrom, mappedTo, node);
    from2 += nodeSize2;
  }
  return tr;
}
function splitAndExtendBlock(tr, pos, text2, node) {
  var textLen = text2.length;
  tr.split(pos).delete(pos - textLen, pos).insert(tr.mapping.map(pos), node).setSelection(createTextSelection(tr, tr.mapping.map(pos) - textLen));
}
function getMdStartLine(mdNode) {
  return mdNode.sourcepos[0][0];
}
function getMdEndLine(mdNode) {
  return mdNode.sourcepos[1][0];
}
function getMdStartCh(mdNode) {
  return mdNode.sourcepos[0][1];
}
function getMdEndCh(mdNode) {
  return mdNode.sourcepos[1][1];
}
function isHTMLNode(mdNode) {
  var type = mdNode.type;
  return type === "htmlBlock" || type === "htmlInline";
}
function isStyledInlineNode(mdNode) {
  var type = mdNode.type;
  return type === "strike" || type === "strong" || type === "emph" || type === "code" || type === "link" || type === "image";
}
function isCodeBlockNode(mdNode) {
  return mdNode && mdNode.type === "codeBlock";
}
function isListNode$1(mdNode) {
  return mdNode && (mdNode.type === "item" || mdNode.type === "list");
}
function isOrderedListNode(mdNode) {
  return isListNode$1(mdNode) && mdNode.listData.type === "ordered";
}
function isBulletListNode(mdNode) {
  return isListNode$1(mdNode) && mdNode.listData.type !== "ordered";
}
function isTableCellNode(mdNode) {
  return mdNode && (mdNode.type === "tableCell" || mdNode.type === "tableDelimCell");
}
function isInlineNode$1(mdNode) {
  switch (mdNode.type) {
    case "code":
    case "text":
    case "emph":
    case "strong":
    case "strike":
    case "link":
    case "image":
    case "htmlInline":
    case "linebreak":
    case "softbreak":
    case "customInline":
      return true;
    default:
      return false;
  }
}
function findClosestNode(mdNode, condition, includeSelf) {
  if (includeSelf === void 0) {
    includeSelf = true;
  }
  mdNode = includeSelf ? mdNode : mdNode.parent;
  while (mdNode && mdNode.type !== "document") {
    if (condition(mdNode)) {
      return mdNode;
    }
    mdNode = mdNode.parent;
  }
  return null;
}
function traverseParentNodes(mdNode, iteratee, includeSelf) {
  if (includeSelf === void 0) {
    includeSelf = true;
  }
  mdNode = includeSelf ? mdNode : mdNode.parent;
  while (mdNode && mdNode.type !== "document") {
    iteratee(mdNode);
    mdNode = mdNode.parent;
  }
}
function addOffsetPos(originPos, offset) {
  return [originPos[0], originPos[1] + offset];
}
function setOffsetPos(originPos, newOffset) {
  return [originPos[0], newOffset];
}
function getInlineMarkdownText(mdNode) {
  var text2 = mdNode.firstChild.literal;
  switch (mdNode.type) {
    case "emph":
      return "*" + text2 + "*";
    case "strong":
      return "**" + text2 + "**";
    case "strike":
      return "~~" + text2 + "~~";
    case "code":
      return "`" + text2 + "`";
    case "link":
    case "image":
      var _a = mdNode, destination = _a.destination, title = _a.title;
      var delim = mdNode.type === "link" ? "" : "!";
      return delim + "[" + text2 + "](" + destination + (title ? ' "' + title + '"' : "") + ")";
    default:
      return null;
  }
}
function isContainer$2(node) {
  switch (node.type) {
    case "document":
    case "blockQuote":
    case "list":
    case "item":
    case "paragraph":
    case "heading":
    case "emph":
    case "strong":
    case "strike":
    case "link":
    case "image":
    case "table":
    case "tableHead":
    case "tableBody":
    case "tableRow":
    case "tableCell":
    case "tableDelimRow":
    case "customInline":
      return true;
    default:
      return false;
  }
}
function getChildrenText$1(node) {
  var buffer = [];
  var walker = node.walker();
  var event = null;
  while (event = walker.next()) {
    var childNode = event.node;
    if (childNode.type === "text") {
      buffer.push(childNode.literal);
    }
  }
  return buffer.join("");
}
var widgetRules = [];
var widgetRuleMap = {};
var reWidgetPrefix = /\$\$widget\d+\s/;
function unwrapWidgetSyntax(text2) {
  var index2 = text2.search(reWidgetPrefix);
  if (index2 !== -1) {
    var rest = text2.substring(index2);
    var replaced = rest.replace(reWidgetPrefix, "").replace("$$", "");
    text2 = text2.substring(0, index2);
    text2 += unwrapWidgetSyntax(replaced);
  }
  return text2;
}
function createWidgetContent(info, text2) {
  return "$$" + info + " " + text2 + "$$";
}
function widgetToDOM(info, text2) {
  var _a = widgetRuleMap[info], rule = _a.rule, toDOM = _a.toDOM;
  var matches3 = unwrapWidgetSyntax(text2).match(rule);
  if (matches3) {
    text2 = matches3[0];
  }
  return toDOM(text2);
}
function getWidgetRules() {
  return widgetRules;
}
function setWidgetRules(rules) {
  widgetRules = rules;
  widgetRules.forEach(function(rule, index2) {
    widgetRuleMap["widget" + index2] = rule;
  });
}
function mergeNodes(nodes, text2, schema, ruleIndex) {
  return nodes.concat(createNodesWithWidget(text2, schema, ruleIndex));
}
function createNodesWithWidget(text2, schema, ruleIndex) {
  if (ruleIndex === void 0) {
    ruleIndex = 0;
  }
  var nodes = [];
  var rule = (widgetRules[ruleIndex] || {}).rule;
  var nextRuleIndex = ruleIndex + 1;
  text2 = unwrapWidgetSyntax(text2);
  if (rule && rule.test(text2)) {
    var index2 = void 0;
    while ((index2 = text2.search(rule)) !== -1) {
      var prev = text2.substring(0, index2);
      if (prev) {
        nodes = mergeNodes(nodes, prev, schema, nextRuleIndex);
      }
      text2 = text2.substring(index2);
      var literal = text2.match(rule)[0];
      var info = "widget" + ruleIndex;
      nodes.push(schema.nodes.widget.create({ info }, schema.text(createWidgetContent(info, literal))));
      text2 = text2.substring(literal.length);
    }
    if (text2) {
      nodes = mergeNodes(nodes, text2, schema, nextRuleIndex);
    }
  } else if (text2) {
    nodes = ruleIndex < widgetRules.length - 1 ? mergeNodes(nodes, text2, schema, nextRuleIndex) : [schema.text(text2)];
  }
  return nodes;
}
function getWidgetContent(widgetNode) {
  var event;
  var text2 = "";
  var walker = widgetNode.walker();
  while (event = walker.next()) {
    var node = event.node, entering = event.entering;
    if (entering) {
      if (node !== widgetNode && node.type !== "text") {
        text2 += getInlineMarkdownText(node);
        walker.resumeAt(widgetNode, false);
        walker.next();
      } else if (node.type === "text") {
        text2 += node.literal;
      }
    }
  }
  return text2;
}
function getDefaultCommands() {
  return {
    deleteSelection: function() {
      return deleteSelection;
    },
    selectAll: function() {
      return selectAll;
    },
    undo: function() {
      return undo;
    },
    redo: function() {
      return redo;
    }
  };
}
function placeholder(options) {
  return new Plugin({
    props: {
      decorations: function(state) {
        var doc3 = state.doc;
        if (options.text && doc3.childCount === 1 && doc3.firstChild.isTextblock && doc3.firstChild.content.size === 0) {
          var placeHolder = document.createElement("span");
          addClass_1(placeHolder, "placeholder");
          if (options.className) {
            addClass_1(placeHolder, options.className);
          }
          placeHolder.textContent = options.text;
          return DecorationSet.create(doc3, [Decoration.widget(1, placeHolder)]);
        }
        return null;
      }
    }
  });
}
var inArray$1 = inArray_1;
var getClass = getClass_1;
function hasClass(element, cssClass) {
  var origin;
  if (element.classList) {
    return element.classList.contains(cssClass);
  }
  origin = getClass(element).split(/\s+/);
  return inArray$1(cssClass, origin) > -1;
}
var hasClass_1 = hasClass;
var inArray = inArray_1;
var toArray = toArray_1;
var elProto = Element.prototype;
var matchSelector = elProto.matches || elProto.webkitMatchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || function(selector) {
  var doc3 = this.document || this.ownerDocument;
  return inArray(this, toArray(doc3.querySelectorAll(selector))) > -1;
};
function matches2(element, selector) {
  return matchSelector.call(element, selector);
}
var matches_1 = matches2;
var TAG_NAME = "[A-Za-z][A-Za-z0-9-]*";
var ATTRIBUTE_NAME = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
var UNQUOTED_VALUE = "[^\"'=<>`\\x00-\\x20]+";
var SINGLE_QUOTED_VALUE = "'[^']*'";
var DOUBLE_QUOTED_VALUE = '"[^"]*"';
var ATTRIBUTE_VALUE = "(?:" + UNQUOTED_VALUE + "|" + SINGLE_QUOTED_VALUE + "|" + DOUBLE_QUOTED_VALUE + ")";
var ATTRIBUTE_VALUE_SPEC = "(?:\\s*=\\s*" + ATTRIBUTE_VALUE + ")";
var ATTRIBUTE$1 = "(?:\\s+" + ATTRIBUTE_NAME + ATTRIBUTE_VALUE_SPEC + "?)";
var OPEN_TAG = "<(" + TAG_NAME + ")(" + ATTRIBUTE$1 + ")*\\s*/?>";
var CLOSE_TAG = "</(" + TAG_NAME + ")\\s*[>]";
var HTML_TAG = "(?:" + OPEN_TAG + "|" + CLOSE_TAG + ")";
var reHTMLTag = new RegExp("^" + HTML_TAG, "i");
var reBR = /<br\s*\/*>/i;
var reHTMLComment = /<! ---->|<!--(?:-?[^>-])(?:-?[^-])*-->/;
var ALTERNATIVE_TAG_FOR_BR = "</p><p>";
function isPositionInBox(style, offsetX, offsetY) {
  var left = parseInt(style.left, 10);
  var top2 = parseInt(style.top, 10);
  var width = parseInt(style.width, 10) + parseInt(style.paddingLeft, 10) + parseInt(style.paddingRight, 10);
  var height = parseInt(style.height, 10) + parseInt(style.paddingTop, 10) + parseInt(style.paddingBottom, 10);
  return offsetX >= left && offsetX <= left + width && offsetY >= top2 && offsetY <= top2 + height;
}
var CLS_PREFIX = "toastui-editor-";
function cls() {
  var names = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    names[_i] = arguments[_i];
  }
  var result = [];
  for (var _a = 0, names_1 = names; _a < names_1.length; _a++) {
    var name_1 = names_1[_a];
    var className = void 0;
    if (Array.isArray(name_1)) {
      className = name_1[0] ? name_1[1] : null;
    } else {
      className = name_1;
    }
    if (className) {
      result.push("" + CLS_PREFIX + className);
    }
  }
  return result.join(" ");
}
function clsWithMdPrefix() {
  var names = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    names[_i] = arguments[_i];
  }
  return names.map(function(className) {
    return CLS_PREFIX + "md-" + className;
  }).join(" ");
}
function isTextNode(node) {
  return (node === null || node === void 0 ? void 0 : node.nodeType) === Node.TEXT_NODE;
}
function isElemNode(node) {
  return node && node.nodeType === Node.ELEMENT_NODE;
}
function findNodes(element, selector) {
  var nodeList = toArray_1(element.querySelectorAll(selector));
  if (nodeList.length) {
    return nodeList;
  }
  return [];
}
function appendNodes(node, nodesToAppend) {
  nodesToAppend = isArray_1(nodesToAppend) ? toArray_1(nodesToAppend) : [nodesToAppend];
  nodesToAppend.forEach(function(nodeToAppend) {
    node.appendChild(nodeToAppend);
  });
}
function insertBeforeNode(insertedNode, node) {
  if (node.parentNode) {
    node.parentNode.insertBefore(insertedNode, node);
  }
}
function removeNode$1(node) {
  if (node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function unwrapNode(node) {
  var result = [];
  while (node.firstChild) {
    result.push(node.firstChild);
    if (node.parentNode) {
      node.parentNode.insertBefore(node.firstChild, node);
    }
  }
  removeNode$1(node);
  return result;
}
function toggleClass(element, className, state) {
  if (isUndefined_1(state)) {
    state = !hasClass_1(element, className);
  }
  var toggleFn = state ? addClass_1 : removeClass_1;
  toggleFn(element, className);
}
function createElementWith(contents, target2) {
  var container = document.createElement("div");
  if (isString_1(contents)) {
    container.innerHTML = contents;
  } else {
    container.appendChild(contents);
  }
  var firstChild = container.firstChild;
  if (target2) {
    target2.appendChild(firstChild);
  }
  return firstChild;
}
function getOuterWidth(el2) {
  var computed = window.getComputedStyle(el2);
  return ["margin-left", "margin-right"].reduce(function(acc, type) {
    return acc + parseInt(computed.getPropertyValue(type), 10);
  }, 0) + el2.offsetWidth;
}
function closest(node, found2) {
  var condition;
  if (isString_1(found2)) {
    condition = function(target2) {
      return matches_1(target2, found2);
    };
  } else {
    condition = function(target2) {
      return target2 === found2;
    };
  }
  while (node && node !== document) {
    if (isElemNode(node) && condition(node)) {
      return node;
    }
    node = node.parentNode;
  }
  return null;
}
function getTotalOffset(el2, root) {
  var offsetTop = 0;
  var offsetLeft = 0;
  while (el2 && el2 !== root) {
    var top_1 = el2.offsetTop, left = el2.offsetLeft, offsetParent = el2.offsetParent;
    offsetTop += top_1;
    offsetLeft += left;
    if (offsetParent === root.offsetParent) {
      break;
    }
    el2 = el2.offsetParent;
  }
  return { offsetTop, offsetLeft };
}
function setAttributes(attributes, element) {
  Object.keys(attributes).forEach(function(attrName) {
    if (isNil(attributes[attrName])) {
      element.removeAttribute(attrName);
    } else {
      element.setAttribute(attrName, attributes[attrName]);
    }
  });
}
function replaceBRWithEmptyBlock(html2) {
  var replacedHTML = html2.replace(/<p><br\s*\/*><\/p>/gi, "<p></p>");
  var reHTMLTag2 = new RegExp(HTML_TAG, "ig");
  var htmlTagMatched = replacedHTML.match(reHTMLTag2);
  htmlTagMatched === null || htmlTagMatched === void 0 ? void 0 : htmlTagMatched.forEach(function(htmlTag, index2) {
    if (reBR.test(htmlTag)) {
      var alternativeTag = ALTERNATIVE_TAG_FOR_BR;
      if (index2) {
        var prevTag = htmlTagMatched[index2 - 1];
        var openTagMatched = prevTag.match(OPEN_TAG);
        if (openTagMatched && !/br/i.test(openTagMatched[1])) {
          var tagName = openTagMatched[1];
          alternativeTag = "</" + tagName + "><" + tagName + ">";
        }
      }
      replacedHTML = replacedHTML.replace(reBR, alternativeTag);
    }
  });
  return replacedHTML;
}
function removeProseMirrorHackNodes(html2) {
  var reProseMirrorImage = /<img class="ProseMirror-separator" alt="">/g;
  var reProseMirrorTrailingBreak = / class="ProseMirror-trailingBreak"/g;
  var resultHTML = html2;
  resultHTML = resultHTML.replace(reProseMirrorImage, "");
  resultHTML = resultHTML.replace(reProseMirrorTrailingBreak, "");
  return resultHTML;
}
var pluginKey$1 = new PluginKey("widget");
var MARGIN = 5;
var PopupWidget = (
  /** @class */
  (function() {
    function PopupWidget2(view, eventEmitter) {
      var _this = this;
      this.popup = null;
      this.removeWidget = function() {
        if (_this.popup) {
          _this.rootEl.removeChild(_this.popup);
          _this.popup = null;
        }
      };
      this.rootEl = view.dom.parentElement;
      this.eventEmitter = eventEmitter;
      this.eventEmitter.listen("blur", this.removeWidget);
      this.eventEmitter.listen("loadUI", function() {
        _this.rootEl = closest(view.dom.parentElement, "." + cls("defaultUI"));
      });
      this.eventEmitter.listen("removePopupWidget", this.removeWidget);
    }
    PopupWidget2.prototype.update = function(view) {
      var widget = pluginKey$1.getState(view.state);
      this.removeWidget();
      if (widget) {
        var node = widget.node, style = widget.style;
        var _a = view.coordsAtPos(widget.pos), top_1 = _a.top, left = _a.left, bottom2 = _a.bottom;
        var height = bottom2 - top_1;
        var rect2 = this.rootEl.getBoundingClientRect();
        var relTopPos = top_1 - rect2.top;
        css_1(node, { opacity: "0" });
        this.rootEl.appendChild(node);
        css_1(node, {
          position: "absolute",
          left: left - rect2.left + MARGIN + "px",
          top: (style === "bottom" ? relTopPos + height - MARGIN : relTopPos - height) + "px",
          opacity: "1"
        });
        this.popup = node;
        view.focus();
      }
    };
    PopupWidget2.prototype.destroy = function() {
      this.eventEmitter.removeEventHandler("blur", this.removeWidget);
    };
    return PopupWidget2;
  })()
);
function addWidget(eventEmitter) {
  return new Plugin({
    key: pluginKey$1,
    state: {
      init: function() {
        return null;
      },
      apply: function(tr) {
        return tr.getMeta("widget");
      }
    },
    view: function(editorView) {
      return new PopupWidget(editorView, eventEmitter);
    }
  });
}
function addDefaultImageBlobHook(eventEmitter) {
  eventEmitter.listen("addImageBlobHook", function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function(_a) {
      var target2 = _a.target;
      return callback(target2.result);
    };
    reader.readAsDataURL(blob);
  });
}
function emitImageBlobHook(eventEmitter, blob, type) {
  var hook = function(imageUrl, altText) {
    eventEmitter.emit("command", "addImage", {
      imageUrl,
      altText: altText || blob.name || "image"
    });
  };
  eventEmitter.emit("addImageBlobHook", blob, hook, type);
}
function pasteImageOnly(items) {
  var images = toArray_1(items).filter(function(_a) {
    var type = _a.type;
    return type.indexOf("image") !== -1;
  });
  if (images.length === 1) {
    var item2 = images[0];
    if (item2) {
      return item2.getAsFile();
    }
  }
  return null;
}
function dropImage(_a) {
  var eventEmitter = _a.eventEmitter;
  return new Plugin({
    props: {
      handleDOMEvents: {
        drop: function(_, ev) {
          var _a2;
          var items = (_a2 = ev.dataTransfer) === null || _a2 === void 0 ? void 0 : _a2.files;
          if (items) {
            forEachArray_1(items, function(item2) {
              if (item2.type.indexOf("image") !== -1) {
                ev.preventDefault();
                ev.stopPropagation();
                emitImageBlobHook(eventEmitter, item2, ev.type);
                return false;
              }
              return true;
            });
          }
          return true;
        }
      }
    }
  });
}
var Node$2 = (
  /** @class */
  (function() {
    function Node3() {
    }
    Object.defineProperty(Node3.prototype, "type", {
      get: function() {
        return "node";
      },
      enumerable: false,
      configurable: true
    });
    Node3.prototype.setContext = function(context) {
      this.context = context;
    };
    return Node3;
  })()
);
function widgetNodeView(pmNode) {
  var dom = document.createElement("span");
  var node = widgetToDOM(pmNode.attrs.info, pmNode.textContent);
  dom.className = "tui-widget";
  dom.appendChild(node);
  return { dom };
}
function isWidgetNode(pmNode) {
  return pmNode.type.name === "widget";
}
var Widget = (
  /** @class */
  (function(_super) {
    __extends$1(Widget2, _super);
    function Widget2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Widget2.prototype, "name", {
      get: function() {
        return "widget";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Widget2.prototype, "schema", {
      get: function() {
        return {
          attrs: {
            info: { default: null }
          },
          group: "inline",
          inline: true,
          content: "text*",
          selectable: false,
          atom: true,
          toDOM: function() {
            return ["span", { class: "tui-widget" }, 0];
          },
          parseDOM: [
            {
              tag: "span.tui-widget",
              getAttrs: function(dom) {
                var text2 = dom.textContent;
                var _a = text2.match(/\$\$(widget\d+)/), info = _a[1];
                return { info };
              }
            }
          ]
        };
      },
      enumerable: false,
      configurable: true
    });
    return Widget2;
  })(Node$2)
);
var EditorBase = (
  /** @class */
  (function() {
    function EditorBase2(eventEmitter) {
      this.timer = null;
      this.el = document.createElement("div");
      this.el.className = "toastui-editor";
      this.eventEmitter = eventEmitter;
      this.placeholder = { text: "" };
    }
    EditorBase2.prototype.createState = function() {
      return EditorState.create({
        schema: this.schema,
        plugins: this.createPlugins()
      });
    };
    EditorBase2.prototype.initEvent = function() {
      var _a = this, eventEmitter = _a.eventEmitter, view = _a.view, editorType = _a.editorType;
      view.dom.addEventListener("focus", function() {
        return eventEmitter.emit("focus", editorType);
      });
      view.dom.addEventListener("blur", function() {
        return eventEmitter.emit("blur", editorType);
      });
    };
    EditorBase2.prototype.emitChangeEvent = function(tr) {
      this.eventEmitter.emit("caretChange", this.editorType);
      if (tr.docChanged) {
        this.eventEmitter.emit("change", this.editorType);
      }
    };
    Object.defineProperty(EditorBase2.prototype, "defaultPlugins", {
      get: function() {
        var rules = this.createInputRules();
        var plugins = __spreadArray$1(__spreadArray$1([], this.keymaps), [
          keymap(__assign$1({ "Shift-Enter": baseKeymap.Enter }, baseKeymap)),
          history(),
          placeholder(this.placeholder),
          addWidget(this.eventEmitter),
          dropImage(this.context)
        ]);
        return rules ? plugins.concat(rules) : plugins;
      },
      enumerable: false,
      configurable: true
    });
    EditorBase2.prototype.createInputRules = function() {
      var widgetRules2 = getWidgetRules();
      var rules = widgetRules2.map(function(_a) {
        var rule = _a.rule;
        return new InputRule(rule, function(state, match, start, end) {
          var schema = state.schema, tr = state.tr, doc3 = state.doc;
          var allMatched = match.input.match(new RegExp(rule, "g"));
          var pos = doc3.resolve(start);
          var parent = pos.parent;
          var count = 0;
          if (isWidgetNode(parent)) {
            parent = pos.node(pos.depth - 1);
          }
          parent.forEach(function(child) {
            return isWidgetNode(child) && (count += 1);
          });
          if (allMatched.length > count) {
            var content = last$1(allMatched);
            var nodes = createNodesWithWidget(content, schema);
            return tr.replaceWith(end - content.length + 1, end, nodes);
          }
          return null;
        });
      });
      return rules.length ? inputRules({ rules }) : null;
    };
    EditorBase2.prototype.clearTimer = function() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    };
    EditorBase2.prototype.createSchema = function() {
      return new Schema({
        nodes: this.specs.nodes,
        marks: this.specs.marks
      });
    };
    EditorBase2.prototype.createKeymaps = function(useCommandShortcut) {
      var _a = getDefaultCommands(), undo2 = _a.undo, redo2 = _a.redo;
      var allKeymaps = this.specs.keymaps(useCommandShortcut);
      var historyKeymap = {
        "Mod-z": undo2(),
        "Shift-Mod-z": redo2()
      };
      return useCommandShortcut ? allKeymaps.concat(keymap(historyKeymap)) : allKeymaps;
    };
    EditorBase2.prototype.createCommands = function() {
      return this.specs.commands(this.view);
    };
    EditorBase2.prototype.createPluginProps = function() {
      var _this = this;
      return this.extraPlugins.map(function(plugin) {
        return plugin(_this.eventEmitter);
      });
    };
    EditorBase2.prototype.focus = function() {
      var _this = this;
      this.clearTimer();
      this.timer = setTimeout(function() {
        _this.view.focus();
        _this.view.dispatch(_this.view.state.tr.scrollIntoView());
      });
    };
    EditorBase2.prototype.blur = function() {
      this.view.dom.blur();
    };
    EditorBase2.prototype.destroy = function() {
      var _this = this;
      this.clearTimer();
      this.view.destroy();
      Object.keys(this).forEach(function(prop2) {
        delete _this[prop2];
      });
    };
    EditorBase2.prototype.moveCursorToStart = function(focus) {
      var tr = this.view.state.tr;
      this.view.dispatch(tr.setSelection(createTextSelection(tr, 1)).scrollIntoView());
      if (focus) {
        this.focus();
      }
    };
    EditorBase2.prototype.moveCursorToEnd = function(focus) {
      var tr = this.view.state.tr;
      this.view.dispatch(tr.setSelection(createTextSelection(tr, tr.doc.content.size - 1)).scrollIntoView());
      if (focus) {
        this.focus();
      }
    };
    EditorBase2.prototype.setScrollTop = function(top2) {
      this.view.dom.scrollTop = top2;
    };
    EditorBase2.prototype.getScrollTop = function() {
      return this.view.dom.scrollTop;
    };
    EditorBase2.prototype.setPlaceholder = function(text2) {
      this.placeholder.text = text2;
      this.view.dispatch(this.view.state.tr.scrollIntoView());
    };
    EditorBase2.prototype.setHeight = function(height) {
      css_1(this.el, { height: height + "px" });
    };
    EditorBase2.prototype.setMinHeight = function(minHeight) {
      css_1(this.el, { minHeight: minHeight + "px" });
    };
    EditorBase2.prototype.getElement = function() {
      return this.el;
    };
    return EditorBase2;
  })()
);
function isFunction(obj) {
  return obj instanceof Function;
}
var isFunction_1 = isFunction;
var defaultCommandShortcuts = [
  "Enter",
  "Shift-Enter",
  "Mod-Enter",
  "Tab",
  "Shift-Tab",
  "Delete",
  "Backspace",
  "Mod-Delete",
  "Mod-Backspace",
  "ArrowUp",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "Mod-d",
  "Mod-D",
  "Alt-ArrowUp",
  "Alt-ArrowDown"
];
function execCommand(view, command, payload) {
  view.focus();
  return command(payload)(view.state, view.dispatch, view);
}
var SpecManager = (
  /** @class */
  (function() {
    function SpecManager2(specs) {
      this.specs = specs;
    }
    Object.defineProperty(SpecManager2.prototype, "nodes", {
      get: function() {
        return this.specs.filter(function(spec) {
          return spec.type === "node";
        }).reduce(function(nodes, _a) {
          var _b;
          var name = _a.name, schema = _a.schema;
          return __assign$1(__assign$1({}, nodes), (_b = {}, _b[name] = schema, _b));
        }, {});
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(SpecManager2.prototype, "marks", {
      get: function() {
        return this.specs.filter(function(spec) {
          return spec.type === "mark";
        }).reduce(function(marks, _a) {
          var _b;
          var name = _a.name, schema = _a.schema;
          return __assign$1(__assign$1({}, marks), (_b = {}, _b[name] = schema, _b));
        }, {});
      },
      enumerable: false,
      configurable: true
    });
    SpecManager2.prototype.commands = function(view, addedCommands) {
      var specCommands = this.specs.filter(function(_a) {
        var commands = _a.commands;
        return commands;
      }).reduce(function(allCommands, spec) {
        var commands = {};
        var specCommand = spec.commands();
        if (isFunction_1(specCommand)) {
          commands[spec.name] = function(payload) {
            return execCommand(view, specCommand, payload);
          };
        } else {
          Object.keys(specCommand).forEach(function(name) {
            commands[name] = function(payload) {
              return execCommand(view, specCommand[name], payload);
            };
          });
        }
        return __assign$1(__assign$1({}, allCommands), commands);
      }, {});
      var defaultCommands = getDefaultCommands();
      Object.keys(defaultCommands).forEach(function(name) {
        specCommands[name] = function(payload) {
          return execCommand(view, defaultCommands[name], payload);
        };
      });
      if (addedCommands) {
        Object.keys(addedCommands).forEach(function(name) {
          specCommands[name] = function(payload) {
            return execCommand(view, addedCommands[name], payload);
          };
        });
      }
      return specCommands;
    };
    SpecManager2.prototype.keymaps = function(useCommandShortcut) {
      var specKeymaps = this.specs.filter(function(spec) {
        return spec.keymaps;
      }).map(function(spec) {
        return spec.keymaps();
      });
      return specKeymaps.map(function(keys2) {
        if (!useCommandShortcut) {
          Object.keys(keys2).forEach(function(key) {
            if (!includes(defaultCommandShortcuts, key)) {
              delete keys2[key];
            }
          });
        }
        return keymap(keys2);
      });
    };
    SpecManager2.prototype.setContext = function(context) {
      this.specs.forEach(function(spec) {
        spec.setContext(context);
      });
    };
    return SpecManager2;
  })()
);
function resolveSelectionPos(selection) {
  var from2 = selection.from, to = selection.to;
  if (selection instanceof AllSelection) {
    return [from2 + 1, to - 1];
  }
  return [from2, to];
}
function getMdLine(resolvedPos) {
  return resolvedPos.index(0) + 1;
}
function getWidgetNodePos(node, chPos, direction) {
  if (direction === void 0) {
    direction = 1;
  }
  var additionalPos = 0;
  node.forEach(function(child, pos) {
    if (isWidgetNode(child) && pos + 2 < chPos) {
      additionalPos += 2 * direction;
    }
  });
  return additionalPos;
}
function getEditorToMdPos(doc3, from2, to) {
  if (to === void 0) {
    to = from2;
  }
  var collapsed = from2 === to;
  var startResolvedPos = doc3.resolve(from2);
  var startLine = getMdLine(startResolvedPos);
  var endLine = startLine;
  var startOffset = startResolvedPos.start(1);
  var endOffset = startOffset;
  if (!collapsed) {
    var endResolvedPos = doc3.resolve(to === doc3.content.size ? to - 1 : to);
    endOffset = endResolvedPos.start(1);
    endLine = getMdLine(endResolvedPos);
    if (endResolvedPos.pos === doc3.content.size) {
      to = doc3.content.size - 2;
    }
  }
  var startCh = Math.max(from2 - startOffset + 1, 1);
  var endCh = Math.max(to - endOffset + 1, 1);
  return [
    [startLine, startCh + getWidgetNodePos(doc3.child(startLine - 1), startCh, -1)],
    [endLine, endCh + getWidgetNodePos(doc3.child(endLine - 1), endCh, -1)]
  ];
}
function getStartPosListPerLine(doc3, endIndex) {
  var startPosListPerLine = [];
  for (var i = 0, pos = 0; i < endIndex; i += 1) {
    var child = doc3.child(i);
    startPosListPerLine[i] = pos;
    pos += child.nodeSize;
  }
  return startPosListPerLine;
}
function getMdToEditorPos(doc3, startPos, endPos) {
  var startPosListPerLine = getStartPosListPerLine(doc3, endPos[0]);
  var startIndex = startPos[0] - 1;
  var endIndex = endPos[0] - 1;
  var startNode = doc3.child(startIndex);
  var endNode = doc3.child(endIndex);
  var from2 = startPosListPerLine[startIndex];
  var to = startPosListPerLine[endIndex];
  from2 += startPos[1] + getWidgetNodePos(startNode, startPos[1] - 1);
  to += endPos[1] + getWidgetNodePos(endNode, endPos[1] - 1);
  return [from2, Math.min(to, doc3.content.size)];
}
function getRangeInfo(selection) {
  var $from = selection.$from, $to = selection.$to;
  var from2 = selection.from, to = selection.to;
  var doc3 = $from.doc;
  if (selection instanceof AllSelection) {
    $from = doc3.resolve(from2 + 1);
    $to = doc3.resolve(to - 1);
  }
  if ($from.depth === 0) {
    $from = doc3.resolve(from2 - 1);
    $to = $from;
  }
  return {
    startFromOffset: $from.start(1),
    endFromOffset: $to.start(1),
    startToOffset: $from.end(1),
    endToOffset: $to.end(1),
    startIndex: $from.index(0),
    endIndex: $to.index(0),
    from: $from.pos,
    to: $to.pos
  };
}
function getNodeContentOffsetRange(doc3, targetIndex) {
  var startOffset = 1;
  var endOffset = 1;
  for (var i = 0, offset = 0; i < doc3.childCount; i += 1) {
    var nodeSize2 = doc3.child(i).nodeSize;
    startOffset = offset + 1;
    endOffset = offset + nodeSize2 - 1;
    if (i === targetIndex) {
      break;
    }
    offset += nodeSize2;
  }
  return { startOffset, endOffset };
}
var HEADING = "heading";
var BLOCK_QUOTE = "blockQuote";
var LIST_ITEM = "listItem";
var TABLE = "table";
var TABLE_CELL = "tableCell";
var CODE_BLOCK = "codeBlock";
var THEMATIC_BREAK = "thematicBreak";
var LINK = "link";
var CODE = "code";
var META = "meta";
var DELIM = "delimiter";
var TASK_DELIM = "taskDelimiter";
var TEXT = "markedText";
var HTML = "html";
var CUSTOM_BLOCK = "customBlock";
var delimSize = {
  strong: 2,
  emph: 1,
  strike: 2
};
function markInfo(start, end, type, attrs) {
  return { start, end, spec: { type, attrs } };
}
function heading$1(_a, start, end) {
  var level = _a.level, headingType = _a.headingType;
  var marks = [markInfo(start, end, HEADING, { level })];
  if (headingType === "atx") {
    marks.push(markInfo(start, addOffsetPos(start, level), DELIM));
  } else {
    marks.push(markInfo(setOffsetPos(end, 0), end, HEADING, { seText: true }));
  }
  return marks;
}
function emphasisAndStrikethrough(_a, start, end) {
  var type = _a.type;
  var startDelimPos = addOffsetPos(start, delimSize[type]);
  var endDelimPos = addOffsetPos(end, -delimSize[type]);
  return [
    markInfo(startDelimPos, endDelimPos, type),
    markInfo(start, startDelimPos, DELIM),
    markInfo(endDelimPos, end, DELIM)
  ];
}
function markLink(start, end, linkTextStart, lastChildCh) {
  return [
    markInfo(start, end, LINK),
    markInfo(setOffsetPos(start, linkTextStart[1] + 1), setOffsetPos(end, lastChildCh), LINK, {
      desc: true
    }),
    markInfo(setOffsetPos(end, lastChildCh + 2), addOffsetPos(end, -1), LINK, { url: true })
  ];
}
function image$1(_a, start, end) {
  var lastChild = _a.lastChild;
  var lastChildCh = lastChild ? getMdEndCh(lastChild) + 1 : 3;
  var linkTextEnd = addOffsetPos(start, 1);
  return __spreadArray$1([markInfo(start, linkTextEnd, META)], markLink(start, end, linkTextEnd, lastChildCh));
}
function link(_a, start, end) {
  var lastChild = _a.lastChild, extendedAutolink = _a.extendedAutolink;
  var lastChildCh = lastChild ? getMdEndCh(lastChild) + 1 : 2;
  return extendedAutolink ? [markInfo(start, end, LINK, { desc: true })] : markLink(start, end, start, lastChildCh);
}
function code(_a, start, end) {
  var tickCount = _a.tickCount;
  var openDelimEnd = addOffsetPos(start, tickCount);
  var closeDelimStart = addOffsetPos(end, -tickCount);
  return [
    markInfo(start, end, CODE),
    markInfo(start, openDelimEnd, CODE, { start: true }),
    markInfo(openDelimEnd, closeDelimStart, CODE, { marked: true }),
    markInfo(closeDelimStart, end, CODE, { end: true })
  ];
}
function lineBackground(parent, start, end, prefix) {
  var defaultBackground = {
    start,
    end,
    spec: {
      attrs: { className: prefix + "-line-background", codeStart: start[0], codeEnd: end[0] }
    },
    lineBackground: true
  };
  return parent.type !== "item" && parent.type !== "blockQuote" ? [
    __assign$1(__assign$1({}, defaultBackground), { end: start, spec: { attrs: { className: prefix + "-line-background start" } } }),
    __assign$1(__assign$1({}, defaultBackground), { start: [Math.min(start[0] + 1, end[0]), start[1]] })
  ] : null;
}
function codeBlock$1(node, start, end, endLine) {
  var fenceOffset = node.fenceOffset, fenceLength = node.fenceLength, fenceChar = node.fenceChar, info = node.info, infoPadding = node.infoPadding, parent = node.parent;
  var fenceEnd = fenceOffset + fenceLength;
  var marks = [markInfo(setOffsetPos(start, 1), end, CODE_BLOCK)];
  if (fenceChar) {
    marks.push(markInfo(start, addOffsetPos(start, fenceEnd), DELIM));
  }
  if (info) {
    marks.push(markInfo(addOffsetPos(start, fenceLength), addOffsetPos(start, fenceLength + infoPadding + info.length), META));
  }
  var codeBlockEnd = "^(\\s{0,4})(" + fenceChar + "{" + fenceLength + ",})";
  var reCodeBlockEnd = new RegExp(codeBlockEnd);
  if (reCodeBlockEnd.test(endLine)) {
    marks.push(markInfo(setOffsetPos(end, 1), end, DELIM));
  }
  var lineBackgroundMarkInfo = lineBackground(parent, start, end, "code-block");
  return lineBackgroundMarkInfo ? marks.concat(lineBackgroundMarkInfo) : marks;
}
function customBlock$2(node, start, end) {
  var _a = node, offset = _a.offset, syntaxLength = _a.syntaxLength, info = _a.info, parent = _a.parent;
  var syntaxEnd = offset + syntaxLength;
  var marks = [markInfo(setOffsetPos(start, 1), end, CUSTOM_BLOCK)];
  marks.push(markInfo(start, addOffsetPos(start, syntaxEnd), DELIM));
  if (info) {
    marks.push(markInfo(addOffsetPos(start, syntaxEnd), addOffsetPos(start, syntaxLength + info.length), META));
  }
  marks.push(markInfo(setOffsetPos(end, 1), end, DELIM));
  var lineBackgroundMarkInfo = lineBackground(parent, start, end, "custom-block");
  return lineBackgroundMarkInfo ? marks.concat(lineBackgroundMarkInfo) : marks;
}
function markListItemChildren(node, markType) {
  var marks = [];
  while (node) {
    var type = node.type;
    if (type === "paragraph" || type === "codeBlock") {
      marks.push(markInfo([getMdStartLine(node), getMdStartCh(node) - 1], [getMdEndLine(node), getMdEndCh(node) + 1], markType));
    }
    node = node.next;
  }
  return marks;
}
function markParagraphInBlockQuote(node) {
  var marks = [];
  while (node) {
    marks.push(markInfo([getMdStartLine(node), getMdStartCh(node)], [getMdEndLine(node), getMdEndCh(node) + 1], TEXT));
    node = node.next;
  }
  return marks;
}
function blockQuote$2(node, start, end) {
  var marks = node.parent && node.parent.type !== "blockQuote" ? [markInfo(start, end, BLOCK_QUOTE)] : [];
  if (node.firstChild) {
    var childMarks = [];
    if (node.firstChild.type === "paragraph") {
      childMarks = markParagraphInBlockQuote(node.firstChild.firstChild);
    } else if (node.firstChild.type === "list") {
      childMarks = markListItemChildren(node.firstChild, TEXT);
    }
    marks = __spreadArray$1(__spreadArray$1([], marks), childMarks);
  }
  return marks;
}
function getSpecOfListItemStyle(node) {
  var depth = 0;
  while (node.parent.parent && node.parent.parent.type === "item") {
    node = node.parent.parent;
    depth += 1;
  }
  var attrs = [{ odd: true }, { even: true }][depth % 2];
  return [LIST_ITEM, __assign$1(__assign$1({}, attrs), { listStyle: true })];
}
function item$1(node, start) {
  var _a = node.listData, padding = _a.padding, task2 = _a.task;
  var spec = getSpecOfListItemStyle(node);
  var marks = [markInfo.apply(void 0, __spreadArray$1([start, addOffsetPos(start, padding)], spec))];
  if (task2) {
    marks.push(markInfo(addOffsetPos(start, padding), addOffsetPos(start, padding + 3), TASK_DELIM));
    marks.push(markInfo(addOffsetPos(start, padding + 1), addOffsetPos(start, padding + 2), META));
  }
  return marks.concat(markListItemChildren(node.firstChild, TEXT));
}
var markNodeFuncMap = {
  heading: heading$1,
  strong: emphasisAndStrikethrough,
  emph: emphasisAndStrikethrough,
  strike: emphasisAndStrikethrough,
  link,
  image: image$1,
  code,
  codeBlock: codeBlock$1,
  blockQuote: blockQuote$2,
  item: item$1,
  customBlock: customBlock$2
};
var simpleMarkClassNameMap = {
  thematicBreak: THEMATIC_BREAK,
  table: TABLE,
  tableCell: TABLE_CELL,
  htmlInline: HTML
};
function getMarkInfo(node, start, end, endLine) {
  var type = node.type;
  if (isFunction_1(markNodeFuncMap[type])) {
    return markNodeFuncMap[type](node, start, end, endLine);
  }
  if (simpleMarkClassNameMap[type]) {
    return [markInfo(start, end, simpleMarkClassNameMap[type])];
  }
  return null;
}
var removingBackgroundIndexMap = {};
function syntaxHighlight(_a) {
  var schema = _a.schema, toastMark = _a.toastMark;
  return new Plugin({
    appendTransaction: function(transactions, _, newState) {
      var tr = transactions[0];
      var newTr = newState.tr;
      if (tr.docChanged) {
        var markInfo_1 = [];
        var editResult = tr.getMeta("editResult");
        editResult.forEach(function(result) {
          var nodes = result.nodes, removedNodeRange = result.removedNodeRange;
          if (nodes.length) {
            markInfo_1 = markInfo_1.concat(getMarkForRemoving(newTr, nodes));
            for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
              var parent_1 = nodes_1[_i];
              var walker = parent_1.walker();
              var event_1 = walker.next();
              while (event_1) {
                var node = event_1.node, entering = event_1.entering;
                if (entering) {
                  markInfo_1 = markInfo_1.concat(getMarkForAdding(node, toastMark));
                }
                event_1 = walker.next();
              }
            }
          } else if (removedNodeRange) {
            var maxIndex = newTr.doc.childCount - 1;
            var _a2 = removedNodeRange.line, startLine = _a2[0], endLine = _a2[1];
            var startIndex = Math.min(startLine, maxIndex);
            var endIndex = Math.min(endLine, maxIndex);
            for (var i = startIndex; i <= endIndex; i += 1) {
              removingBackgroundIndexMap[i] = true;
            }
          }
        });
        appendMarkTr(newTr, schema, markInfo_1);
      }
      return newTr.setMeta("widget", tr.getMeta("widget"));
    }
  });
}
function isDifferentBlock(doc3, index2, attrs) {
  return Object.keys(attrs).some(function(name) {
    return attrs[name] !== doc3.child(index2).attrs[name];
  });
}
function addLineBackground(tr, doc3, paragraph2, blockPosInfo, attrs) {
  if (attrs === void 0) {
    attrs = {};
  }
  var startIndex = blockPosInfo.startIndex, endIndex = blockPosInfo.endIndex, from2 = blockPosInfo.from, to = blockPosInfo.to;
  var shouldChangeBlockType = false;
  for (var i = startIndex; i <= endIndex; i += 1) {
    delete removingBackgroundIndexMap[i];
    shouldChangeBlockType = isDifferentBlock(doc3, i, attrs);
  }
  if (shouldChangeBlockType) {
    tr.setBlockType(from2, to, paragraph2, attrs);
  }
}
function appendMarkTr(tr, schema, marks) {
  var doc3 = tr.doc;
  var paragraph2 = schema.nodes.paragraph;
  var startPosListPerLine = getStartPosListPerLine(doc3, doc3.childCount);
  marks.forEach(function(_a) {
    var start = _a.start, end = _a.end, spec = _a.spec, lineBackground2 = _a.lineBackground;
    var startIndex = Math.min(start[0], doc3.childCount) - 1;
    var endIndex = Math.min(end[0], doc3.childCount) - 1;
    var startNode = doc3.child(startIndex);
    var endNode = doc3.child(endIndex);
    var from2 = startPosListPerLine[startIndex];
    var to = startPosListPerLine[endIndex];
    from2 += start[1] + getWidgetNodePos(startNode, start[1] - 1);
    to += end[1] + getWidgetNodePos(endNode, end[1] - 1);
    if (spec) {
      if (lineBackground2) {
        var posInfo = { from: from2, to, startIndex, endIndex };
        addLineBackground(tr, doc3, paragraph2, posInfo, spec.attrs);
      } else {
        tr.addMark(from2, to, schema.mark(spec.type, spec.attrs));
      }
    } else {
      tr.removeMark(from2, to);
    }
  });
  removeBlockBackground(tr, startPosListPerLine, paragraph2);
}
function removeBlockBackground(tr, startPosListPerLine, paragraph2) {
  Object.keys(removingBackgroundIndexMap).forEach(function(index2) {
    var startIndex = Number(index2);
    var endIndex = Math.min(Number(index2) + 1, tr.doc.childCount - 1);
    var from2 = startPosListPerLine[startIndex];
    var to = startPosListPerLine[endIndex] - 1;
    if (startIndex === endIndex) {
      to += 2;
    }
    tr.setBlockType(from2, to, paragraph2);
  });
}
function cacheIndexToRemoveBackground(doc3, start, end) {
  var skipLines = [];
  removingBackgroundIndexMap = {};
  for (var i = start[0] - 1; i < end[0]; i += 1) {
    var node = doc3.child(i);
    var codeEnd = node.attrs.codeEnd;
    var codeStart = node.attrs.codeStart;
    if (codeStart && codeEnd && !includes(skipLines, codeStart)) {
      skipLines.push(codeStart);
      codeEnd = Math.min(codeEnd, doc3.childCount);
      var startIndex = codeStart - 1;
      var endIndex = end[0];
      for (var index2 = startIndex; index2 < endIndex; index2 += 1) {
        removingBackgroundIndexMap[index2] = true;
      }
    }
  }
}
function getMarkForRemoving(_a, nodes) {
  var doc3 = _a.doc;
  var start = nodes[0].sourcepos[0];
  var _b = last$1(nodes).sourcepos, end = _b[1];
  var startPos = [start[0], start[1]];
  var endPos = [end[0], end[1] + 1];
  var marks = [];
  cacheIndexToRemoveBackground(doc3, start, end);
  marks.push({ start: startPos, end: endPos });
  return marks;
}
function getMarkForAdding(node, toastMark) {
  var lineTexts = toastMark.getLineTexts();
  var startPos = [getMdStartLine(node), getMdStartCh(node)];
  var endPos = [getMdEndLine(node), getMdEndCh(node) + 1];
  var markInfo2 = getMarkInfo(node, startPos, endPos, lineTexts[endPos[0] - 1]);
  return markInfo2 !== null && markInfo2 !== void 0 ? markInfo2 : [];
}
var defaultToolbarStateKeys = [
  "taskList",
  "orderedList",
  "bulletList",
  "table",
  "strong",
  "emph",
  "strike",
  "heading",
  "thematicBreak",
  "blockQuote",
  "code",
  "codeBlock",
  "indent",
  "outdent"
];
function getToolbarStateType$1(mdNode) {
  var type = mdNode.type;
  if (isListNode$1(mdNode)) {
    if (mdNode.listData.task) {
      return "taskList";
    }
    return mdNode.listData.type === "ordered" ? "orderedList" : "bulletList";
  }
  if (type.indexOf("table") !== -1) {
    return "table";
  }
  if (!includes(defaultToolbarStateKeys, type)) {
    return null;
  }
  return type;
}
function getToolbarState$1(targetNode) {
  var toolbarState = {
    indent: { active: false, disabled: true },
    outdent: { active: false, disabled: true }
  };
  var listEnabled = true;
  traverseParentNodes(targetNode, function(mdNode) {
    var type = getToolbarStateType$1(mdNode);
    if (!type) {
      return;
    }
    if (type === "bulletList" || type === "orderedList") {
      if (listEnabled) {
        toolbarState[type] = { active: true };
        toolbarState.indent.disabled = false;
        toolbarState.outdent.disabled = false;
        listEnabled = false;
      }
    } else {
      toolbarState[type] = { active: true };
    }
  });
  return toolbarState;
}
function previewHighlight(_a) {
  var toastMark = _a.toastMark, eventEmitter = _a.eventEmitter;
  return new Plugin({
    view: function() {
      return {
        update: function(view, prevState) {
          var state = view.state;
          var doc3 = state.doc, selection = state.selection;
          if (prevState && prevState.doc.eq(doc3) && prevState.selection.eq(selection)) {
            return;
          }
          var from2 = selection.from;
          var startChOffset = state.doc.resolve(from2).start();
          var line = state.doc.content.findIndex(from2).index + 1;
          var ch = from2 - startChOffset;
          if (from2 === startChOffset) {
            ch += 1;
          }
          var cursorPos = [line, ch];
          var mdNode = toastMark.findNodeAtPosition(cursorPos);
          var toolbarState = getToolbarState$1(mdNode);
          eventEmitter.emit("changeToolbarState", {
            cursorPos,
            mdNode,
            toolbarState
          });
          eventEmitter.emit("setFocusedNode", mdNode);
        }
      };
    }
  });
}
var Doc$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Doc2, _super);
    function Doc2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Doc2.prototype, "name", {
      get: function() {
        return "doc";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Doc2.prototype, "schema", {
      get: function() {
        return {
          content: "block+"
        };
      },
      enumerable: false,
      configurable: true
    });
    return Doc2;
  })(Node$2)
);
var Mark2 = (
  /** @class */
  (function() {
    function Mark3() {
    }
    Object.defineProperty(Mark3.prototype, "type", {
      get: function() {
        return "mark";
      },
      enumerable: false,
      configurable: true
    });
    Mark3.prototype.setContext = function(context) {
      this.context = context;
    };
    return Mark3;
  })()
);
function getTextByMdLine(doc3, mdLine) {
  return getTextContent(doc3, mdLine - 1);
}
function getTextContent(doc3, index2) {
  return doc3.child(index2).textContent;
}
var reBlockQuote = /^\s*> ?/;
var BlockQuote$1 = (
  /** @class */
  (function(_super) {
    __extends$1(BlockQuote2, _super);
    function BlockQuote2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BlockQuote2.prototype, "name", {
      get: function() {
        return "blockQuote";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BlockQuote2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("block-quote") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    BlockQuote2.prototype.createBlockQuoteText = function(text2, isBlockQuote) {
      return isBlockQuote ? text2.replace(reBlockQuote, "").trim() : "> " + text2.trim();
    };
    BlockQuote2.prototype.extendBlockQuote = function() {
      var _this = this;
      return function(_a, dispatch) {
        var selection = _a.selection, doc3 = _a.doc, tr = _a.tr, schema = _a.schema;
        var _b = getRangeInfo(selection), endFromOffset = _b.endFromOffset, endToOffset = _b.endToOffset, endIndex = _b.endIndex, to = _b.to;
        var textContent = getTextContent(doc3, endIndex);
        var isBlockQuote = reBlockQuote.test(textContent);
        if (isBlockQuote && to > endFromOffset && selection.empty) {
          var isEmpty2 = !textContent.replace(reBlockQuote, "").trim();
          if (isEmpty2) {
            tr.deleteRange(endFromOffset, endToOffset).split(tr.mapping.map(endToOffset));
          } else {
            var slicedText = textContent.slice(to - endFromOffset).trim();
            var node = createTextNode$1(schema, _this.createBlockQuoteText(slicedText));
            splitAndExtendBlock(tr, endToOffset, slicedText, node);
          }
          dispatch(tr);
          return true;
        }
        return false;
      };
    };
    BlockQuote2.prototype.commands = function() {
      var _this = this;
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, doc3 = state.doc;
          var _a = getRangeInfo(selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset, startIndex = _a.startIndex, endIndex = _a.endIndex;
          var isBlockQuote = reBlockQuote.test(getTextContent(doc3, startIndex));
          var tr = replaceTextNode({
            state,
            startIndex,
            endIndex,
            from: startFromOffset,
            createText: function(textContent) {
              return _this.createBlockQuoteText(textContent, isBlockQuote);
            }
          });
          dispatch(tr.setSelection(createTextSelection(tr, tr.mapping.map(endToOffset))));
          return true;
        };
      };
    };
    BlockQuote2.prototype.keymaps = function() {
      var blockQuoteCommand = this.commands()();
      return {
        "alt-q": blockQuoteCommand,
        "alt-Q": blockQuoteCommand,
        Enter: this.extendBlockQuote()
      };
    };
    return BlockQuote2;
  })(Mark2)
);
var reList = /(^\s*)([-*+] |[\d]+\. )/;
var reOrderedList = /(^\s*)([\d])+\.( \[[ xX]])? /;
var reOrderedListGroup = /^(\s*)((\d+)([.)]\s(?:\[(?:x|\s)\]\s)?))(.*)/;
var reCanBeTaskList = /(^\s*)([-*+]|[\d]+\.)( \[[ xX]])? /;
var reBulletListGroup = /^(\s*)([-*+]+(\s(?:\[(?:x|\s)\]\s)?))(.*)/;
var reTaskList = /(^\s*)([-*+] |[\d]+\. )(\[[ xX]] )/;
var reBulletTaskList = /(^\s*)([-*+])( \[[ xX]]) /;
function getListType(text2) {
  return reOrderedList.test(text2) ? "ordered" : "bullet";
}
function getListDepth(mdNode) {
  var depth = 0;
  while (mdNode && mdNode.type !== "document") {
    if (mdNode.type === "list") {
      depth += 1;
    }
    mdNode = mdNode.parent;
  }
  return depth;
}
function findSameDepthList(toastMark, currentLine, depth, backward) {
  var lineTexts = toastMark.getLineTexts();
  var lineLen = lineTexts.length;
  var result = [];
  var line = currentLine;
  while (backward ? line < lineLen : line > 1) {
    line = backward ? line + 1 : line - 1;
    var mdNode = toastMark.findFirstNodeAtLine(line);
    var currentListDepth = getListDepth(mdNode);
    if (currentListDepth === depth) {
      result.push({ line, depth, mdNode });
    } else if (currentListDepth < depth) {
      break;
    }
  }
  return result;
}
function getSameDepthItems(_a) {
  var toastMark = _a.toastMark, mdNode = _a.mdNode, line = _a.line;
  var depth = getListDepth(mdNode);
  var forwardList = findSameDepthList(toastMark, line, depth, false).reverse();
  var backwardList = findSameDepthList(toastMark, line, depth, true);
  return forwardList.concat([{ line, depth, mdNode }]).concat(backwardList);
}
function textToBullet(text2) {
  if (!reList.test(text2)) {
    return "* " + text2;
  }
  var type = getListType(text2);
  if (type === "bullet" && reCanBeTaskList.test(text2)) {
    text2 = text2.replace(reBulletTaskList, "$1$2 ");
  } else if (type === "ordered") {
    text2 = text2.replace(reOrderedList, "$1* ");
  }
  return text2;
}
function textToOrdered(text2, ordinalNum) {
  if (!reList.test(text2)) {
    return ordinalNum + ". " + text2;
  }
  var type = getListType(text2);
  if (type === "bullet" || type === "ordered" && reCanBeTaskList.test(text2)) {
    text2 = text2.replace(reCanBeTaskList, "$1" + ordinalNum + ". ");
  } else if (type === "ordered") {
    var start = reOrderedListGroup.exec(text2)[3];
    if (Number(start) !== ordinalNum) {
      text2 = text2.replace(reOrderedList, "$1" + ordinalNum + ". ");
    }
  }
  return text2;
}
function getChangedInfo(doc3, sameDepthItems, type, start) {
  if (start === void 0) {
    start = 0;
  }
  var firstIndex = Number.MAX_VALUE;
  var lastIndex = 0;
  var changedResults = sameDepthItems.map(function(_a, index2) {
    var line = _a.line;
    firstIndex = Math.min(line - 1, firstIndex);
    lastIndex = Math.max(line - 1, lastIndex);
    var text2 = getTextByMdLine(doc3, line);
    text2 = type === "bullet" ? textToBullet(text2) : textToOrdered(text2, index2 + 1 + start);
    return { text: text2, line };
  });
  return { changedResults, firstIndex, lastIndex };
}
function getBulletOrOrdered(type, context) {
  var sameDepthListInfo = getSameDepthItems(context);
  return getChangedInfo(context.doc, sameDepthListInfo, type);
}
var otherListToList = {
  bullet: function(context) {
    return getBulletOrOrdered("bullet", context);
  },
  ordered: function(context) {
    return getBulletOrOrdered("ordered", context);
  },
  task: function(_a) {
    var mdNode = _a.mdNode, doc3 = _a.doc, line = _a.line;
    var text2 = getTextByMdLine(doc3, line);
    if (mdNode.listData.task) {
      text2 = text2.replace(reTaskList, "$1$2");
    } else if (isListNode$1(mdNode)) {
      text2 = text2.replace(reList, "$1$2[ ] ");
    }
    return { changedResults: [{ text: text2, line }] };
  }
};
var otherNodeToList = {
  bullet: function(_a) {
    var doc3 = _a.doc, line = _a.line;
    var lineText = getTextByMdLine(doc3, line);
    var changedResults = [{ text: "* " + lineText, line }];
    return { changedResults };
  },
  ordered: function(_a) {
    var toastMark = _a.toastMark, doc3 = _a.doc, line = _a.line, startLine = _a.startLine;
    var lineText = getTextByMdLine(doc3, line);
    var firstOrderedListNum = 1;
    var firstOrderedListLine = startLine;
    var skipped = 0;
    for (var i = startLine - 1; i > 0; i -= 1) {
      var mdNode = toastMark.findFirstNodeAtLine(i);
      var text2 = getTextByMdLine(doc3, i);
      var canBeListNode = text2 && !!findClosestNode(mdNode, function(targetNode) {
        return isListNode$1(targetNode);
      });
      var searchResult = reOrderedListGroup.exec(getTextByMdLine(doc3, i));
      if (!searchResult && !canBeListNode) {
        break;
      }
      if (!searchResult && canBeListNode) {
        skipped += 1;
        continue;
      }
      var _b = searchResult, indent2 = _b[1], start = _b[3];
      if (!indent2) {
        firstOrderedListNum = Number(start);
        firstOrderedListLine = i;
        break;
      }
    }
    var ordinalNum = firstOrderedListNum + line - firstOrderedListLine - skipped;
    var changedResults = [{ text: ordinalNum + ". " + lineText, line }];
    return { changedResults };
  },
  task: function(_a) {
    var doc3 = _a.doc, line = _a.line;
    var lineText = getTextByMdLine(doc3, line);
    var changedResults = [{ text: "* [ ] " + lineText, line }];
    return { changedResults };
  }
};
var extendList = {
  bullet: function(_a) {
    var line = _a.line, doc3 = _a.doc;
    var lineText = getTextByMdLine(doc3, line);
    var _b = reBulletListGroup.exec(lineText), indent2 = _b[1], delimiter = _b[2];
    return { listSyntax: "" + indent2 + delimiter };
  },
  ordered: function(_a) {
    var toastMark = _a.toastMark, line = _a.line, mdNode = _a.mdNode, doc3 = _a.doc;
    var depth = getListDepth(mdNode);
    var lineText = getTextByMdLine(doc3, line);
    var _b = reOrderedListGroup.exec(lineText), indent2 = _b[1], start = _b[3], delimiter = _b[4];
    var ordinalNum = Number(start) + 1;
    var listSyntax = "" + indent2 + ordinalNum + delimiter;
    var backwardList = findSameDepthList(toastMark, line, depth, true);
    var filteredList = backwardList.filter(function(info) {
      var searchResult = reOrderedListGroup.exec(getTextByMdLine(doc3, info.line));
      return searchResult && searchResult[1].length === indent2.length && !!findClosestNode(info.mdNode, function(targetNode) {
        return isOrderedListNode(targetNode);
      });
    });
    return __assign$1({ listSyntax }, getChangedInfo(doc3, filteredList, "ordered", ordinalNum));
  }
};
function getReorderedListInfo(doc3, schema, line, ordinalNum, prevIndentLength) {
  var nodes = [];
  var lineText = getTextByMdLine(doc3, line);
  var searchResult = reOrderedListGroup.exec(lineText);
  while (searchResult) {
    var indent2 = searchResult[1], delimiter = searchResult[4], text2 = searchResult[5];
    var indentLength = indent2.length;
    if (indentLength === prevIndentLength) {
      nodes.push(createTextNode$1(schema, "" + indent2 + ordinalNum + delimiter + text2));
      ordinalNum += 1;
      line += 1;
    } else if (indentLength > prevIndentLength) {
      var nestedListInfo = getReorderedListInfo(doc3, schema, line, 1, indentLength);
      line = nestedListInfo.line;
      nodes = nodes.concat(nestedListInfo.nodes);
    }
    if (indentLength < prevIndentLength || line > doc3.childCount) {
      break;
    }
    lineText = getTextByMdLine(doc3, line);
    searchResult = reOrderedListGroup.exec(lineText);
  }
  return { nodes, line };
}
var reStartSpace = /(^\s{1,4})(.*)/;
function isBlockUnit(from2, to, text2) {
  return from2 < to || reList.test(text2) || reBlockQuote.test(text2);
}
function isInTableCellNode(doc3, schema, selection) {
  var $pos = selection.$from;
  if ($pos.depth === 0) {
    $pos = doc3.resolve($pos.pos - 1);
  }
  var node = $pos.node(1);
  var startOffset = $pos.start(1);
  var contentSize = node.content.size;
  return node.rangeHasMark(0, contentSize, schema.marks.table) && $pos.pos - startOffset !== contentSize && $pos.pos !== startOffset;
}
function createSelection(tr, posInfo) {
  var from2 = posInfo.from, to = posInfo.to;
  if (posInfo.type === "indent") {
    var softTabLen = 4;
    from2 += softTabLen;
    to += (posInfo.lineLen + 1) * softTabLen;
  } else {
    var spaceLenList = posInfo.spaceLenList;
    from2 -= spaceLenList[0];
    for (var i = 0; i < spaceLenList.length; i += 1) {
      to -= spaceLenList[i];
    }
  }
  return createTextSelection(tr, from2, to);
}
var Paragraph$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Paragraph2, _super);
    function Paragraph2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Paragraph2.prototype, "name", {
      get: function() {
        return "paragraph";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Paragraph2.prototype, "schema", {
      get: function() {
        return {
          content: "inline*",
          attrs: {
            className: { default: null },
            codeStart: { default: null },
            codeEnd: { default: null }
          },
          selectable: false,
          group: "block",
          parseDOM: [{ tag: "div" }],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return attrs.className ? ["div", { class: clsWithMdPrefix(attrs.className) }, 0] : ["div", 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Paragraph2.prototype.reorderList = function(startLine, endLine) {
      var _a = this.context, view = _a.view, toastMark = _a.toastMark, schema = _a.schema;
      var _b = view.state, tr = _b.tr, selection = _b.selection, doc3 = _b.doc;
      var mdNode = toastMark.findFirstNodeAtLine(startLine);
      var topListNode = mdNode;
      while (mdNode && !isBulletListNode(mdNode) && mdNode.parent.type !== "document") {
        mdNode = mdNode.parent;
        if (isOrderedListNode(mdNode)) {
          topListNode = mdNode;
          break;
        }
      }
      if (topListNode) {
        startLine = topListNode.sourcepos[0][0];
      }
      var _c = reOrderedListGroup.exec(getTextByMdLine(doc3, startLine)), indent2 = _c[1], start = _c[3];
      var indentLen = indent2.length;
      var _d = getReorderedListInfo(doc3, schema, startLine, Number(start), indentLen), line = _d.line, nodes = _d.nodes;
      endLine = Math.max(endLine, line - 1);
      var startOffset = getNodeContentOffsetRange(doc3, startLine - 1).startOffset;
      for (var i = startLine - 1; i <= endLine - 1; i += 1) {
        var _e = doc3.child(i), nodeSize2 = _e.nodeSize, content = _e.content;
        var mappedFrom = tr.mapping.map(startOffset);
        var mappedTo = mappedFrom + content.size;
        tr.replaceWith(mappedFrom, mappedTo, nodes[i - startLine + 1]);
        startOffset += nodeSize2;
      }
      var newSelection = createTextSelection(tr, selection.from, selection.to);
      view.dispatch(tr.setSelection(newSelection));
    };
    Paragraph2.prototype.indent = function(tabKey) {
      var _this = this;
      if (tabKey === void 0) {
        tabKey = false;
      }
      return function() {
        return function(state, dispatch) {
          var schema = state.schema, selection = state.selection, doc3 = state.doc;
          var _a = getRangeInfo(selection), from2 = _a.from, to = _a.to, startFromOffset = _a.startFromOffset, startIndex = _a.startIndex, endIndex = _a.endIndex;
          if (tabKey && isInTableCellNode(doc3, schema, selection)) {
            return false;
          }
          var startLineText = getTextContent(doc3, startIndex);
          if (tabKey && isBlockUnit(from2, to, startLineText) || !tabKey && reList.test(startLineText)) {
            var tr = replaceTextNode({
              state,
              from: startFromOffset,
              startIndex,
              endIndex,
              createText: function(textContent) {
                return "    " + textContent;
              }
            });
            var posInfo = {
              type: "indent",
              from: from2,
              to,
              lineLen: endIndex - startIndex
            };
            dispatch(tr.setSelection(createSelection(tr, posInfo)));
            if (reOrderedListGroup.test(startLineText)) {
              _this.reorderList(startIndex + 1, endIndex + 1);
            }
          } else if (tabKey) {
            dispatch(state.tr.insert(to, createTextNode$1(schema, "    ")));
          }
          return true;
        };
      };
    };
    Paragraph2.prototype.outdent = function(tabKey) {
      var _this = this;
      if (tabKey === void 0) {
        tabKey = false;
      }
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, doc3 = state.doc, schema = state.schema;
          var _a = getRangeInfo(selection), from2 = _a.from, to = _a.to, startFromOffset = _a.startFromOffset, startIndex = _a.startIndex, endIndex = _a.endIndex;
          if (tabKey && isInTableCellNode(doc3, schema, selection)) {
            return false;
          }
          var startLineText = getTextContent(doc3, startIndex);
          if (tabKey && isBlockUnit(from2, to, startLineText) || !tabKey && reList.test(startLineText)) {
            var spaceLenList_1 = [];
            var tr = replaceTextNode({
              state,
              from: startFromOffset,
              startIndex,
              endIndex,
              createText: function(textContent) {
                var searchResult = reStartSpace.exec(textContent);
                spaceLenList_1.push(searchResult ? searchResult[1].length : 0);
                return textContent.replace(reStartSpace, "$2");
              }
            });
            var posInfo = { type: "outdent", from: from2, to, spaceLenList: spaceLenList_1 };
            dispatch(tr.setSelection(createSelection(tr, posInfo)));
            if (reOrderedListGroup.test(startLineText)) {
              _this.reorderList(startIndex + 1, endIndex + 1);
            }
          } else if (tabKey) {
            var startText = startLineText.slice(0, to - startFromOffset);
            var startTextWithoutSpace = startText.replace(/\s{1,4}$/, "");
            var deletStart = to - (startText.length - startTextWithoutSpace.length);
            dispatch(state.tr.delete(deletStart, to));
          }
          return true;
        };
      };
    };
    Paragraph2.prototype.deleteLines = function() {
      var _this = this;
      return function(state, dispatch) {
        var view = _this.context.view;
        var _a = getRangeInfo(state.selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset;
        var deleteRange2 = function() {
          dispatch(state.tr.deleteRange(startFromOffset, endToOffset));
          return true;
        };
        return chainCommands(deleteRange2, joinForward)(state, dispatch, view);
      };
    };
    Paragraph2.prototype.moveDown = function() {
      return function(state, dispatch) {
        var doc3 = state.doc, tr = state.tr, selection = state.selection, schema = state.schema;
        var _a = getRangeInfo(selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset, endIndex = _a.endIndex;
        if (endIndex < doc3.content.childCount - 1) {
          var _b = doc3.child(endIndex + 1), nodeSize2 = _b.nodeSize, textContent = _b.textContent;
          tr.delete(endToOffset, endToOffset + nodeSize2).split(startFromOffset).insert(tr.mapping.map(startFromOffset) - 2, createTextNode$1(schema, textContent));
          dispatch(tr);
          return true;
        }
        return false;
      };
    };
    Paragraph2.prototype.moveUp = function() {
      return function(state, dispatch) {
        var tr = state.tr, doc3 = state.doc, selection = state.selection, schema = state.schema;
        var _a = getRangeInfo(selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset, startIndex = _a.startIndex;
        if (startIndex > 0) {
          var _b = doc3.child(startIndex - 1), nodeSize2 = _b.nodeSize, textContent = _b.textContent;
          tr.delete(startFromOffset - nodeSize2, startFromOffset).split(tr.mapping.map(endToOffset)).insert(tr.mapping.map(endToOffset), createTextNode$1(schema, textContent));
          dispatch(tr);
          return true;
        }
        return false;
      };
    };
    Paragraph2.prototype.commands = function() {
      return {
        indent: this.indent(),
        outdent: this.outdent()
      };
    };
    Paragraph2.prototype.keymaps = function() {
      return {
        Tab: this.indent(true)(),
        "Shift-Tab": this.outdent(true)(),
        "Mod-d": this.deleteLines(),
        "Mod-D": this.deleteLines(),
        "Alt-ArrowUp": this.moveUp(),
        "Alt-ArrowDown": this.moveDown()
      };
    };
    return Paragraph2;
  })(Node$2)
);
var Text$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Text2, _super);
    function Text2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Text2.prototype, "name", {
      get: function() {
        return "text";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Text2.prototype, "schema", {
      get: function() {
        return {
          group: "inline"
        };
      },
      enumerable: false,
      configurable: true
    });
    return Text2;
  })(Node$2)
);
var reHeading = /^#{1,6}\s/;
var Heading$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Heading2, _super);
    function Heading2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Heading2.prototype, "name", {
      get: function() {
        return "heading";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Heading2.prototype, "schema", {
      get: function() {
        return {
          attrs: {
            level: { default: 1 },
            seText: { default: false }
          },
          toDOM: function(_a) {
            var attrs = _a.attrs;
            var level = attrs.level, seText = attrs.seText;
            var classNames = "heading|heading" + level;
            if (seText) {
              classNames += "|delimiter|setext";
            }
            return ["span", { class: clsWithMdPrefix.apply(void 0, classNames.split("|")) }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Heading2.prototype.createHeadingText = function(level, text2, curHeadingSyntax) {
      var textContent = text2.replace(curHeadingSyntax, "").trim();
      var headingText = "";
      while (level > 0) {
        headingText += "#";
        level -= 1;
      }
      return headingText + " " + textContent;
    };
    Heading2.prototype.commands = function() {
      var _this = this;
      return function(payload) {
        return function(state, dispatch) {
          var level = payload.level;
          var _a = getRangeInfo(state.selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset, startIndex = _a.startIndex, endIndex = _a.endIndex;
          var tr = replaceTextNode({
            state,
            from: startFromOffset,
            startIndex,
            endIndex,
            createText: function(textContent) {
              var matchedHeading = textContent.match(reHeading);
              var curHeadingSyntax = matchedHeading ? matchedHeading[0] : "";
              return _this.createHeadingText(level, textContent, curHeadingSyntax);
            }
          });
          dispatch(tr.setSelection(createTextSelection(tr, tr.mapping.map(endToOffset))));
          return true;
        };
      };
    };
    return Heading2;
  })(Mark2)
);
var fencedCodeBlockSyntax = "```";
var CodeBlock$1 = (
  /** @class */
  (function(_super) {
    __extends$1(CodeBlock2, _super);
    function CodeBlock2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(CodeBlock2.prototype, "name", {
      get: function() {
        return "codeBlock";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(CodeBlock2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("code-block") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    CodeBlock2.prototype.commands = function() {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, schema = state.schema, tr = state.tr;
          var _a = getRangeInfo(selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset;
          var fencedNode = createTextNode$1(schema, fencedCodeBlockSyntax);
          tr.insert(startFromOffset, fencedNode).split(startFromOffset + fencedCodeBlockSyntax.length);
          tr.split(tr.mapping.map(endToOffset)).insert(tr.mapping.map(endToOffset), fencedNode);
          dispatch(tr.setSelection(
            // subtract fenced syntax length and open, close tag(2)
            createTextSelection(tr, tr.mapping.map(endToOffset) - (fencedCodeBlockSyntax.length + 2))
          ));
          return true;
        };
      };
    };
    CodeBlock2.prototype.keepIndentation = function() {
      var _this = this;
      return function(_a, dispatch) {
        var selection = _a.selection, tr = _a.tr, doc3 = _a.doc, schema = _a.schema;
        var toastMark = _this.context.toastMark;
        var _b = getRangeInfo(selection), startFromOffset = _b.startFromOffset, endToOffset = _b.endToOffset, endIndex = _b.endIndex, from2 = _b.from, to = _b.to;
        var textContent = getTextContent(doc3, endIndex);
        if (from2 === to && textContent.trim()) {
          var matched = textContent.match(/^\s+/);
          var mdNode = toastMark.findFirstNodeAtLine(endIndex + 1);
          if (isCodeBlockNode(mdNode) && matched) {
            var spaces = matched[0];
            var slicedText = textContent.slice(to - startFromOffset);
            var node = createTextNode$1(schema, spaces + slicedText);
            splitAndExtendBlock(tr, endToOffset, slicedText, node);
            dispatch(tr);
            return true;
          }
        }
        return false;
      };
    };
    CodeBlock2.prototype.keymaps = function() {
      var codeBlockCommand = this.commands()();
      return {
        "Shift-Mod-p": codeBlockCommand,
        "Shift-Mod-P": codeBlockCommand,
        Enter: this.keepIndentation()
      };
    };
    return CodeBlock2;
  })(Mark2)
);
var reEmptyTable = /\||\s/g;
function createTableHeader(columnCount) {
  return [createTableRow(columnCount), createTableRow(columnCount, true)];
}
function createTableBody$1(columnCount, rowCount) {
  var bodyRows = [];
  for (var i = 0; i < rowCount; i += 1) {
    bodyRows.push(createTableRow(columnCount));
  }
  return bodyRows;
}
function createTableRow(columnCount, delim) {
  var row = "|";
  for (var i = 0; i < columnCount; i += 1) {
    row += delim ? " --- |" : "  |";
  }
  return row;
}
function createTargetTypes(moveNext) {
  return moveNext ? { type: "next", parentType: "tableHead", childType: "firstChild" } : { type: "prev", parentType: "tableBody", childType: "lastChild" };
}
var Table$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Table2, _super);
    function Table2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Table2.prototype, "name", {
      get: function() {
        return "table";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Table2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("table") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Table2.prototype.extendTable = function() {
      var _this = this;
      return function(_a, dispatch) {
        var selection = _a.selection, doc3 = _a.doc, tr = _a.tr, schema = _a.schema;
        if (!selection.empty) {
          return false;
        }
        var _b = getRangeInfo(selection), endFromOffset = _b.endFromOffset, endToOffset = _b.endToOffset, endIndex = _b.endIndex, to = _b.to;
        var textContent = getTextContent(doc3, endIndex);
        var mdPos = [endIndex + 1, to - endFromOffset + 1];
        var mdNode = _this.context.toastMark.findNodeAtPosition(mdPos);
        var cellNode = findClosestNode(mdNode, function(node) {
          return isTableCellNode(node) && (node.parent.type === "tableDelimRow" || node.parent.parent.type === "tableBody");
        });
        if (cellNode) {
          var isEmpty2 = !textContent.replace(reEmptyTable, "").trim();
          var parent_1 = cellNode.parent;
          var columnCount = parent_1.parent.parent.columns.length;
          var row = createTableRow(columnCount);
          if (isEmpty2) {
            tr.deleteRange(endFromOffset, endToOffset).split(tr.mapping.map(endToOffset));
          } else {
            tr.split(endToOffset).insert(tr.mapping.map(endToOffset), createTextNode$1(schema, row)).setSelection(createTextSelection(tr, tr.mapping.map(endToOffset) - 2));
          }
          dispatch(tr);
          return true;
        }
        return false;
      };
    };
    Table2.prototype.moveTableCell = function(moveNext) {
      var _this = this;
      return function(_a, dispatch) {
        var selection = _a.selection, tr = _a.tr;
        var _b = getRangeInfo(selection), endFromOffset = _b.endFromOffset, endIndex = _b.endIndex, to = _b.to;
        var mdPos = [endIndex + 1, to - endFromOffset];
        var mdNode = _this.context.toastMark.findNodeAtPosition(mdPos);
        var cellNode = findClosestNode(mdNode, function(node) {
          return isTableCellNode(node);
        });
        if (cellNode) {
          var parent_2 = cellNode.parent;
          var _c = createTargetTypes(moveNext), type = _c.type, parentType = _c.parentType, childType = _c.childType;
          var chOffset = getMdEndCh(cellNode);
          if (cellNode[type]) {
            chOffset = getMdEndCh(cellNode[type]) - 1;
          } else {
            var row = !parent_2[type] && parent_2.parent.type === parentType ? parent_2.parent[type][childType] : parent_2[type];
            if (type === "next") {
              var baseOffset = row ? getMdEndCh(row[childType]) : 0;
              chOffset += baseOffset + 2;
            } else if (type === "prev") {
              chOffset = row ? -4 : 0;
            }
          }
          dispatch(tr.setSelection(createTextSelection(tr, endFromOffset + chOffset)));
          return true;
        }
        return false;
      };
    };
    Table2.prototype.addTable = function() {
      return function(payload) {
        return function(_a, dispatch) {
          var selection = _a.selection, tr = _a.tr, schema = _a.schema;
          var _b = payload, columnCount = _b.columnCount, rowCount = _b.rowCount;
          var endToOffset = getRangeInfo(selection).endToOffset;
          var headerRows = createTableHeader(columnCount);
          var bodyRows = createTableBody$1(columnCount, rowCount - 1);
          var rows = __spreadArray$1(__spreadArray$1([], headerRows), bodyRows);
          rows.forEach(function(row) {
            tr.split(tr.mapping.map(endToOffset)).insert(tr.mapping.map(endToOffset), createTextNode$1(schema, row));
          });
          dispatch(tr.setSelection(createTextSelection(tr, endToOffset + 4)));
          return true;
        };
      };
    };
    Table2.prototype.commands = function() {
      return { addTable: this.addTable() };
    };
    Table2.prototype.keymaps = function() {
      return {
        Enter: this.extendTable(),
        Tab: this.moveTableCell(true),
        "Shift-Tab": this.moveTableCell(false)
      };
    };
    return Table2;
  })(Mark2)
);
var thematicBreakSyntax = "***";
var ThematicBreak$1 = (
  /** @class */
  (function(_super) {
    __extends$1(ThematicBreak2, _super);
    function ThematicBreak2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ThematicBreak2.prototype, "name", {
      get: function() {
        return "thematicBreak";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(ThematicBreak2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("thematic-break") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    ThematicBreak2.prototype.hr = function() {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, schema = state.schema, tr = state.tr;
          var _a = getRangeInfo(selection), from2 = _a.from, to = _a.to, endToOffset = _a.endToOffset;
          var node = createTextNode$1(schema, thematicBreakSyntax);
          tr.split(from2).replaceWith(tr.mapping.map(from2), tr.mapping.map(to), node).split(tr.mapping.map(to)).setSelection(createTextSelection(tr, tr.mapping.map(endToOffset)));
          dispatch(tr);
          return true;
        };
      };
    };
    ThematicBreak2.prototype.commands = function() {
      return { hr: this.hr() };
    };
    ThematicBreak2.prototype.keymaps = function() {
      var lineCommand = this.hr()();
      return { "Mod-l": lineCommand, "Mod-L": lineCommand };
    };
    return ThematicBreak2;
  })(Mark2)
);
function cannotBeListNode(_a, line) {
  var type = _a.type, sourcepos = _a.sourcepos;
  var startLine = sourcepos[0][0];
  return line <= startLine && (type === "codeBlock" || type === "heading" || type.match("table"));
}
var ListItem$1 = (
  /** @class */
  (function(_super) {
    __extends$1(ListItem2, _super);
    function ListItem2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ListItem2.prototype, "name", {
      get: function() {
        return "listItem";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(ListItem2.prototype, "schema", {
      get: function() {
        return {
          attrs: {
            odd: { default: false },
            even: { default: false },
            listStyle: { default: false }
          },
          toDOM: function(_a) {
            var attrs = _a.attrs;
            var odd = attrs.odd, even = attrs.even, listStyle = attrs.listStyle;
            var classNames = "list-item";
            if (listStyle) {
              classNames += "|list-item-style";
            }
            if (odd) {
              classNames += "|list-item-odd";
            }
            if (even) {
              classNames += "|list-item-even";
            }
            return ["span", { class: clsWithMdPrefix.apply(void 0, classNames.split("|")) }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    ListItem2.prototype.extendList = function() {
      var _this = this;
      return function(_a, dispatch) {
        var selection = _a.selection, doc3 = _a.doc, schema = _a.schema, tr = _a.tr;
        var toastMark = _this.context.toastMark;
        var _b = getRangeInfo(selection), to = _b.to, startFromOffset = _b.startFromOffset, endFromOffset = _b.endFromOffset, endIndex = _b.endIndex, endToOffset = _b.endToOffset;
        var textContent = getTextContent(doc3, endIndex);
        var isList2 = reList.test(textContent);
        if (!isList2 || selection.from === startFromOffset || !selection.empty) {
          return false;
        }
        var isEmpty2 = !textContent.replace(reCanBeTaskList, "").trim();
        if (isEmpty2) {
          tr.deleteRange(endFromOffset, endToOffset).split(tr.mapping.map(endToOffset));
        } else {
          var commandType = getListType(textContent);
          var mdNode = toastMark.findFirstNodeAtLine(endIndex + 1);
          var slicedText = textContent.slice(to - endFromOffset);
          var context = { toastMark, mdNode, doc: doc3, line: endIndex + 1 };
          var _c = extendList[commandType](context), listSyntax = _c.listSyntax, changedResults = _c.changedResults;
          if (changedResults === null || changedResults === void 0 ? void 0 : changedResults.length) {
            tr.split(to);
            changedResults.unshift({ text: listSyntax + slicedText, line: endIndex + 1 });
            _this.changeToListPerLine(tr, changedResults, {
              from: to,
              // don't subtract 1 because the line has increased through 'split' command.
              startLine: changedResults[0].line,
              endLine: last$1(changedResults).line
            });
            var pos = tr.mapping.map(endToOffset) - slicedText.length;
            tr.setSelection(createTextSelection(tr, pos));
          } else {
            var node = createTextNode$1(schema, listSyntax + slicedText);
            splitAndExtendBlock(tr, endToOffset, slicedText, node);
          }
        }
        dispatch(tr);
        return true;
      };
    };
    ListItem2.prototype.toList = function(commandType) {
      var _this = this;
      return function() {
        return function(_a, dispatch) {
          var doc3 = _a.doc, tr = _a.tr, selection = _a.selection;
          var toastMark = _this.context.toastMark;
          var rangeInfo = getRangeInfo(selection);
          var startLine = rangeInfo.startIndex + 1;
          var endLine = rangeInfo.endIndex + 1;
          var endToOffset = rangeInfo.endToOffset;
          var skipLines = [];
          for (var line = startLine; line <= endLine; line += 1) {
            var mdNode = toastMark.findFirstNodeAtLine(line);
            if (mdNode && cannotBeListNode(mdNode, line)) {
              break;
            }
            if (skipLines.indexOf(line) !== -1) {
              continue;
            }
            var context = { toastMark, mdNode, doc: doc3, line, startLine };
            var changedResults = (isListNode$1(mdNode) ? otherListToList[commandType](context) : otherNodeToList[commandType](context)).changedResults;
            var endOffset = _this.changeToListPerLine(tr, changedResults, {
              from: getNodeContentOffsetRange(doc3, changedResults[0].line - 1).startOffset,
              startLine: changedResults[0].line,
              endLine: last$1(changedResults).line,
              indexDiff: 1
            });
            endToOffset = Math.max(endOffset, endToOffset);
            if (changedResults) {
              skipLines = skipLines.concat(changedResults.map(function(info) {
                return info.line;
              }));
            }
          }
          dispatch(tr.setSelection(createTextSelection(tr, tr.mapping.map(endToOffset))));
          return true;
        };
      };
    };
    ListItem2.prototype.changeToListPerLine = function(tr, changedResults, _a) {
      var from2 = _a.from, startLine = _a.startLine, endLine = _a.endLine, _b = _a.indexDiff, indexDiff = _b === void 0 ? 0 : _b;
      var maxEndOffset = 0;
      var _loop_1 = function(i2) {
        var _c = tr.doc.child(i2), nodeSize2 = _c.nodeSize, content = _c.content;
        var mappedFrom = tr.mapping.map(from2);
        var mappedTo = mappedFrom + content.size;
        var changedResult = changedResults.filter(function(result) {
          return result.line - indexDiff === i2;
        })[0];
        if (changedResult) {
          tr.replaceWith(mappedFrom, mappedTo, createTextNode$1(this_1.context.schema, changedResult.text));
          maxEndOffset = Math.max(maxEndOffset, from2 + content.size);
        }
        from2 += nodeSize2;
      };
      var this_1 = this;
      for (var i = startLine - indexDiff; i <= endLine - indexDiff; i += 1) {
        _loop_1(i);
      }
      return maxEndOffset;
    };
    ListItem2.prototype.toggleTask = function() {
      var _this = this;
      return function(_a, dispatch) {
        var selection = _a.selection, tr = _a.tr, doc3 = _a.doc, schema = _a.schema;
        var toastMark = _this.context.toastMark;
        var _b = getRangeInfo(selection), startIndex = _b.startIndex, endIndex = _b.endIndex;
        var newTr = null;
        for (var i = startIndex; i <= endIndex; i += 1) {
          var mdNode = toastMark.findFirstNodeAtLine(i + 1);
          if (isListNode$1(mdNode) && mdNode.listData.task) {
            var _c = mdNode.listData, checked = _c.checked, padding = _c.padding;
            var stateChar = checked ? " " : "x";
            var mdPos = mdNode.sourcepos[0];
            var startOffset = getNodeContentOffsetRange(doc3, mdPos[0] - 1).startOffset;
            startOffset += mdPos[1] + padding;
            newTr = tr.replaceWith(startOffset, startOffset + 1, schema.text(stateChar));
          }
        }
        if (newTr) {
          dispatch(newTr);
          return true;
        }
        return false;
      };
    };
    ListItem2.prototype.commands = function() {
      return {
        bulletList: this.toList("bullet"),
        orderedList: this.toList("ordered"),
        taskList: this.toList("task")
      };
    };
    ListItem2.prototype.keymaps = function() {
      var bulletCommand = this.toList("bullet")();
      var orderedCommand = this.toList("ordered")();
      var taskCommand = this.toList("task")();
      var togleTaskCommand = this.toggleTask();
      return {
        "Mod-u": bulletCommand,
        "Mod-U": bulletCommand,
        "Mod-o": orderedCommand,
        "Mod-O": orderedCommand,
        "alt-t": taskCommand,
        "alt-T": taskCommand,
        "Shift-Ctrl-x": togleTaskCommand,
        "Shift-Ctrl-X": togleTaskCommand,
        Enter: this.extendList()
      };
    };
    return ListItem2;
  })(Mark2)
);
function toggleMark2(condition, syntax) {
  return function() {
    return function(_a, dispatch) {
      var tr = _a.tr, selection = _a.selection;
      var conditionFn = !isFunction_1(condition) ? function(text2) {
        return condition.test(text2);
      } : condition;
      var syntaxLen = syntax.length;
      var doc3 = tr.doc;
      var _b = resolveSelectionPos(selection), from2 = _b[0], to = _b[1];
      var prevPos = Math.max(from2 - syntaxLen, 1);
      var nextPos = Math.min(to + syntaxLen, doc3.content.size - 1);
      var slice2 = selection.content();
      var textContent = slice2.content.textBetween(0, slice2.content.size, "\n");
      var prevText = doc3.textBetween(prevPos, from2, "\n");
      var nextText = doc3.textBetween(to, nextPos, "\n");
      textContent = "" + prevText + textContent + nextText;
      if (prevText && nextText && conditionFn(textContent)) {
        tr.delete(nextPos - syntaxLen, nextPos).delete(prevPos, prevPos + syntaxLen);
      } else {
        tr.insertText(syntax, to).insertText(syntax, from2);
        var newSelection = selection.empty ? createTextSelection(tr, from2 + syntaxLen) : createTextSelection(tr, from2 + syntaxLen, to + syntaxLen);
        tr.setSelection(newSelection);
      }
      dispatch(tr);
      return true;
    };
  };
}
var reStrong = /^(\*{2}|_{2}).*([\s\S]*)\1$/m;
var strongSyntax = "**";
var Strong$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Strong2, _super);
    function Strong2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Strong2.prototype, "name", {
      get: function() {
        return "strong";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Strong2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("strong") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Strong2.prototype.bold = function() {
      return toggleMark2(reStrong, strongSyntax);
    };
    Strong2.prototype.commands = function() {
      return { bold: this.bold() };
    };
    Strong2.prototype.keymaps = function() {
      var boldCommand = this.bold()();
      return { "Mod-b": boldCommand, "Mod-B": boldCommand };
    };
    return Strong2;
  })(Mark2)
);
var reStrike = /^(~{2}).*([\s\S]*)\1$/m;
var strikeSyntax = "~~";
var Strike$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Strike2, _super);
    function Strike2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Strike2.prototype, "name", {
      get: function() {
        return "strike";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Strike2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("strike") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Strike2.prototype.commands = function() {
      return toggleMark2(reStrike, strikeSyntax);
    };
    Strike2.prototype.keymaps = function() {
      var strikeCommand = this.commands()();
      return { "Mod-s": strikeCommand, "Mod-S": strikeCommand };
    };
    return Strike2;
  })(Mark2)
);
var reEmph = /^(\*|_).*([\s\S]*)\1$/m;
var emphSyntax = "*";
var Emph$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Emph2, _super);
    function Emph2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Emph2.prototype, "name", {
      get: function() {
        return "emph";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Emph2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("emph") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Emph2.prototype.italic = function() {
      return toggleMark2(reEmph, emphSyntax);
    };
    Emph2.prototype.commands = function() {
      return { italic: this.italic() };
    };
    Emph2.prototype.keymaps = function() {
      var italicCommand = this.italic()();
      return { "Mod-i": italicCommand, "Mod-I": italicCommand };
    };
    return Emph2;
  })(Mark2)
);
var reCode = /^(`).*([\s\S]*)\1$/m;
var codeSyntax = "`";
var Code$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Code2, _super);
    function Code2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Code2.prototype, "name", {
      get: function() {
        return "code";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Code2.prototype, "schema", {
      get: function() {
        return {
          attrs: {
            start: { default: false },
            end: { default: false },
            marked: { default: false }
          },
          toDOM: function(mark) {
            var _a = mark.attrs, start = _a.start, end = _a.end, marked = _a.marked;
            var classNames = "code";
            if (start) {
              classNames += "|delimiter|start";
            }
            if (end) {
              classNames += "|delimiter|end";
            }
            if (marked) {
              classNames += "|marked-text";
            }
            return ["span", { class: clsWithMdPrefix.apply(void 0, classNames.split("|")) }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Code2.prototype.commands = function() {
      return toggleMark2(reCode, codeSyntax);
    };
    Code2.prototype.keymaps = function() {
      var codeCommand = this.commands()();
      return { "Shift-Mod-c": codeCommand, "Shift-Mod-C": codeCommand };
    };
    return Code2;
  })(Mark2)
);
var Link$1 = (
  /** @class */
  (function(_super) {
    __extends$1(Link2, _super);
    function Link2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Link2.prototype, "name", {
      get: function() {
        return "link";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Link2.prototype, "schema", {
      get: function() {
        return {
          attrs: {
            url: { default: false },
            desc: { default: false }
          },
          toDOM: function(_a) {
            var attrs = _a.attrs;
            var url = attrs.url, desc = attrs.desc;
            var classNames = "link";
            if (url) {
              classNames += "|link-url|marked-text";
            }
            if (desc) {
              classNames += "|link-desc|marked-text";
            }
            return ["span", { class: clsWithMdPrefix.apply(void 0, classNames.split("|")) }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Link2.prototype.addLinkOrImage = function(commandType) {
      return function(payload) {
        return function(_a, dispatch) {
          var selection = _a.selection, tr = _a.tr, schema = _a.schema;
          var _b = resolveSelectionPos(selection), from2 = _b[0], to = _b[1];
          var _c = payload, linkText = _c.linkText, altText = _c.altText, linkUrl = _c.linkUrl, imageUrl = _c.imageUrl;
          var text2 = linkText;
          var url = linkUrl;
          var syntax = "";
          if (commandType === "image") {
            text2 = altText;
            url = imageUrl;
            syntax = "!";
          }
          text2 = escapeTextForLink(text2);
          syntax += "[" + text2 + "](" + url + ")";
          dispatch(tr.replaceWith(from2, to, createTextNode$1(schema, syntax)));
          return true;
        };
      };
    };
    Link2.prototype.commands = function() {
      return {
        addImage: this.addLinkOrImage("image"),
        addLink: this.addLinkOrImage("link")
      };
    };
    return Link2;
  })(Mark2)
);
var TaskDelimiter = (
  /** @class */
  (function(_super) {
    __extends$1(TaskDelimiter2, _super);
    function TaskDelimiter2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TaskDelimiter2.prototype, "name", {
      get: function() {
        return "taskDelimiter";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TaskDelimiter2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("delimiter", "list-item") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TaskDelimiter2;
  })(Mark2)
);
var Delimiter = (
  /** @class */
  (function(_super) {
    __extends$1(Delimiter2, _super);
    function Delimiter2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Delimiter2.prototype, "name", {
      get: function() {
        return "delimiter";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Delimiter2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("delimiter") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return Delimiter2;
  })(Mark2)
);
var Meta = (
  /** @class */
  (function(_super) {
    __extends$1(Meta2, _super);
    function Meta2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Meta2.prototype, "name", {
      get: function() {
        return "meta";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Meta2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("meta") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return Meta2;
  })(Mark2)
);
var MarkedText = (
  /** @class */
  (function(_super) {
    __extends$1(MarkedText2, _super);
    function MarkedText2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(MarkedText2.prototype, "name", {
      get: function() {
        return "markedText";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(MarkedText2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("marked-text") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return MarkedText2;
  })(Mark2)
);
var TableCell = (
  /** @class */
  (function(_super) {
    __extends$1(TableCell2, _super);
    function TableCell2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TableCell2.prototype, "name", {
      get: function() {
        return "tableCell";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableCell2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("table-cell") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TableCell2;
  })(Mark2)
);
var Html = (
  /** @class */
  (function(_super) {
    __extends$1(Html2, _super);
    function Html2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Html2.prototype, "name", {
      get: function() {
        return "html";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Html2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("html") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return Html2;
  })(Mark2)
);
var customBlockSyntax = "$$";
var CustomBlock$1 = (
  /** @class */
  (function(_super) {
    __extends$1(CustomBlock2, _super);
    function CustomBlock2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(CustomBlock2.prototype, "name", {
      get: function() {
        return "customBlock";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(CustomBlock2.prototype, "schema", {
      get: function() {
        return {
          toDOM: function() {
            return ["span", { class: clsWithMdPrefix("custom-block") }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    CustomBlock2.prototype.commands = function() {
      return function(payload) {
        return function(state, dispatch) {
          var selection = state.selection, schema = state.schema, tr = state.tr;
          var _a = getRangeInfo(selection), startFromOffset = _a.startFromOffset, endToOffset = _a.endToOffset;
          if (!(payload === null || payload === void 0 ? void 0 : payload.info)) {
            return false;
          }
          var customBlock2 = "" + customBlockSyntax + payload.info;
          var startNode = createTextNode$1(schema, customBlock2);
          var endNode = createTextNode$1(schema, customBlockSyntax);
          tr.insert(startFromOffset, startNode).split(startFromOffset + customBlock2.length);
          tr.split(tr.mapping.map(endToOffset)).insert(tr.mapping.map(endToOffset), endNode);
          dispatch(tr.setSelection(createTextSelection(tr, tr.mapping.map(endToOffset) - (customBlockSyntax.length + 2))));
          return true;
        };
      };
    };
    return CustomBlock2;
  })(Mark2)
);
var reTaskMarkerKey = /x|backspace/i;
var reTaskMarker = /^\[(\s*)(x?)(\s*)\](?:\s+)/i;
function smartTask(_a) {
  var schema = _a.schema, toastMark = _a.toastMark;
  return new Plugin({
    props: {
      handleDOMEvents: {
        keyup: function(view, ev) {
          var _a2;
          var _b = view.state, doc3 = _b.doc, tr = _b.tr, selection = _b.selection;
          if (selection.empty && reTaskMarkerKey.test(ev.key)) {
            var _c = getRangeInfo(selection), startIndex = _c.startIndex, startFromOffset = _c.startFromOffset, from2 = _c.from;
            var mdPos = [startIndex + 1, from2 - startFromOffset + 1];
            var mdNode = toastMark.findNodeAtPosition(mdPos);
            var paraNode = findClosestNode(mdNode, function(node) {
              var _a3;
              return node.type === "paragraph" && ((_a3 = node.parent) === null || _a3 === void 0 ? void 0 : _a3.type) === "item";
            });
            if ((_a2 = paraNode === null || paraNode === void 0 ? void 0 : paraNode.firstChild) === null || _a2 === void 0 ? void 0 : _a2.literal) {
              var firstChild = paraNode.firstChild;
              var matched = firstChild.literal.match(reTaskMarker);
              if (matched) {
                var startMdPos = firstChild.sourcepos[0];
                var startSpaces = matched[1], stateChar = matched[2], lastSpaces = matched[3];
                var spaces = startSpaces.length + lastSpaces.length;
                var startOffset = getNodeContentOffsetRange(doc3, startMdPos[0] - 1).startOffset;
                var startPos = startMdPos[1] + startOffset;
                if (stateChar) {
                  var addedPos = spaces ? spaces + 1 : 0;
                  tr.replaceWith(startPos, addedPos + startPos, schema.text(stateChar));
                  view.dispatch(tr);
                } else if (!spaces) {
                  tr.insertText(" ", startPos);
                  view.dispatch(tr);
                }
              }
            }
          }
          return false;
        }
      }
    }
  });
}
var EVENT_TYPE = "cut";
var reLineEnding$2 = /\r\n|\n|\r/;
var MdEditor = (
  /** @class */
  (function(_super) {
    __extends$1(MdEditor2, _super);
    function MdEditor2(eventEmitter, options) {
      var _this = _super.call(this, eventEmitter) || this;
      var toastMark = options.toastMark, _a = options.useCommandShortcut, useCommandShortcut = _a === void 0 ? true : _a, _b = options.mdPlugins, mdPlugins = _b === void 0 ? [] : _b;
      _this.editorType = "markdown";
      _this.el.classList.add("md-mode");
      _this.toastMark = toastMark;
      _this.extraPlugins = mdPlugins;
      _this.specs = _this.createSpecs();
      _this.schema = _this.createSchema();
      _this.context = _this.createContext();
      _this.keymaps = _this.createKeymaps(useCommandShortcut);
      _this.view = _this.createView();
      _this.commands = _this.createCommands();
      _this.specs.setContext(__assign$1(__assign$1({}, _this.context), { view: _this.view }));
      _this.createClipboard();
      _this.eventEmitter.listen("changePreviewTabWrite", function(isMarkdownTabMounted) {
        return _this.toggleActive(true, isMarkdownTabMounted);
      });
      _this.eventEmitter.listen("changePreviewTabPreview", function() {
        return _this.toggleActive(false);
      });
      _this.initEvent();
      return _this;
    }
    MdEditor2.prototype.toggleActive = function(active, isMarkdownTabMounted) {
      toggleClass(this.el, "active", active);
      if (active) {
        if (!isMarkdownTabMounted) {
          this.focus();
        }
      } else {
        this.blur();
      }
    };
    MdEditor2.prototype.createClipboard = function() {
      var _this = this;
      this.clipboard = document.createElement("textarea");
      this.clipboard.className = cls("pseudo-clipboard");
      this.clipboard.addEventListener("paste", function(ev) {
        var clipboardData = ev.clipboardData || window.clipboardData;
        var items = clipboardData && clipboardData.items;
        if (items) {
          var containRtfItem = toArray_1(items).some(function(item2) {
            return item2.kind === "string" && item2.type === "text/rtf";
          });
          if (!containRtfItem) {
            var imageBlob = pasteImageOnly(items);
            if (imageBlob) {
              ev.preventDefault();
              emitImageBlobHook(_this.eventEmitter, imageBlob, ev.type);
            }
          }
        }
      });
      this.clipboard.addEventListener("input", function(ev) {
        var text2 = ev.target.value;
        _this.replaceSelection(text2);
        ev.preventDefault();
        ev.target.value = "";
      });
      this.el.insertBefore(this.clipboard, this.view.dom);
    };
    MdEditor2.prototype.createContext = function() {
      return {
        toastMark: this.toastMark,
        schema: this.schema,
        eventEmitter: this.eventEmitter
      };
    };
    MdEditor2.prototype.createSpecs = function() {
      return new SpecManager([
        new Doc$1(),
        new Paragraph$1(),
        new Widget(),
        new Text$1(),
        new Heading$1(),
        new BlockQuote$1(),
        new CodeBlock$1(),
        new CustomBlock$1(),
        new Table$1(),
        new TableCell(),
        new ThematicBreak$1(),
        new ListItem$1(),
        new Strong$1(),
        new Strike$1(),
        new Emph$1(),
        new Code$1(),
        new Link$1(),
        new Delimiter(),
        new TaskDelimiter(),
        new MarkedText(),
        new Meta(),
        new Html()
      ]);
    };
    MdEditor2.prototype.createPlugins = function() {
      return __spreadArray$1([
        syntaxHighlight(this.context),
        previewHighlight(this.context),
        smartTask(this.context)
      ], this.createPluginProps()).concat(this.defaultPlugins);
    };
    MdEditor2.prototype.createView = function() {
      var _this = this;
      return new EditorView(this.el, {
        state: this.createState(),
        dispatchTransaction: function(tr) {
          _this.updateMarkdown(tr);
          var state = _this.view.state.applyTransaction(tr).state;
          _this.view.updateState(state);
          _this.emitChangeEvent(tr);
        },
        handleKeyDown: function(_, ev) {
          if ((ev.metaKey || ev.ctrlKey) && ev.key.toUpperCase() === "V") {
            _this.clipboard.focus();
          }
          _this.eventEmitter.emit("keydown", _this.editorType, ev);
          return false;
        },
        handleDOMEvents: {
          copy: function(_, ev) {
            return _this.captureCopy(ev);
          },
          cut: function(_, ev) {
            return _this.captureCopy(ev, EVENT_TYPE);
          },
          scroll: function() {
            _this.eventEmitter.emit("scroll", "editor");
            return true;
          },
          keyup: function(_, ev) {
            _this.eventEmitter.emit("keyup", _this.editorType, ev);
            return false;
          }
        },
        nodeViews: {
          widget: widgetNodeView
        }
      });
    };
    MdEditor2.prototype.createCommands = function() {
      return this.specs.commands(this.view);
    };
    MdEditor2.prototype.captureCopy = function(ev, type) {
      ev.preventDefault();
      var _a = this.view.state, selection = _a.selection, tr = _a.tr;
      if (selection.empty) {
        return true;
      }
      var text2 = this.getChanged(selection.content());
      if (ev.clipboardData) {
        ev.clipboardData.setData("text/plain", text2);
      } else {
        window.clipboardData.setData("Text", text2);
      }
      if (type === EVENT_TYPE) {
        this.view.dispatch(tr.deleteSelection().scrollIntoView().setMeta("uiEvent", EVENT_TYPE));
      }
      return true;
    };
    MdEditor2.prototype.updateMarkdown = function(tr) {
      var _this = this;
      if (tr.docChanged) {
        tr.steps.forEach(function(step, index2) {
          if (step.slice && !(step instanceof ReplaceAroundStep)) {
            var doc3 = tr.docs[index2];
            var _a = [step.from, step.to], from2 = _a[0], to = _a[1];
            var _b = getEditorToMdPos(doc3, from2, to), startPos = _b[0], endPos = _b[1];
            var changed = _this.getChanged(step.slice);
            if (startPos[0] === endPos[0] && startPos[1] === endPos[1] && changed === "") {
              changed = "\n";
            }
            var editResult = _this.toastMark.editMarkdown(startPos, endPos, changed);
            _this.eventEmitter.emit("updatePreview", editResult);
            tr.setMeta("editResult", editResult).scrollIntoView();
          }
        });
      }
    };
    MdEditor2.prototype.getChanged = function(slice2) {
      var changed = "";
      var from2 = 0;
      var to = slice2.content.size;
      slice2.content.nodesBetween(from2, to, function(node, pos) {
        if (node.isText) {
          changed += node.text.slice(Math.max(from2, pos) - pos, to - pos);
        } else if (node.isBlock && pos > 0) {
          changed += "\n";
        }
      });
      return changed;
    };
    MdEditor2.prototype.setSelection = function(start, end) {
      if (end === void 0) {
        end = start;
      }
      var tr = this.view.state.tr;
      var _a = getMdToEditorPos(tr.doc, start, end), from2 = _a[0], to = _a[1];
      this.view.dispatch(tr.setSelection(createTextSelection(tr, from2, to)).scrollIntoView());
    };
    MdEditor2.prototype.replaceSelection = function(text2, start, end) {
      var newTr;
      var _a = this.view.state, tr = _a.tr, schema = _a.schema, doc3 = _a.doc;
      var lineTexts = text2.split(reLineEnding$2);
      var nodes = lineTexts.map(function(lineText) {
        return createParagraph(schema, createNodesWithWidget(lineText, schema));
      });
      var slice2 = new Slice(Fragment.from(nodes), 1, 1);
      this.focus();
      if (start && end) {
        var _b = getMdToEditorPos(doc3, start, end), from2 = _b[0], to = _b[1];
        newTr = tr.replaceRange(from2, to, slice2);
      } else {
        newTr = tr.replaceSelection(slice2);
      }
      this.view.dispatch(newTr.scrollIntoView());
    };
    MdEditor2.prototype.deleteSelection = function(start, end) {
      var newTr;
      var _a = this.view.state, tr = _a.tr, doc3 = _a.doc;
      if (start && end) {
        var _b = getMdToEditorPos(doc3, start, end), from2 = _b[0], to = _b[1];
        newTr = tr.deleteRange(from2, to);
      } else {
        newTr = tr.deleteSelection();
      }
      this.view.dispatch(newTr.scrollIntoView());
    };
    MdEditor2.prototype.getSelectedText = function(start, end) {
      var _a = this.view.state, doc3 = _a.doc, selection = _a.selection;
      var from2 = selection.from, to = selection.to;
      if (start && end) {
        var pos = getMdToEditorPos(doc3, start, end);
        from2 = pos[0];
        to = pos[1];
      }
      return doc3.textBetween(from2, to, "\n");
    };
    MdEditor2.prototype.getSelection = function() {
      var _a = this.view.state.selection, from2 = _a.from, to = _a.to;
      return getEditorToMdPos(this.view.state.tr.doc, from2, to);
    };
    MdEditor2.prototype.setMarkdown = function(markdown, cursorToEnd) {
      if (cursorToEnd === void 0) {
        cursorToEnd = true;
      }
      var lineTexts = markdown.split(reLineEnding$2);
      var _a = this.view.state, tr = _a.tr, doc3 = _a.doc, schema = _a.schema;
      var nodes = lineTexts.map(function(lineText) {
        return createParagraph(schema, createNodesWithWidget(lineText, schema));
      });
      this.view.dispatch(tr.replaceWith(0, doc3.content.size, nodes));
      if (cursorToEnd) {
        this.moveCursorToEnd(true);
      }
    };
    MdEditor2.prototype.addWidget = function(node, style, mdPos) {
      var _a = this.view.state, tr = _a.tr, doc3 = _a.doc, selection = _a.selection;
      var pos = mdPos ? getMdToEditorPos(doc3, mdPos, mdPos)[0] : selection.to;
      this.view.dispatch(tr.setMeta("widget", { pos, node, style }));
    };
    MdEditor2.prototype.replaceWithWidget = function(start, end, text2) {
      var _a = this.view.state, tr = _a.tr, schema = _a.schema, doc3 = _a.doc;
      var pos = getMdToEditorPos(doc3, start, end);
      var nodes = createNodesWithWidget(text2, schema);
      this.view.dispatch(tr.replaceWith(pos[0], pos[1], nodes));
    };
    MdEditor2.prototype.getRangeInfoOfNode = function(pos) {
      var _a = this.view.state, doc3 = _a.doc, selection = _a.selection;
      var mdPos = pos || getEditorToMdPos(doc3, selection.from)[0];
      var mdNode = this.toastMark.findNodeAtPosition(mdPos);
      if (mdNode.type === "text" && mdNode.parent.type !== "paragraph") {
        mdNode = mdNode.parent;
      }
      mdNode.sourcepos[1][1] += 1;
      return { range: mdNode.sourcepos, type: mdNode.type };
    };
    MdEditor2.prototype.getMarkdown = function() {
      return this.toastMark.getLineTexts().map(function(lineText) {
        return unwrapWidgetSyntax(lineText);
      }).join("\n");
    };
    MdEditor2.prototype.getToastMark = function() {
      return this.toastMark;
    };
    return MdEditor2;
  })(EditorBase)
);
var EVENT_KEY = "_feEventKey";
function safeEvent$2(element, type) {
  var events = element[EVENT_KEY];
  var handlers2;
  if (!events) {
    events = element[EVENT_KEY] = {};
  }
  handlers2 = events[type];
  if (!handlers2) {
    handlers2 = events[type] = [];
  }
  return handlers2;
}
var _safeEvent = safeEvent$2;
var isString$1 = isString_1;
var forEach$1 = forEach_1;
var safeEvent$1 = _safeEvent;
function off(element, types, handler) {
  if (isString$1(types)) {
    forEach$1(types.split(/\s+/g), function(type) {
      unbindEvent(element, type, handler);
    });
    return;
  }
  forEach$1(types, function(func, type) {
    unbindEvent(element, type, func);
  });
}
function unbindEvent(element, type, handler) {
  var events = safeEvent$1(element, type);
  var index2;
  if (!handler) {
    forEach$1(events, function(item2) {
      removeHandler(element, type, item2.wrappedHandler);
    });
    events.splice(0, events.length);
  } else {
    forEach$1(events, function(item2, idx) {
      if (handler === item2.handler) {
        removeHandler(element, type, item2.wrappedHandler);
        index2 = idx;
        return false;
      }
      return true;
    });
    events.splice(index2, 1);
  }
}
function removeHandler(element, type, handler) {
  if ("removeEventListener" in element) {
    element.removeEventListener(type, handler);
  } else if ("detachEvent" in element) {
    element.detachEvent("on" + type, handler);
  }
}
var off_1 = off;
var isString = isString_1;
var forEach2 = forEach_1;
var safeEvent = _safeEvent;
function on(element, types, handler, context) {
  if (isString(types)) {
    forEach2(types.split(/\s+/g), function(type) {
      bindEvent(element, type, handler, context);
    });
    return;
  }
  forEach2(types, function(func, type) {
    bindEvent(element, type, func, handler);
  });
}
function bindEvent(element, type, handler, context) {
  function eventHandler(e) {
    handler.call(context || element, e || window.event);
  }
  if ("addEventListener" in element) {
    element.addEventListener(type, eventHandler);
  } else if ("attachEvent" in element) {
    element.attachEvent("on" + type, eventHandler);
  }
  memorizeHandler(element, type, handler, eventHandler);
}
function memorizeHandler(element, type, handler, wrappedHandler) {
  var events = safeEvent(element, type);
  var existInEvents = false;
  forEach2(events, function(obj) {
    if (obj.handler === handler) {
      existInEvents = true;
      return false;
    }
    return true;
  });
  if (!existInEvents) {
    events.push({
      handler,
      wrappedHandler
    });
  }
}
var on_1 = on;
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
  __assign = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
function __spreadArray(to, from2, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from2.length, ar; i < l; i++) {
    if (ar || !(i in from2)) {
      if (!ar) ar = Array.prototype.slice.call(from2, 0, i);
      ar[i] = from2[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from2));
}
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var encodeCache = {};
function getEncodeCache(exclude) {
  var i, ch, cache2 = encodeCache[exclude];
  if (cache2) {
    return cache2;
  }
  cache2 = encodeCache[exclude] = [];
  for (i = 0; i < 128; i++) {
    ch = String.fromCharCode(i);
    if (/^[0-9a-z]$/i.test(ch)) {
      cache2.push(ch);
    } else {
      cache2.push("%" + ("0" + i.toString(16).toUpperCase()).slice(-2));
    }
  }
  for (i = 0; i < exclude.length; i++) {
    cache2[exclude.charCodeAt(i)] = exclude[i];
  }
  return cache2;
}
function encode$1(string, exclude, keepEscaped) {
  var i, l, code2, nextCode, cache2, result = "";
  if (typeof exclude !== "string") {
    keepEscaped = exclude;
    exclude = encode$1.defaultChars;
  }
  if (typeof keepEscaped === "undefined") {
    keepEscaped = true;
  }
  cache2 = getEncodeCache(exclude);
  for (i = 0, l = string.length; i < l; i++) {
    code2 = string.charCodeAt(i);
    if (keepEscaped && code2 === 37 && i + 2 < l) {
      if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) {
        result += string.slice(i, i + 3);
        i += 2;
        continue;
      }
    }
    if (code2 < 128) {
      result += cache2[code2];
      continue;
    }
    if (code2 >= 55296 && code2 <= 57343) {
      if (code2 >= 55296 && code2 <= 56319 && i + 1 < l) {
        nextCode = string.charCodeAt(i + 1);
        if (nextCode >= 56320 && nextCode <= 57343) {
          result += encodeURIComponent(string[i] + string[i + 1]);
          i++;
          continue;
        }
      }
      result += "%EF%BF%BD";
      continue;
    }
    result += encodeURIComponent(string[i]);
  }
  return result;
}
encode$1.defaultChars = ";/?:@&=+$,-_.!~*'()#";
encode$1.componentChars = "-_.!~*'()";
var encode_1 = encode$1;
var lib = {};
var decode = {};
var Aacute$1 = "\xC1";
var aacute$1 = "\xE1";
var Abreve = "\u0102";
var abreve = "\u0103";
var ac = "\u223E";
var acd = "\u223F";
var acE = "\u223E\u0333";
var Acirc$1 = "\xC2";
var acirc$1 = "\xE2";
var acute$1 = "\xB4";
var Acy = "\u0410";
var acy = "\u0430";
var AElig$1 = "\xC6";
var aelig$1 = "\xE6";
var af = "\u2061";
var Afr = "\u{1D504}";
var afr = "\u{1D51E}";
var Agrave$1 = "\xC0";
var agrave$1 = "\xE0";
var alefsym = "\u2135";
var aleph = "\u2135";
var Alpha = "\u0391";
var alpha = "\u03B1";
var Amacr = "\u0100";
var amacr = "\u0101";
var amalg = "\u2A3F";
var amp$2 = "&";
var AMP$1 = "&";
var andand = "\u2A55";
var And = "\u2A53";
var and = "\u2227";
var andd = "\u2A5C";
var andslope = "\u2A58";
var andv = "\u2A5A";
var ang = "\u2220";
var ange = "\u29A4";
var angle = "\u2220";
var angmsdaa = "\u29A8";
var angmsdab = "\u29A9";
var angmsdac = "\u29AA";
var angmsdad = "\u29AB";
var angmsdae = "\u29AC";
var angmsdaf = "\u29AD";
var angmsdag = "\u29AE";
var angmsdah = "\u29AF";
var angmsd = "\u2221";
var angrt = "\u221F";
var angrtvb = "\u22BE";
var angrtvbd = "\u299D";
var angsph = "\u2222";
var angst = "\xC5";
var angzarr = "\u237C";
var Aogon = "\u0104";
var aogon = "\u0105";
var Aopf = "\u{1D538}";
var aopf = "\u{1D552}";
var apacir = "\u2A6F";
var ap = "\u2248";
var apE = "\u2A70";
var ape = "\u224A";
var apid = "\u224B";
var apos$1 = "'";
var ApplyFunction = "\u2061";
var approx = "\u2248";
var approxeq = "\u224A";
var Aring$1 = "\xC5";
var aring$1 = "\xE5";
var Ascr = "\u{1D49C}";
var ascr = "\u{1D4B6}";
var Assign = "\u2254";
var ast = "*";
var asymp = "\u2248";
var asympeq = "\u224D";
var Atilde$1 = "\xC3";
var atilde$1 = "\xE3";
var Auml$1 = "\xC4";
var auml$1 = "\xE4";
var awconint = "\u2233";
var awint = "\u2A11";
var backcong = "\u224C";
var backepsilon = "\u03F6";
var backprime = "\u2035";
var backsim = "\u223D";
var backsimeq = "\u22CD";
var Backslash = "\u2216";
var Barv = "\u2AE7";
var barvee = "\u22BD";
var barwed = "\u2305";
var Barwed = "\u2306";
var barwedge = "\u2305";
var bbrk = "\u23B5";
var bbrktbrk = "\u23B6";
var bcong = "\u224C";
var Bcy = "\u0411";
var bcy = "\u0431";
var bdquo = "\u201E";
var becaus = "\u2235";
var because = "\u2235";
var Because = "\u2235";
var bemptyv = "\u29B0";
var bepsi = "\u03F6";
var bernou = "\u212C";
var Bernoullis = "\u212C";
var Beta = "\u0392";
var beta = "\u03B2";
var beth = "\u2136";
var between = "\u226C";
var Bfr = "\u{1D505}";
var bfr = "\u{1D51F}";
var bigcap = "\u22C2";
var bigcirc = "\u25EF";
var bigcup = "\u22C3";
var bigodot = "\u2A00";
var bigoplus = "\u2A01";
var bigotimes = "\u2A02";
var bigsqcup = "\u2A06";
var bigstar = "\u2605";
var bigtriangledown = "\u25BD";
var bigtriangleup = "\u25B3";
var biguplus = "\u2A04";
var bigvee = "\u22C1";
var bigwedge = "\u22C0";
var bkarow = "\u290D";
var blacklozenge = "\u29EB";
var blacksquare = "\u25AA";
var blacktriangle = "\u25B4";
var blacktriangledown = "\u25BE";
var blacktriangleleft = "\u25C2";
var blacktriangleright = "\u25B8";
var blank = "\u2423";
var blk12 = "\u2592";
var blk14 = "\u2591";
var blk34 = "\u2593";
var block = "\u2588";
var bne = "=\u20E5";
var bnequiv = "\u2261\u20E5";
var bNot = "\u2AED";
var bnot = "\u2310";
var Bopf = "\u{1D539}";
var bopf = "\u{1D553}";
var bot = "\u22A5";
var bottom = "\u22A5";
var bowtie = "\u22C8";
var boxbox = "\u29C9";
var boxdl = "\u2510";
var boxdL = "\u2555";
var boxDl = "\u2556";
var boxDL = "\u2557";
var boxdr = "\u250C";
var boxdR = "\u2552";
var boxDr = "\u2553";
var boxDR = "\u2554";
var boxh = "\u2500";
var boxH = "\u2550";
var boxhd = "\u252C";
var boxHd = "\u2564";
var boxhD = "\u2565";
var boxHD = "\u2566";
var boxhu = "\u2534";
var boxHu = "\u2567";
var boxhU = "\u2568";
var boxHU = "\u2569";
var boxminus = "\u229F";
var boxplus = "\u229E";
var boxtimes = "\u22A0";
var boxul = "\u2518";
var boxuL = "\u255B";
var boxUl = "\u255C";
var boxUL = "\u255D";
var boxur = "\u2514";
var boxuR = "\u2558";
var boxUr = "\u2559";
var boxUR = "\u255A";
var boxv = "\u2502";
var boxV = "\u2551";
var boxvh = "\u253C";
var boxvH = "\u256A";
var boxVh = "\u256B";
var boxVH = "\u256C";
var boxvl = "\u2524";
var boxvL = "\u2561";
var boxVl = "\u2562";
var boxVL = "\u2563";
var boxvr = "\u251C";
var boxvR = "\u255E";
var boxVr = "\u255F";
var boxVR = "\u2560";
var bprime = "\u2035";
var breve = "\u02D8";
var Breve = "\u02D8";
var brvbar$1 = "\xA6";
var bscr = "\u{1D4B7}";
var Bscr = "\u212C";
var bsemi = "\u204F";
var bsim = "\u223D";
var bsime = "\u22CD";
var bsolb = "\u29C5";
var bsol = "\\";
var bsolhsub = "\u27C8";
var bull = "\u2022";
var bullet = "\u2022";
var bump = "\u224E";
var bumpE = "\u2AAE";
var bumpe = "\u224F";
var Bumpeq = "\u224E";
var bumpeq = "\u224F";
var Cacute = "\u0106";
var cacute = "\u0107";
var capand = "\u2A44";
var capbrcup = "\u2A49";
var capcap = "\u2A4B";
var cap = "\u2229";
var Cap = "\u22D2";
var capcup = "\u2A47";
var capdot = "\u2A40";
var CapitalDifferentialD = "\u2145";
var caps = "\u2229\uFE00";
var caret = "\u2041";
var caron = "\u02C7";
var Cayleys = "\u212D";
var ccaps = "\u2A4D";
var Ccaron = "\u010C";
var ccaron = "\u010D";
var Ccedil$1 = "\xC7";
var ccedil$1 = "\xE7";
var Ccirc = "\u0108";
var ccirc = "\u0109";
var Cconint = "\u2230";
var ccups = "\u2A4C";
var ccupssm = "\u2A50";
var Cdot = "\u010A";
var cdot = "\u010B";
var cedil$1 = "\xB8";
var Cedilla = "\xB8";
var cemptyv = "\u29B2";
var cent$1 = "\xA2";
var centerdot = "\xB7";
var CenterDot = "\xB7";
var cfr = "\u{1D520}";
var Cfr = "\u212D";
var CHcy = "\u0427";
var chcy = "\u0447";
var check = "\u2713";
var checkmark = "\u2713";
var Chi = "\u03A7";
var chi = "\u03C7";
var circ = "\u02C6";
var circeq = "\u2257";
var circlearrowleft = "\u21BA";
var circlearrowright = "\u21BB";
var circledast = "\u229B";
var circledcirc = "\u229A";
var circleddash = "\u229D";
var CircleDot = "\u2299";
var circledR = "\xAE";
var circledS = "\u24C8";
var CircleMinus = "\u2296";
var CirclePlus = "\u2295";
var CircleTimes = "\u2297";
var cir = "\u25CB";
var cirE = "\u29C3";
var cire = "\u2257";
var cirfnint = "\u2A10";
var cirmid = "\u2AEF";
var cirscir = "\u29C2";
var ClockwiseContourIntegral = "\u2232";
var CloseCurlyDoubleQuote = "\u201D";
var CloseCurlyQuote = "\u2019";
var clubs = "\u2663";
var clubsuit = "\u2663";
var colon = ":";
var Colon = "\u2237";
var Colone = "\u2A74";
var colone = "\u2254";
var coloneq = "\u2254";
var comma = ",";
var commat = "@";
var comp = "\u2201";
var compfn = "\u2218";
var complement = "\u2201";
var complexes = "\u2102";
var cong = "\u2245";
var congdot = "\u2A6D";
var Congruent = "\u2261";
var conint = "\u222E";
var Conint = "\u222F";
var ContourIntegral = "\u222E";
var copf = "\u{1D554}";
var Copf = "\u2102";
var coprod = "\u2210";
var Coproduct = "\u2210";
var copy$1 = "\xA9";
var COPY$1 = "\xA9";
var copysr = "\u2117";
var CounterClockwiseContourIntegral = "\u2233";
var crarr = "\u21B5";
var cross = "\u2717";
var Cross = "\u2A2F";
var Cscr = "\u{1D49E}";
var cscr = "\u{1D4B8}";
var csub = "\u2ACF";
var csube = "\u2AD1";
var csup = "\u2AD0";
var csupe = "\u2AD2";
var ctdot = "\u22EF";
var cudarrl = "\u2938";
var cudarrr = "\u2935";
var cuepr = "\u22DE";
var cuesc = "\u22DF";
var cularr = "\u21B6";
var cularrp = "\u293D";
var cupbrcap = "\u2A48";
var cupcap = "\u2A46";
var CupCap = "\u224D";
var cup = "\u222A";
var Cup = "\u22D3";
var cupcup = "\u2A4A";
var cupdot = "\u228D";
var cupor = "\u2A45";
var cups = "\u222A\uFE00";
var curarr = "\u21B7";
var curarrm = "\u293C";
var curlyeqprec = "\u22DE";
var curlyeqsucc = "\u22DF";
var curlyvee = "\u22CE";
var curlywedge = "\u22CF";
var curren$1 = "\xA4";
var curvearrowleft = "\u21B6";
var curvearrowright = "\u21B7";
var cuvee = "\u22CE";
var cuwed = "\u22CF";
var cwconint = "\u2232";
var cwint = "\u2231";
var cylcty = "\u232D";
var dagger = "\u2020";
var Dagger = "\u2021";
var daleth = "\u2138";
var darr = "\u2193";
var Darr = "\u21A1";
var dArr = "\u21D3";
var dash = "\u2010";
var Dashv = "\u2AE4";
var dashv = "\u22A3";
var dbkarow = "\u290F";
var dblac = "\u02DD";
var Dcaron = "\u010E";
var dcaron = "\u010F";
var Dcy = "\u0414";
var dcy = "\u0434";
var ddagger = "\u2021";
var ddarr = "\u21CA";
var DD = "\u2145";
var dd = "\u2146";
var DDotrahd = "\u2911";
var ddotseq = "\u2A77";
var deg$1 = "\xB0";
var Del = "\u2207";
var Delta = "\u0394";
var delta = "\u03B4";
var demptyv = "\u29B1";
var dfisht = "\u297F";
var Dfr = "\u{1D507}";
var dfr = "\u{1D521}";
var dHar = "\u2965";
var dharl = "\u21C3";
var dharr = "\u21C2";
var DiacriticalAcute = "\xB4";
var DiacriticalDot = "\u02D9";
var DiacriticalDoubleAcute = "\u02DD";
var DiacriticalGrave = "`";
var DiacriticalTilde = "\u02DC";
var diam = "\u22C4";
var diamond = "\u22C4";
var Diamond = "\u22C4";
var diamondsuit = "\u2666";
var diams = "\u2666";
var die = "\xA8";
var DifferentialD = "\u2146";
var digamma = "\u03DD";
var disin = "\u22F2";
var div = "\xF7";
var divide$1 = "\xF7";
var divideontimes = "\u22C7";
var divonx = "\u22C7";
var DJcy = "\u0402";
var djcy = "\u0452";
var dlcorn = "\u231E";
var dlcrop = "\u230D";
var dollar = "$";
var Dopf = "\u{1D53B}";
var dopf = "\u{1D555}";
var Dot = "\xA8";
var dot = "\u02D9";
var DotDot = "\u20DC";
var doteq = "\u2250";
var doteqdot = "\u2251";
var DotEqual = "\u2250";
var dotminus = "\u2238";
var dotplus = "\u2214";
var dotsquare = "\u22A1";
var doublebarwedge = "\u2306";
var DoubleContourIntegral = "\u222F";
var DoubleDot = "\xA8";
var DoubleDownArrow = "\u21D3";
var DoubleLeftArrow = "\u21D0";
var DoubleLeftRightArrow = "\u21D4";
var DoubleLeftTee = "\u2AE4";
var DoubleLongLeftArrow = "\u27F8";
var DoubleLongLeftRightArrow = "\u27FA";
var DoubleLongRightArrow = "\u27F9";
var DoubleRightArrow = "\u21D2";
var DoubleRightTee = "\u22A8";
var DoubleUpArrow = "\u21D1";
var DoubleUpDownArrow = "\u21D5";
var DoubleVerticalBar = "\u2225";
var DownArrowBar = "\u2913";
var downarrow = "\u2193";
var DownArrow = "\u2193";
var Downarrow = "\u21D3";
var DownArrowUpArrow = "\u21F5";
var DownBreve = "\u0311";
var downdownarrows = "\u21CA";
var downharpoonleft = "\u21C3";
var downharpoonright = "\u21C2";
var DownLeftRightVector = "\u2950";
var DownLeftTeeVector = "\u295E";
var DownLeftVectorBar = "\u2956";
var DownLeftVector = "\u21BD";
var DownRightTeeVector = "\u295F";
var DownRightVectorBar = "\u2957";
var DownRightVector = "\u21C1";
var DownTeeArrow = "\u21A7";
var DownTee = "\u22A4";
var drbkarow = "\u2910";
var drcorn = "\u231F";
var drcrop = "\u230C";
var Dscr = "\u{1D49F}";
var dscr = "\u{1D4B9}";
var DScy = "\u0405";
var dscy = "\u0455";
var dsol = "\u29F6";
var Dstrok = "\u0110";
var dstrok = "\u0111";
var dtdot = "\u22F1";
var dtri = "\u25BF";
var dtrif = "\u25BE";
var duarr = "\u21F5";
var duhar = "\u296F";
var dwangle = "\u29A6";
var DZcy = "\u040F";
var dzcy = "\u045F";
var dzigrarr = "\u27FF";
var Eacute$1 = "\xC9";
var eacute$1 = "\xE9";
var easter = "\u2A6E";
var Ecaron = "\u011A";
var ecaron = "\u011B";
var Ecirc$1 = "\xCA";
var ecirc$1 = "\xEA";
var ecir = "\u2256";
var ecolon = "\u2255";
var Ecy = "\u042D";
var ecy = "\u044D";
var eDDot = "\u2A77";
var Edot = "\u0116";
var edot = "\u0117";
var eDot = "\u2251";
var ee = "\u2147";
var efDot = "\u2252";
var Efr = "\u{1D508}";
var efr = "\u{1D522}";
var eg = "\u2A9A";
var Egrave$1 = "\xC8";
var egrave$1 = "\xE8";
var egs = "\u2A96";
var egsdot = "\u2A98";
var el = "\u2A99";
var Element$1 = "\u2208";
var elinters = "\u23E7";
var ell = "\u2113";
var els = "\u2A95";
var elsdot = "\u2A97";
var Emacr = "\u0112";
var emacr = "\u0113";
var empty2 = "\u2205";
var emptyset = "\u2205";
var EmptySmallSquare = "\u25FB";
var emptyv = "\u2205";
var EmptyVerySmallSquare = "\u25AB";
var emsp13 = "\u2004";
var emsp14 = "\u2005";
var emsp = "\u2003";
var ENG = "\u014A";
var eng = "\u014B";
var ensp = "\u2002";
var Eogon = "\u0118";
var eogon = "\u0119";
var Eopf = "\u{1D53C}";
var eopf = "\u{1D556}";
var epar = "\u22D5";
var eparsl = "\u29E3";
var eplus = "\u2A71";
var epsi = "\u03B5";
var Epsilon = "\u0395";
var epsilon = "\u03B5";
var epsiv = "\u03F5";
var eqcirc = "\u2256";
var eqcolon = "\u2255";
var eqsim = "\u2242";
var eqslantgtr = "\u2A96";
var eqslantless = "\u2A95";
var Equal = "\u2A75";
var equals = "=";
var EqualTilde = "\u2242";
var equest = "\u225F";
var Equilibrium = "\u21CC";
var equiv = "\u2261";
var equivDD = "\u2A78";
var eqvparsl = "\u29E5";
var erarr = "\u2971";
var erDot = "\u2253";
var escr = "\u212F";
var Escr = "\u2130";
var esdot = "\u2250";
var Esim = "\u2A73";
var esim = "\u2242";
var Eta = "\u0397";
var eta = "\u03B7";
var ETH$1 = "\xD0";
var eth$1 = "\xF0";
var Euml$1 = "\xCB";
var euml$1 = "\xEB";
var euro = "\u20AC";
var excl = "!";
var exist = "\u2203";
var Exists = "\u2203";
var expectation = "\u2130";
var exponentiale = "\u2147";
var ExponentialE = "\u2147";
var fallingdotseq = "\u2252";
var Fcy = "\u0424";
var fcy = "\u0444";
var female = "\u2640";
var ffilig = "\uFB03";
var fflig = "\uFB00";
var ffllig = "\uFB04";
var Ffr = "\u{1D509}";
var ffr = "\u{1D523}";
var filig = "\uFB01";
var FilledSmallSquare = "\u25FC";
var FilledVerySmallSquare = "\u25AA";
var fjlig = "fj";
var flat = "\u266D";
var fllig = "\uFB02";
var fltns = "\u25B1";
var fnof = "\u0192";
var Fopf = "\u{1D53D}";
var fopf = "\u{1D557}";
var forall = "\u2200";
var ForAll = "\u2200";
var fork = "\u22D4";
var forkv = "\u2AD9";
var Fouriertrf = "\u2131";
var fpartint = "\u2A0D";
var frac12$1 = "\xBD";
var frac13 = "\u2153";
var frac14$1 = "\xBC";
var frac15 = "\u2155";
var frac16 = "\u2159";
var frac18 = "\u215B";
var frac23 = "\u2154";
var frac25 = "\u2156";
var frac34$1 = "\xBE";
var frac35 = "\u2157";
var frac38 = "\u215C";
var frac45 = "\u2158";
var frac56 = "\u215A";
var frac58 = "\u215D";
var frac78 = "\u215E";
var frasl = "\u2044";
var frown = "\u2322";
var fscr = "\u{1D4BB}";
var Fscr = "\u2131";
var gacute = "\u01F5";
var Gamma = "\u0393";
var gamma = "\u03B3";
var Gammad = "\u03DC";
var gammad = "\u03DD";
var gap = "\u2A86";
var Gbreve = "\u011E";
var gbreve = "\u011F";
var Gcedil = "\u0122";
var Gcirc = "\u011C";
var gcirc = "\u011D";
var Gcy = "\u0413";
var gcy = "\u0433";
var Gdot = "\u0120";
var gdot = "\u0121";
var ge = "\u2265";
var gE = "\u2267";
var gEl = "\u2A8C";
var gel = "\u22DB";
var geq = "\u2265";
var geqq = "\u2267";
var geqslant = "\u2A7E";
var gescc = "\u2AA9";
var ges = "\u2A7E";
var gesdot = "\u2A80";
var gesdoto = "\u2A82";
var gesdotol = "\u2A84";
var gesl = "\u22DB\uFE00";
var gesles = "\u2A94";
var Gfr = "\u{1D50A}";
var gfr = "\u{1D524}";
var gg = "\u226B";
var Gg = "\u22D9";
var ggg = "\u22D9";
var gimel = "\u2137";
var GJcy = "\u0403";
var gjcy = "\u0453";
var gla = "\u2AA5";
var gl = "\u2277";
var glE = "\u2A92";
var glj = "\u2AA4";
var gnap = "\u2A8A";
var gnapprox = "\u2A8A";
var gne = "\u2A88";
var gnE = "\u2269";
var gneq = "\u2A88";
var gneqq = "\u2269";
var gnsim = "\u22E7";
var Gopf = "\u{1D53E}";
var gopf = "\u{1D558}";
var grave = "`";
var GreaterEqual = "\u2265";
var GreaterEqualLess = "\u22DB";
var GreaterFullEqual = "\u2267";
var GreaterGreater = "\u2AA2";
var GreaterLess = "\u2277";
var GreaterSlantEqual = "\u2A7E";
var GreaterTilde = "\u2273";
var Gscr = "\u{1D4A2}";
var gscr = "\u210A";
var gsim = "\u2273";
var gsime = "\u2A8E";
var gsiml = "\u2A90";
var gtcc = "\u2AA7";
var gtcir = "\u2A7A";
var gt$2 = ">";
var GT$1 = ">";
var Gt = "\u226B";
var gtdot = "\u22D7";
var gtlPar = "\u2995";
var gtquest = "\u2A7C";
var gtrapprox = "\u2A86";
var gtrarr = "\u2978";
var gtrdot = "\u22D7";
var gtreqless = "\u22DB";
var gtreqqless = "\u2A8C";
var gtrless = "\u2277";
var gtrsim = "\u2273";
var gvertneqq = "\u2269\uFE00";
var gvnE = "\u2269\uFE00";
var Hacek = "\u02C7";
var hairsp = "\u200A";
var half = "\xBD";
var hamilt = "\u210B";
var HARDcy = "\u042A";
var hardcy = "\u044A";
var harrcir = "\u2948";
var harr = "\u2194";
var hArr = "\u21D4";
var harrw = "\u21AD";
var Hat = "^";
var hbar = "\u210F";
var Hcirc = "\u0124";
var hcirc = "\u0125";
var hearts = "\u2665";
var heartsuit = "\u2665";
var hellip = "\u2026";
var hercon = "\u22B9";
var hfr = "\u{1D525}";
var Hfr = "\u210C";
var HilbertSpace = "\u210B";
var hksearow = "\u2925";
var hkswarow = "\u2926";
var hoarr = "\u21FF";
var homtht = "\u223B";
var hookleftarrow = "\u21A9";
var hookrightarrow = "\u21AA";
var hopf = "\u{1D559}";
var Hopf = "\u210D";
var horbar = "\u2015";
var HorizontalLine = "\u2500";
var hscr = "\u{1D4BD}";
var Hscr = "\u210B";
var hslash = "\u210F";
var Hstrok = "\u0126";
var hstrok = "\u0127";
var HumpDownHump = "\u224E";
var HumpEqual = "\u224F";
var hybull = "\u2043";
var hyphen = "\u2010";
var Iacute$1 = "\xCD";
var iacute$1 = "\xED";
var ic = "\u2063";
var Icirc$1 = "\xCE";
var icirc$1 = "\xEE";
var Icy = "\u0418";
var icy = "\u0438";
var Idot = "\u0130";
var IEcy = "\u0415";
var iecy = "\u0435";
var iexcl$1 = "\xA1";
var iff = "\u21D4";
var ifr = "\u{1D526}";
var Ifr = "\u2111";
var Igrave$1 = "\xCC";
var igrave$1 = "\xEC";
var ii = "\u2148";
var iiiint = "\u2A0C";
var iiint = "\u222D";
var iinfin = "\u29DC";
var iiota = "\u2129";
var IJlig = "\u0132";
var ijlig = "\u0133";
var Imacr = "\u012A";
var imacr = "\u012B";
var image = "\u2111";
var ImaginaryI = "\u2148";
var imagline = "\u2110";
var imagpart = "\u2111";
var imath = "\u0131";
var Im = "\u2111";
var imof = "\u22B7";
var imped = "\u01B5";
var Implies = "\u21D2";
var incare = "\u2105";
var infin = "\u221E";
var infintie = "\u29DD";
var inodot = "\u0131";
var intcal = "\u22BA";
var int = "\u222B";
var Int = "\u222C";
var integers = "\u2124";
var Integral = "\u222B";
var intercal = "\u22BA";
var Intersection = "\u22C2";
var intlarhk = "\u2A17";
var intprod = "\u2A3C";
var InvisibleComma = "\u2063";
var InvisibleTimes = "\u2062";
var IOcy = "\u0401";
var iocy = "\u0451";
var Iogon = "\u012E";
var iogon = "\u012F";
var Iopf = "\u{1D540}";
var iopf = "\u{1D55A}";
var Iota = "\u0399";
var iota = "\u03B9";
var iprod = "\u2A3C";
var iquest$1 = "\xBF";
var iscr = "\u{1D4BE}";
var Iscr = "\u2110";
var isin = "\u2208";
var isindot = "\u22F5";
var isinE = "\u22F9";
var isins = "\u22F4";
var isinsv = "\u22F3";
var isinv = "\u2208";
var it = "\u2062";
var Itilde = "\u0128";
var itilde = "\u0129";
var Iukcy = "\u0406";
var iukcy = "\u0456";
var Iuml$1 = "\xCF";
var iuml$1 = "\xEF";
var Jcirc = "\u0134";
var jcirc = "\u0135";
var Jcy = "\u0419";
var jcy = "\u0439";
var Jfr = "\u{1D50D}";
var jfr = "\u{1D527}";
var jmath = "\u0237";
var Jopf = "\u{1D541}";
var jopf = "\u{1D55B}";
var Jscr = "\u{1D4A5}";
var jscr = "\u{1D4BF}";
var Jsercy = "\u0408";
var jsercy = "\u0458";
var Jukcy = "\u0404";
var jukcy = "\u0454";
var Kappa = "\u039A";
var kappa = "\u03BA";
var kappav = "\u03F0";
var Kcedil = "\u0136";
var kcedil = "\u0137";
var Kcy = "\u041A";
var kcy = "\u043A";
var Kfr = "\u{1D50E}";
var kfr = "\u{1D528}";
var kgreen = "\u0138";
var KHcy = "\u0425";
var khcy = "\u0445";
var KJcy = "\u040C";
var kjcy = "\u045C";
var Kopf = "\u{1D542}";
var kopf = "\u{1D55C}";
var Kscr = "\u{1D4A6}";
var kscr = "\u{1D4C0}";
var lAarr = "\u21DA";
var Lacute = "\u0139";
var lacute = "\u013A";
var laemptyv = "\u29B4";
var lagran = "\u2112";
var Lambda = "\u039B";
var lambda = "\u03BB";
var lang = "\u27E8";
var Lang = "\u27EA";
var langd = "\u2991";
var langle = "\u27E8";
var lap = "\u2A85";
var Laplacetrf = "\u2112";
var laquo$1 = "\xAB";
var larrb = "\u21E4";
var larrbfs = "\u291F";
var larr = "\u2190";
var Larr = "\u219E";
var lArr = "\u21D0";
var larrfs = "\u291D";
var larrhk = "\u21A9";
var larrlp = "\u21AB";
var larrpl = "\u2939";
var larrsim = "\u2973";
var larrtl = "\u21A2";
var latail = "\u2919";
var lAtail = "\u291B";
var lat = "\u2AAB";
var late = "\u2AAD";
var lates = "\u2AAD\uFE00";
var lbarr = "\u290C";
var lBarr = "\u290E";
var lbbrk = "\u2772";
var lbrace = "{";
var lbrack = "[";
var lbrke = "\u298B";
var lbrksld = "\u298F";
var lbrkslu = "\u298D";
var Lcaron = "\u013D";
var lcaron = "\u013E";
var Lcedil = "\u013B";
var lcedil = "\u013C";
var lceil = "\u2308";
var lcub = "{";
var Lcy = "\u041B";
var lcy = "\u043B";
var ldca = "\u2936";
var ldquo = "\u201C";
var ldquor = "\u201E";
var ldrdhar = "\u2967";
var ldrushar = "\u294B";
var ldsh = "\u21B2";
var le = "\u2264";
var lE = "\u2266";
var LeftAngleBracket = "\u27E8";
var LeftArrowBar = "\u21E4";
var leftarrow = "\u2190";
var LeftArrow = "\u2190";
var Leftarrow = "\u21D0";
var LeftArrowRightArrow = "\u21C6";
var leftarrowtail = "\u21A2";
var LeftCeiling = "\u2308";
var LeftDoubleBracket = "\u27E6";
var LeftDownTeeVector = "\u2961";
var LeftDownVectorBar = "\u2959";
var LeftDownVector = "\u21C3";
var LeftFloor = "\u230A";
var leftharpoondown = "\u21BD";
var leftharpoonup = "\u21BC";
var leftleftarrows = "\u21C7";
var leftrightarrow = "\u2194";
var LeftRightArrow = "\u2194";
var Leftrightarrow = "\u21D4";
var leftrightarrows = "\u21C6";
var leftrightharpoons = "\u21CB";
var leftrightsquigarrow = "\u21AD";
var LeftRightVector = "\u294E";
var LeftTeeArrow = "\u21A4";
var LeftTee = "\u22A3";
var LeftTeeVector = "\u295A";
var leftthreetimes = "\u22CB";
var LeftTriangleBar = "\u29CF";
var LeftTriangle = "\u22B2";
var LeftTriangleEqual = "\u22B4";
var LeftUpDownVector = "\u2951";
var LeftUpTeeVector = "\u2960";
var LeftUpVectorBar = "\u2958";
var LeftUpVector = "\u21BF";
var LeftVectorBar = "\u2952";
var LeftVector = "\u21BC";
var lEg = "\u2A8B";
var leg = "\u22DA";
var leq = "\u2264";
var leqq = "\u2266";
var leqslant = "\u2A7D";
var lescc = "\u2AA8";
var les = "\u2A7D";
var lesdot = "\u2A7F";
var lesdoto = "\u2A81";
var lesdotor = "\u2A83";
var lesg = "\u22DA\uFE00";
var lesges = "\u2A93";
var lessapprox = "\u2A85";
var lessdot = "\u22D6";
var lesseqgtr = "\u22DA";
var lesseqqgtr = "\u2A8B";
var LessEqualGreater = "\u22DA";
var LessFullEqual = "\u2266";
var LessGreater = "\u2276";
var lessgtr = "\u2276";
var LessLess = "\u2AA1";
var lesssim = "\u2272";
var LessSlantEqual = "\u2A7D";
var LessTilde = "\u2272";
var lfisht = "\u297C";
var lfloor = "\u230A";
var Lfr = "\u{1D50F}";
var lfr = "\u{1D529}";
var lg = "\u2276";
var lgE = "\u2A91";
var lHar = "\u2962";
var lhard = "\u21BD";
var lharu = "\u21BC";
var lharul = "\u296A";
var lhblk = "\u2584";
var LJcy = "\u0409";
var ljcy = "\u0459";
var llarr = "\u21C7";
var ll = "\u226A";
var Ll = "\u22D8";
var llcorner = "\u231E";
var Lleftarrow = "\u21DA";
var llhard = "\u296B";
var lltri = "\u25FA";
var Lmidot = "\u013F";
var lmidot = "\u0140";
var lmoustache = "\u23B0";
var lmoust = "\u23B0";
var lnap = "\u2A89";
var lnapprox = "\u2A89";
var lne = "\u2A87";
var lnE = "\u2268";
var lneq = "\u2A87";
var lneqq = "\u2268";
var lnsim = "\u22E6";
var loang = "\u27EC";
var loarr = "\u21FD";
var lobrk = "\u27E6";
var longleftarrow = "\u27F5";
var LongLeftArrow = "\u27F5";
var Longleftarrow = "\u27F8";
var longleftrightarrow = "\u27F7";
var LongLeftRightArrow = "\u27F7";
var Longleftrightarrow = "\u27FA";
var longmapsto = "\u27FC";
var longrightarrow = "\u27F6";
var LongRightArrow = "\u27F6";
var Longrightarrow = "\u27F9";
var looparrowleft = "\u21AB";
var looparrowright = "\u21AC";
var lopar = "\u2985";
var Lopf = "\u{1D543}";
var lopf = "\u{1D55D}";
var loplus = "\u2A2D";
var lotimes = "\u2A34";
var lowast = "\u2217";
var lowbar = "_";
var LowerLeftArrow = "\u2199";
var LowerRightArrow = "\u2198";
var loz = "\u25CA";
var lozenge = "\u25CA";
var lozf = "\u29EB";
var lpar = "(";
var lparlt = "\u2993";
var lrarr = "\u21C6";
var lrcorner = "\u231F";
var lrhar = "\u21CB";
var lrhard = "\u296D";
var lrm = "\u200E";
var lrtri = "\u22BF";
var lsaquo = "\u2039";
var lscr = "\u{1D4C1}";
var Lscr = "\u2112";
var lsh = "\u21B0";
var Lsh = "\u21B0";
var lsim = "\u2272";
var lsime = "\u2A8D";
var lsimg = "\u2A8F";
var lsqb = "[";
var lsquo = "\u2018";
var lsquor = "\u201A";
var Lstrok = "\u0141";
var lstrok = "\u0142";
var ltcc = "\u2AA6";
var ltcir = "\u2A79";
var lt$2 = "<";
var LT$1 = "<";
var Lt = "\u226A";
var ltdot = "\u22D6";
var lthree = "\u22CB";
var ltimes = "\u22C9";
var ltlarr = "\u2976";
var ltquest = "\u2A7B";
var ltri = "\u25C3";
var ltrie = "\u22B4";
var ltrif = "\u25C2";
var ltrPar = "\u2996";
var lurdshar = "\u294A";
var luruhar = "\u2966";
var lvertneqq = "\u2268\uFE00";
var lvnE = "\u2268\uFE00";
var macr$1 = "\xAF";
var male = "\u2642";
var malt = "\u2720";
var maltese = "\u2720";
var map2 = "\u21A6";
var mapsto = "\u21A6";
var mapstodown = "\u21A7";
var mapstoleft = "\u21A4";
var mapstoup = "\u21A5";
var marker = "\u25AE";
var mcomma = "\u2A29";
var Mcy = "\u041C";
var mcy = "\u043C";
var mdash = "\u2014";
var mDDot = "\u223A";
var measuredangle = "\u2221";
var MediumSpace = "\u205F";
var Mellintrf = "\u2133";
var Mfr = "\u{1D510}";
var mfr = "\u{1D52A}";
var mho = "\u2127";
var micro$1 = "\xB5";
var midast = "*";
var midcir = "\u2AF0";
var mid = "\u2223";
var middot$1 = "\xB7";
var minusb = "\u229F";
var minus = "\u2212";
var minusd = "\u2238";
var minusdu = "\u2A2A";
var MinusPlus = "\u2213";
var mlcp = "\u2ADB";
var mldr = "\u2026";
var mnplus = "\u2213";
var models = "\u22A7";
var Mopf = "\u{1D544}";
var mopf = "\u{1D55E}";
var mp = "\u2213";
var mscr = "\u{1D4C2}";
var Mscr = "\u2133";
var mstpos = "\u223E";
var Mu = "\u039C";
var mu = "\u03BC";
var multimap = "\u22B8";
var mumap = "\u22B8";
var nabla = "\u2207";
var Nacute = "\u0143";
var nacute = "\u0144";
var nang = "\u2220\u20D2";
var nap = "\u2249";
var napE = "\u2A70\u0338";
var napid = "\u224B\u0338";
var napos = "\u0149";
var napprox = "\u2249";
var natural = "\u266E";
var naturals = "\u2115";
var natur = "\u266E";
var nbsp$1 = "\xA0";
var nbump = "\u224E\u0338";
var nbumpe = "\u224F\u0338";
var ncap = "\u2A43";
var Ncaron = "\u0147";
var ncaron = "\u0148";
var Ncedil = "\u0145";
var ncedil = "\u0146";
var ncong = "\u2247";
var ncongdot = "\u2A6D\u0338";
var ncup = "\u2A42";
var Ncy = "\u041D";
var ncy = "\u043D";
var ndash = "\u2013";
var nearhk = "\u2924";
var nearr = "\u2197";
var neArr = "\u21D7";
var nearrow = "\u2197";
var ne = "\u2260";
var nedot = "\u2250\u0338";
var NegativeMediumSpace = "\u200B";
var NegativeThickSpace = "\u200B";
var NegativeThinSpace = "\u200B";
var NegativeVeryThinSpace = "\u200B";
var nequiv = "\u2262";
var nesear = "\u2928";
var nesim = "\u2242\u0338";
var NestedGreaterGreater = "\u226B";
var NestedLessLess = "\u226A";
var NewLine = "\n";
var nexist = "\u2204";
var nexists = "\u2204";
var Nfr = "\u{1D511}";
var nfr = "\u{1D52B}";
var ngE = "\u2267\u0338";
var nge = "\u2271";
var ngeq = "\u2271";
var ngeqq = "\u2267\u0338";
var ngeqslant = "\u2A7E\u0338";
var nges = "\u2A7E\u0338";
var nGg = "\u22D9\u0338";
var ngsim = "\u2275";
var nGt = "\u226B\u20D2";
var ngt = "\u226F";
var ngtr = "\u226F";
var nGtv = "\u226B\u0338";
var nharr = "\u21AE";
var nhArr = "\u21CE";
var nhpar = "\u2AF2";
var ni = "\u220B";
var nis = "\u22FC";
var nisd = "\u22FA";
var niv = "\u220B";
var NJcy = "\u040A";
var njcy = "\u045A";
var nlarr = "\u219A";
var nlArr = "\u21CD";
var nldr = "\u2025";
var nlE = "\u2266\u0338";
var nle = "\u2270";
var nleftarrow = "\u219A";
var nLeftarrow = "\u21CD";
var nleftrightarrow = "\u21AE";
var nLeftrightarrow = "\u21CE";
var nleq = "\u2270";
var nleqq = "\u2266\u0338";
var nleqslant = "\u2A7D\u0338";
var nles = "\u2A7D\u0338";
var nless = "\u226E";
var nLl = "\u22D8\u0338";
var nlsim = "\u2274";
var nLt = "\u226A\u20D2";
var nlt = "\u226E";
var nltri = "\u22EA";
var nltrie = "\u22EC";
var nLtv = "\u226A\u0338";
var nmid = "\u2224";
var NoBreak = "\u2060";
var NonBreakingSpace = "\xA0";
var nopf = "\u{1D55F}";
var Nopf = "\u2115";
var Not = "\u2AEC";
var not$1 = "\xAC";
var NotCongruent = "\u2262";
var NotCupCap = "\u226D";
var NotDoubleVerticalBar = "\u2226";
var NotElement = "\u2209";
var NotEqual = "\u2260";
var NotEqualTilde = "\u2242\u0338";
var NotExists = "\u2204";
var NotGreater = "\u226F";
var NotGreaterEqual = "\u2271";
var NotGreaterFullEqual = "\u2267\u0338";
var NotGreaterGreater = "\u226B\u0338";
var NotGreaterLess = "\u2279";
var NotGreaterSlantEqual = "\u2A7E\u0338";
var NotGreaterTilde = "\u2275";
var NotHumpDownHump = "\u224E\u0338";
var NotHumpEqual = "\u224F\u0338";
var notin = "\u2209";
var notindot = "\u22F5\u0338";
var notinE = "\u22F9\u0338";
var notinva = "\u2209";
var notinvb = "\u22F7";
var notinvc = "\u22F6";
var NotLeftTriangleBar = "\u29CF\u0338";
var NotLeftTriangle = "\u22EA";
var NotLeftTriangleEqual = "\u22EC";
var NotLess = "\u226E";
var NotLessEqual = "\u2270";
var NotLessGreater = "\u2278";
var NotLessLess = "\u226A\u0338";
var NotLessSlantEqual = "\u2A7D\u0338";
var NotLessTilde = "\u2274";
var NotNestedGreaterGreater = "\u2AA2\u0338";
var NotNestedLessLess = "\u2AA1\u0338";
var notni = "\u220C";
var notniva = "\u220C";
var notnivb = "\u22FE";
var notnivc = "\u22FD";
var NotPrecedes = "\u2280";
var NotPrecedesEqual = "\u2AAF\u0338";
var NotPrecedesSlantEqual = "\u22E0";
var NotReverseElement = "\u220C";
var NotRightTriangleBar = "\u29D0\u0338";
var NotRightTriangle = "\u22EB";
var NotRightTriangleEqual = "\u22ED";
var NotSquareSubset = "\u228F\u0338";
var NotSquareSubsetEqual = "\u22E2";
var NotSquareSuperset = "\u2290\u0338";
var NotSquareSupersetEqual = "\u22E3";
var NotSubset = "\u2282\u20D2";
var NotSubsetEqual = "\u2288";
var NotSucceeds = "\u2281";
var NotSucceedsEqual = "\u2AB0\u0338";
var NotSucceedsSlantEqual = "\u22E1";
var NotSucceedsTilde = "\u227F\u0338";
var NotSuperset = "\u2283\u20D2";
var NotSupersetEqual = "\u2289";
var NotTilde = "\u2241";
var NotTildeEqual = "\u2244";
var NotTildeFullEqual = "\u2247";
var NotTildeTilde = "\u2249";
var NotVerticalBar = "\u2224";
var nparallel = "\u2226";
var npar = "\u2226";
var nparsl = "\u2AFD\u20E5";
var npart = "\u2202\u0338";
var npolint = "\u2A14";
var npr = "\u2280";
var nprcue = "\u22E0";
var nprec = "\u2280";
var npreceq = "\u2AAF\u0338";
var npre = "\u2AAF\u0338";
var nrarrc = "\u2933\u0338";
var nrarr = "\u219B";
var nrArr = "\u21CF";
var nrarrw = "\u219D\u0338";
var nrightarrow = "\u219B";
var nRightarrow = "\u21CF";
var nrtri = "\u22EB";
var nrtrie = "\u22ED";
var nsc = "\u2281";
var nsccue = "\u22E1";
var nsce = "\u2AB0\u0338";
var Nscr = "\u{1D4A9}";
var nscr = "\u{1D4C3}";
var nshortmid = "\u2224";
var nshortparallel = "\u2226";
var nsim = "\u2241";
var nsime = "\u2244";
var nsimeq = "\u2244";
var nsmid = "\u2224";
var nspar = "\u2226";
var nsqsube = "\u22E2";
var nsqsupe = "\u22E3";
var nsub = "\u2284";
var nsubE = "\u2AC5\u0338";
var nsube = "\u2288";
var nsubset = "\u2282\u20D2";
var nsubseteq = "\u2288";
var nsubseteqq = "\u2AC5\u0338";
var nsucc = "\u2281";
var nsucceq = "\u2AB0\u0338";
var nsup = "\u2285";
var nsupE = "\u2AC6\u0338";
var nsupe = "\u2289";
var nsupset = "\u2283\u20D2";
var nsupseteq = "\u2289";
var nsupseteqq = "\u2AC6\u0338";
var ntgl = "\u2279";
var Ntilde$1 = "\xD1";
var ntilde$1 = "\xF1";
var ntlg = "\u2278";
var ntriangleleft = "\u22EA";
var ntrianglelefteq = "\u22EC";
var ntriangleright = "\u22EB";
var ntrianglerighteq = "\u22ED";
var Nu = "\u039D";
var nu = "\u03BD";
var num = "#";
var numero = "\u2116";
var numsp = "\u2007";
var nvap = "\u224D\u20D2";
var nvdash = "\u22AC";
var nvDash = "\u22AD";
var nVdash = "\u22AE";
var nVDash = "\u22AF";
var nvge = "\u2265\u20D2";
var nvgt = ">\u20D2";
var nvHarr = "\u2904";
var nvinfin = "\u29DE";
var nvlArr = "\u2902";
var nvle = "\u2264\u20D2";
var nvlt = "<\u20D2";
var nvltrie = "\u22B4\u20D2";
var nvrArr = "\u2903";
var nvrtrie = "\u22B5\u20D2";
var nvsim = "\u223C\u20D2";
var nwarhk = "\u2923";
var nwarr = "\u2196";
var nwArr = "\u21D6";
var nwarrow = "\u2196";
var nwnear = "\u2927";
var Oacute$1 = "\xD3";
var oacute$1 = "\xF3";
var oast = "\u229B";
var Ocirc$1 = "\xD4";
var ocirc$1 = "\xF4";
var ocir = "\u229A";
var Ocy = "\u041E";
var ocy = "\u043E";
var odash = "\u229D";
var Odblac = "\u0150";
var odblac = "\u0151";
var odiv = "\u2A38";
var odot = "\u2299";
var odsold = "\u29BC";
var OElig = "\u0152";
var oelig = "\u0153";
var ofcir = "\u29BF";
var Ofr = "\u{1D512}";
var ofr = "\u{1D52C}";
var ogon = "\u02DB";
var Ograve$1 = "\xD2";
var ograve$1 = "\xF2";
var ogt = "\u29C1";
var ohbar = "\u29B5";
var ohm = "\u03A9";
var oint = "\u222E";
var olarr = "\u21BA";
var olcir = "\u29BE";
var olcross = "\u29BB";
var oline = "\u203E";
var olt = "\u29C0";
var Omacr = "\u014C";
var omacr = "\u014D";
var Omega = "\u03A9";
var omega = "\u03C9";
var Omicron = "\u039F";
var omicron = "\u03BF";
var omid = "\u29B6";
var ominus = "\u2296";
var Oopf = "\u{1D546}";
var oopf = "\u{1D560}";
var opar = "\u29B7";
var OpenCurlyDoubleQuote = "\u201C";
var OpenCurlyQuote = "\u2018";
var operp = "\u29B9";
var oplus = "\u2295";
var orarr = "\u21BB";
var Or = "\u2A54";
var or = "\u2228";
var ord = "\u2A5D";
var order = "\u2134";
var orderof = "\u2134";
var ordf$1 = "\xAA";
var ordm$1 = "\xBA";
var origof = "\u22B6";
var oror = "\u2A56";
var orslope = "\u2A57";
var orv = "\u2A5B";
var oS = "\u24C8";
var Oscr = "\u{1D4AA}";
var oscr = "\u2134";
var Oslash$1 = "\xD8";
var oslash$1 = "\xF8";
var osol = "\u2298";
var Otilde$1 = "\xD5";
var otilde$1 = "\xF5";
var otimesas = "\u2A36";
var Otimes = "\u2A37";
var otimes = "\u2297";
var Ouml$1 = "\xD6";
var ouml$1 = "\xF6";
var ovbar = "\u233D";
var OverBar = "\u203E";
var OverBrace = "\u23DE";
var OverBracket = "\u23B4";
var OverParenthesis = "\u23DC";
var para$1 = "\xB6";
var parallel = "\u2225";
var par = "\u2225";
var parsim = "\u2AF3";
var parsl = "\u2AFD";
var part = "\u2202";
var PartialD = "\u2202";
var Pcy = "\u041F";
var pcy = "\u043F";
var percnt = "%";
var period = ".";
var permil = "\u2030";
var perp = "\u22A5";
var pertenk = "\u2031";
var Pfr = "\u{1D513}";
var pfr = "\u{1D52D}";
var Phi = "\u03A6";
var phi = "\u03C6";
var phiv = "\u03D5";
var phmmat = "\u2133";
var phone = "\u260E";
var Pi = "\u03A0";
var pi = "\u03C0";
var pitchfork = "\u22D4";
var piv = "\u03D6";
var planck = "\u210F";
var planckh = "\u210E";
var plankv = "\u210F";
var plusacir = "\u2A23";
var plusb = "\u229E";
var pluscir = "\u2A22";
var plus = "+";
var plusdo = "\u2214";
var plusdu = "\u2A25";
var pluse = "\u2A72";
var PlusMinus = "\xB1";
var plusmn$1 = "\xB1";
var plussim = "\u2A26";
var plustwo = "\u2A27";
var pm = "\xB1";
var Poincareplane = "\u210C";
var pointint = "\u2A15";
var popf = "\u{1D561}";
var Popf = "\u2119";
var pound$1 = "\xA3";
var prap = "\u2AB7";
var Pr = "\u2ABB";
var pr = "\u227A";
var prcue = "\u227C";
var precapprox = "\u2AB7";
var prec = "\u227A";
var preccurlyeq = "\u227C";
var Precedes = "\u227A";
var PrecedesEqual = "\u2AAF";
var PrecedesSlantEqual = "\u227C";
var PrecedesTilde = "\u227E";
var preceq = "\u2AAF";
var precnapprox = "\u2AB9";
var precneqq = "\u2AB5";
var precnsim = "\u22E8";
var pre = "\u2AAF";
var prE = "\u2AB3";
var precsim = "\u227E";
var prime = "\u2032";
var Prime = "\u2033";
var primes = "\u2119";
var prnap = "\u2AB9";
var prnE = "\u2AB5";
var prnsim = "\u22E8";
var prod = "\u220F";
var Product = "\u220F";
var profalar = "\u232E";
var profline = "\u2312";
var profsurf = "\u2313";
var prop = "\u221D";
var Proportional = "\u221D";
var Proportion = "\u2237";
var propto = "\u221D";
var prsim = "\u227E";
var prurel = "\u22B0";
var Pscr = "\u{1D4AB}";
var pscr = "\u{1D4C5}";
var Psi = "\u03A8";
var psi = "\u03C8";
var puncsp = "\u2008";
var Qfr = "\u{1D514}";
var qfr = "\u{1D52E}";
var qint = "\u2A0C";
var qopf = "\u{1D562}";
var Qopf = "\u211A";
var qprime = "\u2057";
var Qscr = "\u{1D4AC}";
var qscr = "\u{1D4C6}";
var quaternions = "\u210D";
var quatint = "\u2A16";
var quest = "?";
var questeq = "\u225F";
var quot$2 = '"';
var QUOT$1 = '"';
var rAarr = "\u21DB";
var race = "\u223D\u0331";
var Racute = "\u0154";
var racute = "\u0155";
var radic = "\u221A";
var raemptyv = "\u29B3";
var rang = "\u27E9";
var Rang = "\u27EB";
var rangd = "\u2992";
var range = "\u29A5";
var rangle = "\u27E9";
var raquo$1 = "\xBB";
var rarrap = "\u2975";
var rarrb = "\u21E5";
var rarrbfs = "\u2920";
var rarrc = "\u2933";
var rarr = "\u2192";
var Rarr = "\u21A0";
var rArr = "\u21D2";
var rarrfs = "\u291E";
var rarrhk = "\u21AA";
var rarrlp = "\u21AC";
var rarrpl = "\u2945";
var rarrsim = "\u2974";
var Rarrtl = "\u2916";
var rarrtl = "\u21A3";
var rarrw = "\u219D";
var ratail = "\u291A";
var rAtail = "\u291C";
var ratio = "\u2236";
var rationals = "\u211A";
var rbarr = "\u290D";
var rBarr = "\u290F";
var RBarr = "\u2910";
var rbbrk = "\u2773";
var rbrace = "}";
var rbrack = "]";
var rbrke = "\u298C";
var rbrksld = "\u298E";
var rbrkslu = "\u2990";
var Rcaron = "\u0158";
var rcaron = "\u0159";
var Rcedil = "\u0156";
var rcedil = "\u0157";
var rceil = "\u2309";
var rcub = "}";
var Rcy = "\u0420";
var rcy = "\u0440";
var rdca = "\u2937";
var rdldhar = "\u2969";
var rdquo = "\u201D";
var rdquor = "\u201D";
var rdsh = "\u21B3";
var real = "\u211C";
var realine = "\u211B";
var realpart = "\u211C";
var reals = "\u211D";
var Re = "\u211C";
var rect = "\u25AD";
var reg$1 = "\xAE";
var REG$1 = "\xAE";
var ReverseElement = "\u220B";
var ReverseEquilibrium = "\u21CB";
var ReverseUpEquilibrium = "\u296F";
var rfisht = "\u297D";
var rfloor = "\u230B";
var rfr = "\u{1D52F}";
var Rfr = "\u211C";
var rHar = "\u2964";
var rhard = "\u21C1";
var rharu = "\u21C0";
var rharul = "\u296C";
var Rho = "\u03A1";
var rho = "\u03C1";
var rhov = "\u03F1";
var RightAngleBracket = "\u27E9";
var RightArrowBar = "\u21E5";
var rightarrow = "\u2192";
var RightArrow = "\u2192";
var Rightarrow = "\u21D2";
var RightArrowLeftArrow = "\u21C4";
var rightarrowtail = "\u21A3";
var RightCeiling = "\u2309";
var RightDoubleBracket = "\u27E7";
var RightDownTeeVector = "\u295D";
var RightDownVectorBar = "\u2955";
var RightDownVector = "\u21C2";
var RightFloor = "\u230B";
var rightharpoondown = "\u21C1";
var rightharpoonup = "\u21C0";
var rightleftarrows = "\u21C4";
var rightleftharpoons = "\u21CC";
var rightrightarrows = "\u21C9";
var rightsquigarrow = "\u219D";
var RightTeeArrow = "\u21A6";
var RightTee = "\u22A2";
var RightTeeVector = "\u295B";
var rightthreetimes = "\u22CC";
var RightTriangleBar = "\u29D0";
var RightTriangle = "\u22B3";
var RightTriangleEqual = "\u22B5";
var RightUpDownVector = "\u294F";
var RightUpTeeVector = "\u295C";
var RightUpVectorBar = "\u2954";
var RightUpVector = "\u21BE";
var RightVectorBar = "\u2953";
var RightVector = "\u21C0";
var ring = "\u02DA";
var risingdotseq = "\u2253";
var rlarr = "\u21C4";
var rlhar = "\u21CC";
var rlm = "\u200F";
var rmoustache = "\u23B1";
var rmoust = "\u23B1";
var rnmid = "\u2AEE";
var roang = "\u27ED";
var roarr = "\u21FE";
var robrk = "\u27E7";
var ropar = "\u2986";
var ropf = "\u{1D563}";
var Ropf = "\u211D";
var roplus = "\u2A2E";
var rotimes = "\u2A35";
var RoundImplies = "\u2970";
var rpar = ")";
var rpargt = "\u2994";
var rppolint = "\u2A12";
var rrarr = "\u21C9";
var Rrightarrow = "\u21DB";
var rsaquo = "\u203A";
var rscr = "\u{1D4C7}";
var Rscr = "\u211B";
var rsh = "\u21B1";
var Rsh = "\u21B1";
var rsqb = "]";
var rsquo = "\u2019";
var rsquor = "\u2019";
var rthree = "\u22CC";
var rtimes = "\u22CA";
var rtri = "\u25B9";
var rtrie = "\u22B5";
var rtrif = "\u25B8";
var rtriltri = "\u29CE";
var RuleDelayed = "\u29F4";
var ruluhar = "\u2968";
var rx = "\u211E";
var Sacute = "\u015A";
var sacute = "\u015B";
var sbquo = "\u201A";
var scap = "\u2AB8";
var Scaron = "\u0160";
var scaron = "\u0161";
var Sc = "\u2ABC";
var sc = "\u227B";
var sccue = "\u227D";
var sce = "\u2AB0";
var scE = "\u2AB4";
var Scedil = "\u015E";
var scedil = "\u015F";
var Scirc = "\u015C";
var scirc = "\u015D";
var scnap = "\u2ABA";
var scnE = "\u2AB6";
var scnsim = "\u22E9";
var scpolint = "\u2A13";
var scsim = "\u227F";
var Scy = "\u0421";
var scy = "\u0441";
var sdotb = "\u22A1";
var sdot = "\u22C5";
var sdote = "\u2A66";
var searhk = "\u2925";
var searr = "\u2198";
var seArr = "\u21D8";
var searrow = "\u2198";
var sect$1 = "\xA7";
var semi = ";";
var seswar = "\u2929";
var setminus = "\u2216";
var setmn = "\u2216";
var sext = "\u2736";
var Sfr = "\u{1D516}";
var sfr = "\u{1D530}";
var sfrown = "\u2322";
var sharp = "\u266F";
var SHCHcy = "\u0429";
var shchcy = "\u0449";
var SHcy = "\u0428";
var shcy = "\u0448";
var ShortDownArrow = "\u2193";
var ShortLeftArrow = "\u2190";
var shortmid = "\u2223";
var shortparallel = "\u2225";
var ShortRightArrow = "\u2192";
var ShortUpArrow = "\u2191";
var shy$1 = "\xAD";
var Sigma = "\u03A3";
var sigma = "\u03C3";
var sigmaf = "\u03C2";
var sigmav = "\u03C2";
var sim = "\u223C";
var simdot = "\u2A6A";
var sime = "\u2243";
var simeq = "\u2243";
var simg = "\u2A9E";
var simgE = "\u2AA0";
var siml = "\u2A9D";
var simlE = "\u2A9F";
var simne = "\u2246";
var simplus = "\u2A24";
var simrarr = "\u2972";
var slarr = "\u2190";
var SmallCircle = "\u2218";
var smallsetminus = "\u2216";
var smashp = "\u2A33";
var smeparsl = "\u29E4";
var smid = "\u2223";
var smile = "\u2323";
var smt = "\u2AAA";
var smte = "\u2AAC";
var smtes = "\u2AAC\uFE00";
var SOFTcy = "\u042C";
var softcy = "\u044C";
var solbar = "\u233F";
var solb = "\u29C4";
var sol = "/";
var Sopf = "\u{1D54A}";
var sopf = "\u{1D564}";
var spades = "\u2660";
var spadesuit = "\u2660";
var spar = "\u2225";
var sqcap = "\u2293";
var sqcaps = "\u2293\uFE00";
var sqcup = "\u2294";
var sqcups = "\u2294\uFE00";
var Sqrt = "\u221A";
var sqsub = "\u228F";
var sqsube = "\u2291";
var sqsubset = "\u228F";
var sqsubseteq = "\u2291";
var sqsup = "\u2290";
var sqsupe = "\u2292";
var sqsupset = "\u2290";
var sqsupseteq = "\u2292";
var square = "\u25A1";
var Square = "\u25A1";
var SquareIntersection = "\u2293";
var SquareSubset = "\u228F";
var SquareSubsetEqual = "\u2291";
var SquareSuperset = "\u2290";
var SquareSupersetEqual = "\u2292";
var SquareUnion = "\u2294";
var squarf = "\u25AA";
var squ = "\u25A1";
var squf = "\u25AA";
var srarr = "\u2192";
var Sscr = "\u{1D4AE}";
var sscr = "\u{1D4C8}";
var ssetmn = "\u2216";
var ssmile = "\u2323";
var sstarf = "\u22C6";
var Star = "\u22C6";
var star = "\u2606";
var starf = "\u2605";
var straightepsilon = "\u03F5";
var straightphi = "\u03D5";
var strns = "\xAF";
var sub = "\u2282";
var Sub = "\u22D0";
var subdot = "\u2ABD";
var subE = "\u2AC5";
var sube = "\u2286";
var subedot = "\u2AC3";
var submult = "\u2AC1";
var subnE = "\u2ACB";
var subne = "\u228A";
var subplus = "\u2ABF";
var subrarr = "\u2979";
var subset = "\u2282";
var Subset = "\u22D0";
var subseteq = "\u2286";
var subseteqq = "\u2AC5";
var SubsetEqual = "\u2286";
var subsetneq = "\u228A";
var subsetneqq = "\u2ACB";
var subsim = "\u2AC7";
var subsub = "\u2AD5";
var subsup = "\u2AD3";
var succapprox = "\u2AB8";
var succ = "\u227B";
var succcurlyeq = "\u227D";
var Succeeds = "\u227B";
var SucceedsEqual = "\u2AB0";
var SucceedsSlantEqual = "\u227D";
var SucceedsTilde = "\u227F";
var succeq = "\u2AB0";
var succnapprox = "\u2ABA";
var succneqq = "\u2AB6";
var succnsim = "\u22E9";
var succsim = "\u227F";
var SuchThat = "\u220B";
var sum = "\u2211";
var Sum = "\u2211";
var sung = "\u266A";
var sup1$1 = "\xB9";
var sup2$1 = "\xB2";
var sup3$1 = "\xB3";
var sup = "\u2283";
var Sup = "\u22D1";
var supdot = "\u2ABE";
var supdsub = "\u2AD8";
var supE = "\u2AC6";
var supe = "\u2287";
var supedot = "\u2AC4";
var Superset = "\u2283";
var SupersetEqual = "\u2287";
var suphsol = "\u27C9";
var suphsub = "\u2AD7";
var suplarr = "\u297B";
var supmult = "\u2AC2";
var supnE = "\u2ACC";
var supne = "\u228B";
var supplus = "\u2AC0";
var supset = "\u2283";
var Supset = "\u22D1";
var supseteq = "\u2287";
var supseteqq = "\u2AC6";
var supsetneq = "\u228B";
var supsetneqq = "\u2ACC";
var supsim = "\u2AC8";
var supsub = "\u2AD4";
var supsup = "\u2AD6";
var swarhk = "\u2926";
var swarr = "\u2199";
var swArr = "\u21D9";
var swarrow = "\u2199";
var swnwar = "\u292A";
var szlig$1 = "\xDF";
var Tab = "	";
var target = "\u2316";
var Tau = "\u03A4";
var tau = "\u03C4";
var tbrk = "\u23B4";
var Tcaron = "\u0164";
var tcaron = "\u0165";
var Tcedil = "\u0162";
var tcedil = "\u0163";
var Tcy = "\u0422";
var tcy = "\u0442";
var tdot = "\u20DB";
var telrec = "\u2315";
var Tfr = "\u{1D517}";
var tfr = "\u{1D531}";
var there4 = "\u2234";
var therefore = "\u2234";
var Therefore = "\u2234";
var Theta = "\u0398";
var theta = "\u03B8";
var thetasym = "\u03D1";
var thetav = "\u03D1";
var thickapprox = "\u2248";
var thicksim = "\u223C";
var ThickSpace = "\u205F\u200A";
var ThinSpace = "\u2009";
var thinsp = "\u2009";
var thkap = "\u2248";
var thksim = "\u223C";
var THORN$1 = "\xDE";
var thorn$1 = "\xFE";
var tilde = "\u02DC";
var Tilde = "\u223C";
var TildeEqual = "\u2243";
var TildeFullEqual = "\u2245";
var TildeTilde = "\u2248";
var timesbar = "\u2A31";
var timesb = "\u22A0";
var times$1 = "\xD7";
var timesd = "\u2A30";
var tint = "\u222D";
var toea = "\u2928";
var topbot = "\u2336";
var topcir = "\u2AF1";
var top = "\u22A4";
var Topf = "\u{1D54B}";
var topf = "\u{1D565}";
var topfork = "\u2ADA";
var tosa = "\u2929";
var tprime = "\u2034";
var trade = "\u2122";
var TRADE = "\u2122";
var triangle = "\u25B5";
var triangledown = "\u25BF";
var triangleleft = "\u25C3";
var trianglelefteq = "\u22B4";
var triangleq = "\u225C";
var triangleright = "\u25B9";
var trianglerighteq = "\u22B5";
var tridot = "\u25EC";
var trie = "\u225C";
var triminus = "\u2A3A";
var TripleDot = "\u20DB";
var triplus = "\u2A39";
var trisb = "\u29CD";
var tritime = "\u2A3B";
var trpezium = "\u23E2";
var Tscr = "\u{1D4AF}";
var tscr = "\u{1D4C9}";
var TScy = "\u0426";
var tscy = "\u0446";
var TSHcy = "\u040B";
var tshcy = "\u045B";
var Tstrok = "\u0166";
var tstrok = "\u0167";
var twixt = "\u226C";
var twoheadleftarrow = "\u219E";
var twoheadrightarrow = "\u21A0";
var Uacute$1 = "\xDA";
var uacute$1 = "\xFA";
var uarr = "\u2191";
var Uarr = "\u219F";
var uArr = "\u21D1";
var Uarrocir = "\u2949";
var Ubrcy = "\u040E";
var ubrcy = "\u045E";
var Ubreve = "\u016C";
var ubreve = "\u016D";
var Ucirc$1 = "\xDB";
var ucirc$1 = "\xFB";
var Ucy = "\u0423";
var ucy = "\u0443";
var udarr = "\u21C5";
var Udblac = "\u0170";
var udblac = "\u0171";
var udhar = "\u296E";
var ufisht = "\u297E";
var Ufr = "\u{1D518}";
var ufr = "\u{1D532}";
var Ugrave$1 = "\xD9";
var ugrave$1 = "\xF9";
var uHar = "\u2963";
var uharl = "\u21BF";
var uharr = "\u21BE";
var uhblk = "\u2580";
var ulcorn = "\u231C";
var ulcorner = "\u231C";
var ulcrop = "\u230F";
var ultri = "\u25F8";
var Umacr = "\u016A";
var umacr = "\u016B";
var uml$1 = "\xA8";
var UnderBar = "_";
var UnderBrace = "\u23DF";
var UnderBracket = "\u23B5";
var UnderParenthesis = "\u23DD";
var Union = "\u22C3";
var UnionPlus = "\u228E";
var Uogon = "\u0172";
var uogon = "\u0173";
var Uopf = "\u{1D54C}";
var uopf = "\u{1D566}";
var UpArrowBar = "\u2912";
var uparrow = "\u2191";
var UpArrow = "\u2191";
var Uparrow = "\u21D1";
var UpArrowDownArrow = "\u21C5";
var updownarrow = "\u2195";
var UpDownArrow = "\u2195";
var Updownarrow = "\u21D5";
var UpEquilibrium = "\u296E";
var upharpoonleft = "\u21BF";
var upharpoonright = "\u21BE";
var uplus = "\u228E";
var UpperLeftArrow = "\u2196";
var UpperRightArrow = "\u2197";
var upsi = "\u03C5";
var Upsi = "\u03D2";
var upsih = "\u03D2";
var Upsilon = "\u03A5";
var upsilon = "\u03C5";
var UpTeeArrow = "\u21A5";
var UpTee = "\u22A5";
var upuparrows = "\u21C8";
var urcorn = "\u231D";
var urcorner = "\u231D";
var urcrop = "\u230E";
var Uring = "\u016E";
var uring = "\u016F";
var urtri = "\u25F9";
var Uscr = "\u{1D4B0}";
var uscr = "\u{1D4CA}";
var utdot = "\u22F0";
var Utilde = "\u0168";
var utilde = "\u0169";
var utri = "\u25B5";
var utrif = "\u25B4";
var uuarr = "\u21C8";
var Uuml$1 = "\xDC";
var uuml$1 = "\xFC";
var uwangle = "\u29A7";
var vangrt = "\u299C";
var varepsilon = "\u03F5";
var varkappa = "\u03F0";
var varnothing = "\u2205";
var varphi = "\u03D5";
var varpi = "\u03D6";
var varpropto = "\u221D";
var varr = "\u2195";
var vArr = "\u21D5";
var varrho = "\u03F1";
var varsigma = "\u03C2";
var varsubsetneq = "\u228A\uFE00";
var varsubsetneqq = "\u2ACB\uFE00";
var varsupsetneq = "\u228B\uFE00";
var varsupsetneqq = "\u2ACC\uFE00";
var vartheta = "\u03D1";
var vartriangleleft = "\u22B2";
var vartriangleright = "\u22B3";
var vBar = "\u2AE8";
var Vbar = "\u2AEB";
var vBarv = "\u2AE9";
var Vcy = "\u0412";
var vcy = "\u0432";
var vdash = "\u22A2";
var vDash = "\u22A8";
var Vdash = "\u22A9";
var VDash = "\u22AB";
var Vdashl = "\u2AE6";
var veebar = "\u22BB";
var vee = "\u2228";
var Vee = "\u22C1";
var veeeq = "\u225A";
var vellip = "\u22EE";
var verbar = "|";
var Verbar = "\u2016";
var vert = "|";
var Vert = "\u2016";
var VerticalBar = "\u2223";
var VerticalLine = "|";
var VerticalSeparator = "\u2758";
var VerticalTilde = "\u2240";
var VeryThinSpace = "\u200A";
var Vfr = "\u{1D519}";
var vfr = "\u{1D533}";
var vltri = "\u22B2";
var vnsub = "\u2282\u20D2";
var vnsup = "\u2283\u20D2";
var Vopf = "\u{1D54D}";
var vopf = "\u{1D567}";
var vprop = "\u221D";
var vrtri = "\u22B3";
var Vscr = "\u{1D4B1}";
var vscr = "\u{1D4CB}";
var vsubnE = "\u2ACB\uFE00";
var vsubne = "\u228A\uFE00";
var vsupnE = "\u2ACC\uFE00";
var vsupne = "\u228B\uFE00";
var Vvdash = "\u22AA";
var vzigzag = "\u299A";
var Wcirc = "\u0174";
var wcirc = "\u0175";
var wedbar = "\u2A5F";
var wedge = "\u2227";
var Wedge = "\u22C0";
var wedgeq = "\u2259";
var weierp = "\u2118";
var Wfr = "\u{1D51A}";
var wfr = "\u{1D534}";
var Wopf = "\u{1D54E}";
var wopf = "\u{1D568}";
var wp = "\u2118";
var wr = "\u2240";
var wreath = "\u2240";
var Wscr = "\u{1D4B2}";
var wscr = "\u{1D4CC}";
var xcap = "\u22C2";
var xcirc = "\u25EF";
var xcup = "\u22C3";
var xdtri = "\u25BD";
var Xfr = "\u{1D51B}";
var xfr = "\u{1D535}";
var xharr = "\u27F7";
var xhArr = "\u27FA";
var Xi = "\u039E";
var xi = "\u03BE";
var xlarr = "\u27F5";
var xlArr = "\u27F8";
var xmap = "\u27FC";
var xnis = "\u22FB";
var xodot = "\u2A00";
var Xopf = "\u{1D54F}";
var xopf = "\u{1D569}";
var xoplus = "\u2A01";
var xotime = "\u2A02";
var xrarr = "\u27F6";
var xrArr = "\u27F9";
var Xscr = "\u{1D4B3}";
var xscr = "\u{1D4CD}";
var xsqcup = "\u2A06";
var xuplus = "\u2A04";
var xutri = "\u25B3";
var xvee = "\u22C1";
var xwedge = "\u22C0";
var Yacute$1 = "\xDD";
var yacute$1 = "\xFD";
var YAcy = "\u042F";
var yacy = "\u044F";
var Ycirc = "\u0176";
var ycirc = "\u0177";
var Ycy = "\u042B";
var ycy = "\u044B";
var yen$1 = "\xA5";
var Yfr = "\u{1D51C}";
var yfr = "\u{1D536}";
var YIcy = "\u0407";
var yicy = "\u0457";
var Yopf = "\u{1D550}";
var yopf = "\u{1D56A}";
var Yscr = "\u{1D4B4}";
var yscr = "\u{1D4CE}";
var YUcy = "\u042E";
var yucy = "\u044E";
var yuml$1 = "\xFF";
var Yuml = "\u0178";
var Zacute = "\u0179";
var zacute = "\u017A";
var Zcaron = "\u017D";
var zcaron = "\u017E";
var Zcy = "\u0417";
var zcy = "\u0437";
var Zdot = "\u017B";
var zdot = "\u017C";
var zeetrf = "\u2128";
var ZeroWidthSpace = "\u200B";
var Zeta = "\u0396";
var zeta = "\u03B6";
var zfr = "\u{1D537}";
var Zfr = "\u2128";
var ZHcy = "\u0416";
var zhcy = "\u0436";
var zigrarr = "\u21DD";
var zopf = "\u{1D56B}";
var Zopf = "\u2124";
var Zscr = "\u{1D4B5}";
var zscr = "\u{1D4CF}";
var zwj = "\u200D";
var zwnj = "\u200C";
var require$$1$1 = {
  Aacute: Aacute$1,
  aacute: aacute$1,
  Abreve,
  abreve,
  ac,
  acd,
  acE,
  Acirc: Acirc$1,
  acirc: acirc$1,
  acute: acute$1,
  Acy,
  acy,
  AElig: AElig$1,
  aelig: aelig$1,
  af,
  Afr,
  afr,
  Agrave: Agrave$1,
  agrave: agrave$1,
  alefsym,
  aleph,
  Alpha,
  alpha,
  Amacr,
  amacr,
  amalg,
  amp: amp$2,
  AMP: AMP$1,
  andand,
  And,
  and,
  andd,
  andslope,
  andv,
  ang,
  ange,
  angle,
  angmsdaa,
  angmsdab,
  angmsdac,
  angmsdad,
  angmsdae,
  angmsdaf,
  angmsdag,
  angmsdah,
  angmsd,
  angrt,
  angrtvb,
  angrtvbd,
  angsph,
  angst,
  angzarr,
  Aogon,
  aogon,
  Aopf,
  aopf,
  apacir,
  ap,
  apE,
  ape,
  apid,
  apos: apos$1,
  ApplyFunction,
  approx,
  approxeq,
  Aring: Aring$1,
  aring: aring$1,
  Ascr,
  ascr,
  Assign,
  ast,
  asymp,
  asympeq,
  Atilde: Atilde$1,
  atilde: atilde$1,
  Auml: Auml$1,
  auml: auml$1,
  awconint,
  awint,
  backcong,
  backepsilon,
  backprime,
  backsim,
  backsimeq,
  Backslash,
  Barv,
  barvee,
  barwed,
  Barwed,
  barwedge,
  bbrk,
  bbrktbrk,
  bcong,
  Bcy,
  bcy,
  bdquo,
  becaus,
  because,
  Because,
  bemptyv,
  bepsi,
  bernou,
  Bernoullis,
  Beta,
  beta,
  beth,
  between,
  Bfr,
  bfr,
  bigcap,
  bigcirc,
  bigcup,
  bigodot,
  bigoplus,
  bigotimes,
  bigsqcup,
  bigstar,
  bigtriangledown,
  bigtriangleup,
  biguplus,
  bigvee,
  bigwedge,
  bkarow,
  blacklozenge,
  blacksquare,
  blacktriangle,
  blacktriangledown,
  blacktriangleleft,
  blacktriangleright,
  blank,
  blk12,
  blk14,
  blk34,
  block,
  bne,
  bnequiv,
  bNot,
  bnot,
  Bopf,
  bopf,
  bot,
  bottom,
  bowtie,
  boxbox,
  boxdl,
  boxdL,
  boxDl,
  boxDL,
  boxdr,
  boxdR,
  boxDr,
  boxDR,
  boxh,
  boxH,
  boxhd,
  boxHd,
  boxhD,
  boxHD,
  boxhu,
  boxHu,
  boxhU,
  boxHU,
  boxminus,
  boxplus,
  boxtimes,
  boxul,
  boxuL,
  boxUl,
  boxUL,
  boxur,
  boxuR,
  boxUr,
  boxUR,
  boxv,
  boxV,
  boxvh,
  boxvH,
  boxVh,
  boxVH,
  boxvl,
  boxvL,
  boxVl,
  boxVL,
  boxvr,
  boxvR,
  boxVr,
  boxVR,
  bprime,
  breve,
  Breve,
  brvbar: brvbar$1,
  bscr,
  Bscr,
  bsemi,
  bsim,
  bsime,
  bsolb,
  bsol,
  bsolhsub,
  bull,
  bullet,
  bump,
  bumpE,
  bumpe,
  Bumpeq,
  bumpeq,
  Cacute,
  cacute,
  capand,
  capbrcup,
  capcap,
  cap,
  Cap,
  capcup,
  capdot,
  CapitalDifferentialD,
  caps,
  caret,
  caron,
  Cayleys,
  ccaps,
  Ccaron,
  ccaron,
  Ccedil: Ccedil$1,
  ccedil: ccedil$1,
  Ccirc,
  ccirc,
  Cconint,
  ccups,
  ccupssm,
  Cdot,
  cdot,
  cedil: cedil$1,
  Cedilla,
  cemptyv,
  cent: cent$1,
  centerdot,
  CenterDot,
  cfr,
  Cfr,
  CHcy,
  chcy,
  check,
  checkmark,
  Chi,
  chi,
  circ,
  circeq,
  circlearrowleft,
  circlearrowright,
  circledast,
  circledcirc,
  circleddash,
  CircleDot,
  circledR,
  circledS,
  CircleMinus,
  CirclePlus,
  CircleTimes,
  cir,
  cirE,
  cire,
  cirfnint,
  cirmid,
  cirscir,
  ClockwiseContourIntegral,
  CloseCurlyDoubleQuote,
  CloseCurlyQuote,
  clubs,
  clubsuit,
  colon,
  Colon,
  Colone,
  colone,
  coloneq,
  comma,
  commat,
  comp,
  compfn,
  complement,
  complexes,
  cong,
  congdot,
  Congruent,
  conint,
  Conint,
  ContourIntegral,
  copf,
  Copf,
  coprod,
  Coproduct,
  copy: copy$1,
  COPY: COPY$1,
  copysr,
  CounterClockwiseContourIntegral,
  crarr,
  cross,
  Cross,
  Cscr,
  cscr,
  csub,
  csube,
  csup,
  csupe,
  ctdot,
  cudarrl,
  cudarrr,
  cuepr,
  cuesc,
  cularr,
  cularrp,
  cupbrcap,
  cupcap,
  CupCap,
  cup,
  Cup,
  cupcup,
  cupdot,
  cupor,
  cups,
  curarr,
  curarrm,
  curlyeqprec,
  curlyeqsucc,
  curlyvee,
  curlywedge,
  curren: curren$1,
  curvearrowleft,
  curvearrowright,
  cuvee,
  cuwed,
  cwconint,
  cwint,
  cylcty,
  dagger,
  Dagger,
  daleth,
  darr,
  Darr,
  dArr,
  dash,
  Dashv,
  dashv,
  dbkarow,
  dblac,
  Dcaron,
  dcaron,
  Dcy,
  dcy,
  ddagger,
  ddarr,
  DD,
  dd,
  DDotrahd,
  ddotseq,
  deg: deg$1,
  Del,
  Delta,
  delta,
  demptyv,
  dfisht,
  Dfr,
  dfr,
  dHar,
  dharl,
  dharr,
  DiacriticalAcute,
  DiacriticalDot,
  DiacriticalDoubleAcute,
  DiacriticalGrave,
  DiacriticalTilde,
  diam,
  diamond,
  Diamond,
  diamondsuit,
  diams,
  die,
  DifferentialD,
  digamma,
  disin,
  div,
  divide: divide$1,
  divideontimes,
  divonx,
  DJcy,
  djcy,
  dlcorn,
  dlcrop,
  dollar,
  Dopf,
  dopf,
  Dot,
  dot,
  DotDot,
  doteq,
  doteqdot,
  DotEqual,
  dotminus,
  dotplus,
  dotsquare,
  doublebarwedge,
  DoubleContourIntegral,
  DoubleDot,
  DoubleDownArrow,
  DoubleLeftArrow,
  DoubleLeftRightArrow,
  DoubleLeftTee,
  DoubleLongLeftArrow,
  DoubleLongLeftRightArrow,
  DoubleLongRightArrow,
  DoubleRightArrow,
  DoubleRightTee,
  DoubleUpArrow,
  DoubleUpDownArrow,
  DoubleVerticalBar,
  DownArrowBar,
  downarrow,
  DownArrow,
  Downarrow,
  DownArrowUpArrow,
  DownBreve,
  downdownarrows,
  downharpoonleft,
  downharpoonright,
  DownLeftRightVector,
  DownLeftTeeVector,
  DownLeftVectorBar,
  DownLeftVector,
  DownRightTeeVector,
  DownRightVectorBar,
  DownRightVector,
  DownTeeArrow,
  DownTee,
  drbkarow,
  drcorn,
  drcrop,
  Dscr,
  dscr,
  DScy,
  dscy,
  dsol,
  Dstrok,
  dstrok,
  dtdot,
  dtri,
  dtrif,
  duarr,
  duhar,
  dwangle,
  DZcy,
  dzcy,
  dzigrarr,
  Eacute: Eacute$1,
  eacute: eacute$1,
  easter,
  Ecaron,
  ecaron,
  Ecirc: Ecirc$1,
  ecirc: ecirc$1,
  ecir,
  ecolon,
  Ecy,
  ecy,
  eDDot,
  Edot,
  edot,
  eDot,
  ee,
  efDot,
  Efr,
  efr,
  eg,
  Egrave: Egrave$1,
  egrave: egrave$1,
  egs,
  egsdot,
  el,
  Element: Element$1,
  elinters,
  ell,
  els,
  elsdot,
  Emacr,
  emacr,
  empty: empty2,
  emptyset,
  EmptySmallSquare,
  emptyv,
  EmptyVerySmallSquare,
  emsp13,
  emsp14,
  emsp,
  ENG,
  eng,
  ensp,
  Eogon,
  eogon,
  Eopf,
  eopf,
  epar,
  eparsl,
  eplus,
  epsi,
  Epsilon,
  epsilon,
  epsiv,
  eqcirc,
  eqcolon,
  eqsim,
  eqslantgtr,
  eqslantless,
  Equal,
  equals,
  EqualTilde,
  equest,
  Equilibrium,
  equiv,
  equivDD,
  eqvparsl,
  erarr,
  erDot,
  escr,
  Escr,
  esdot,
  Esim,
  esim,
  Eta,
  eta,
  ETH: ETH$1,
  eth: eth$1,
  Euml: Euml$1,
  euml: euml$1,
  euro,
  excl,
  exist,
  Exists,
  expectation,
  exponentiale,
  ExponentialE,
  fallingdotseq,
  Fcy,
  fcy,
  female,
  ffilig,
  fflig,
  ffllig,
  Ffr,
  ffr,
  filig,
  FilledSmallSquare,
  FilledVerySmallSquare,
  fjlig,
  flat,
  fllig,
  fltns,
  fnof,
  Fopf,
  fopf,
  forall,
  ForAll,
  fork,
  forkv,
  Fouriertrf,
  fpartint,
  frac12: frac12$1,
  frac13,
  frac14: frac14$1,
  frac15,
  frac16,
  frac18,
  frac23,
  frac25,
  frac34: frac34$1,
  frac35,
  frac38,
  frac45,
  frac56,
  frac58,
  frac78,
  frasl,
  frown,
  fscr,
  Fscr,
  gacute,
  Gamma,
  gamma,
  Gammad,
  gammad,
  gap,
  Gbreve,
  gbreve,
  Gcedil,
  Gcirc,
  gcirc,
  Gcy,
  gcy,
  Gdot,
  gdot,
  ge,
  gE,
  gEl,
  gel,
  geq,
  geqq,
  geqslant,
  gescc,
  ges,
  gesdot,
  gesdoto,
  gesdotol,
  gesl,
  gesles,
  Gfr,
  gfr,
  gg,
  Gg,
  ggg,
  gimel,
  GJcy,
  gjcy,
  gla,
  gl,
  glE,
  glj,
  gnap,
  gnapprox,
  gne,
  gnE,
  gneq,
  gneqq,
  gnsim,
  Gopf,
  gopf,
  grave,
  GreaterEqual,
  GreaterEqualLess,
  GreaterFullEqual,
  GreaterGreater,
  GreaterLess,
  GreaterSlantEqual,
  GreaterTilde,
  Gscr,
  gscr,
  gsim,
  gsime,
  gsiml,
  gtcc,
  gtcir,
  gt: gt$2,
  GT: GT$1,
  Gt,
  gtdot,
  gtlPar,
  gtquest,
  gtrapprox,
  gtrarr,
  gtrdot,
  gtreqless,
  gtreqqless,
  gtrless,
  gtrsim,
  gvertneqq,
  gvnE,
  Hacek,
  hairsp,
  half,
  hamilt,
  HARDcy,
  hardcy,
  harrcir,
  harr,
  hArr,
  harrw,
  Hat,
  hbar,
  Hcirc,
  hcirc,
  hearts,
  heartsuit,
  hellip,
  hercon,
  hfr,
  Hfr,
  HilbertSpace,
  hksearow,
  hkswarow,
  hoarr,
  homtht,
  hookleftarrow,
  hookrightarrow,
  hopf,
  Hopf,
  horbar,
  HorizontalLine,
  hscr,
  Hscr,
  hslash,
  Hstrok,
  hstrok,
  HumpDownHump,
  HumpEqual,
  hybull,
  hyphen,
  Iacute: Iacute$1,
  iacute: iacute$1,
  ic,
  Icirc: Icirc$1,
  icirc: icirc$1,
  Icy,
  icy,
  Idot,
  IEcy,
  iecy,
  iexcl: iexcl$1,
  iff,
  ifr,
  Ifr,
  Igrave: Igrave$1,
  igrave: igrave$1,
  ii,
  iiiint,
  iiint,
  iinfin,
  iiota,
  IJlig,
  ijlig,
  Imacr,
  imacr,
  image,
  ImaginaryI,
  imagline,
  imagpart,
  imath,
  Im,
  imof,
  imped,
  Implies,
  incare,
  "in": "\u2208",
  infin,
  infintie,
  inodot,
  intcal,
  int,
  Int,
  integers,
  Integral,
  intercal,
  Intersection,
  intlarhk,
  intprod,
  InvisibleComma,
  InvisibleTimes,
  IOcy,
  iocy,
  Iogon,
  iogon,
  Iopf,
  iopf,
  Iota,
  iota,
  iprod,
  iquest: iquest$1,
  iscr,
  Iscr,
  isin,
  isindot,
  isinE,
  isins,
  isinsv,
  isinv,
  it,
  Itilde,
  itilde,
  Iukcy,
  iukcy,
  Iuml: Iuml$1,
  iuml: iuml$1,
  Jcirc,
  jcirc,
  Jcy,
  jcy,
  Jfr,
  jfr,
  jmath,
  Jopf,
  jopf,
  Jscr,
  jscr,
  Jsercy,
  jsercy,
  Jukcy,
  jukcy,
  Kappa,
  kappa,
  kappav,
  Kcedil,
  kcedil,
  Kcy,
  kcy,
  Kfr,
  kfr,
  kgreen,
  KHcy,
  khcy,
  KJcy,
  kjcy,
  Kopf,
  kopf,
  Kscr,
  kscr,
  lAarr,
  Lacute,
  lacute,
  laemptyv,
  lagran,
  Lambda,
  lambda,
  lang,
  Lang,
  langd,
  langle,
  lap,
  Laplacetrf,
  laquo: laquo$1,
  larrb,
  larrbfs,
  larr,
  Larr,
  lArr,
  larrfs,
  larrhk,
  larrlp,
  larrpl,
  larrsim,
  larrtl,
  latail,
  lAtail,
  lat,
  late,
  lates,
  lbarr,
  lBarr,
  lbbrk,
  lbrace,
  lbrack,
  lbrke,
  lbrksld,
  lbrkslu,
  Lcaron,
  lcaron,
  Lcedil,
  lcedil,
  lceil,
  lcub,
  Lcy,
  lcy,
  ldca,
  ldquo,
  ldquor,
  ldrdhar,
  ldrushar,
  ldsh,
  le,
  lE,
  LeftAngleBracket,
  LeftArrowBar,
  leftarrow,
  LeftArrow,
  Leftarrow,
  LeftArrowRightArrow,
  leftarrowtail,
  LeftCeiling,
  LeftDoubleBracket,
  LeftDownTeeVector,
  LeftDownVectorBar,
  LeftDownVector,
  LeftFloor,
  leftharpoondown,
  leftharpoonup,
  leftleftarrows,
  leftrightarrow,
  LeftRightArrow,
  Leftrightarrow,
  leftrightarrows,
  leftrightharpoons,
  leftrightsquigarrow,
  LeftRightVector,
  LeftTeeArrow,
  LeftTee,
  LeftTeeVector,
  leftthreetimes,
  LeftTriangleBar,
  LeftTriangle,
  LeftTriangleEqual,
  LeftUpDownVector,
  LeftUpTeeVector,
  LeftUpVectorBar,
  LeftUpVector,
  LeftVectorBar,
  LeftVector,
  lEg,
  leg,
  leq,
  leqq,
  leqslant,
  lescc,
  les,
  lesdot,
  lesdoto,
  lesdotor,
  lesg,
  lesges,
  lessapprox,
  lessdot,
  lesseqgtr,
  lesseqqgtr,
  LessEqualGreater,
  LessFullEqual,
  LessGreater,
  lessgtr,
  LessLess,
  lesssim,
  LessSlantEqual,
  LessTilde,
  lfisht,
  lfloor,
  Lfr,
  lfr,
  lg,
  lgE,
  lHar,
  lhard,
  lharu,
  lharul,
  lhblk,
  LJcy,
  ljcy,
  llarr,
  ll,
  Ll,
  llcorner,
  Lleftarrow,
  llhard,
  lltri,
  Lmidot,
  lmidot,
  lmoustache,
  lmoust,
  lnap,
  lnapprox,
  lne,
  lnE,
  lneq,
  lneqq,
  lnsim,
  loang,
  loarr,
  lobrk,
  longleftarrow,
  LongLeftArrow,
  Longleftarrow,
  longleftrightarrow,
  LongLeftRightArrow,
  Longleftrightarrow,
  longmapsto,
  longrightarrow,
  LongRightArrow,
  Longrightarrow,
  looparrowleft,
  looparrowright,
  lopar,
  Lopf,
  lopf,
  loplus,
  lotimes,
  lowast,
  lowbar,
  LowerLeftArrow,
  LowerRightArrow,
  loz,
  lozenge,
  lozf,
  lpar,
  lparlt,
  lrarr,
  lrcorner,
  lrhar,
  lrhard,
  lrm,
  lrtri,
  lsaquo,
  lscr,
  Lscr,
  lsh,
  Lsh,
  lsim,
  lsime,
  lsimg,
  lsqb,
  lsquo,
  lsquor,
  Lstrok,
  lstrok,
  ltcc,
  ltcir,
  lt: lt$2,
  LT: LT$1,
  Lt,
  ltdot,
  lthree,
  ltimes,
  ltlarr,
  ltquest,
  ltri,
  ltrie,
  ltrif,
  ltrPar,
  lurdshar,
  luruhar,
  lvertneqq,
  lvnE,
  macr: macr$1,
  male,
  malt,
  maltese,
  "Map": "\u2905",
  map: map2,
  mapsto,
  mapstodown,
  mapstoleft,
  mapstoup,
  marker,
  mcomma,
  Mcy,
  mcy,
  mdash,
  mDDot,
  measuredangle,
  MediumSpace,
  Mellintrf,
  Mfr,
  mfr,
  mho,
  micro: micro$1,
  midast,
  midcir,
  mid,
  middot: middot$1,
  minusb,
  minus,
  minusd,
  minusdu,
  MinusPlus,
  mlcp,
  mldr,
  mnplus,
  models,
  Mopf,
  mopf,
  mp,
  mscr,
  Mscr,
  mstpos,
  Mu,
  mu,
  multimap,
  mumap,
  nabla,
  Nacute,
  nacute,
  nang,
  nap,
  napE,
  napid,
  napos,
  napprox,
  natural,
  naturals,
  natur,
  nbsp: nbsp$1,
  nbump,
  nbumpe,
  ncap,
  Ncaron,
  ncaron,
  Ncedil,
  ncedil,
  ncong,
  ncongdot,
  ncup,
  Ncy,
  ncy,
  ndash,
  nearhk,
  nearr,
  neArr,
  nearrow,
  ne,
  nedot,
  NegativeMediumSpace,
  NegativeThickSpace,
  NegativeThinSpace,
  NegativeVeryThinSpace,
  nequiv,
  nesear,
  nesim,
  NestedGreaterGreater,
  NestedLessLess,
  NewLine,
  nexist,
  nexists,
  Nfr,
  nfr,
  ngE,
  nge,
  ngeq,
  ngeqq,
  ngeqslant,
  nges,
  nGg,
  ngsim,
  nGt,
  ngt,
  ngtr,
  nGtv,
  nharr,
  nhArr,
  nhpar,
  ni,
  nis,
  nisd,
  niv,
  NJcy,
  njcy,
  nlarr,
  nlArr,
  nldr,
  nlE,
  nle,
  nleftarrow,
  nLeftarrow,
  nleftrightarrow,
  nLeftrightarrow,
  nleq,
  nleqq,
  nleqslant,
  nles,
  nless,
  nLl,
  nlsim,
  nLt,
  nlt,
  nltri,
  nltrie,
  nLtv,
  nmid,
  NoBreak,
  NonBreakingSpace,
  nopf,
  Nopf,
  Not,
  not: not$1,
  NotCongruent,
  NotCupCap,
  NotDoubleVerticalBar,
  NotElement,
  NotEqual,
  NotEqualTilde,
  NotExists,
  NotGreater,
  NotGreaterEqual,
  NotGreaterFullEqual,
  NotGreaterGreater,
  NotGreaterLess,
  NotGreaterSlantEqual,
  NotGreaterTilde,
  NotHumpDownHump,
  NotHumpEqual,
  notin,
  notindot,
  notinE,
  notinva,
  notinvb,
  notinvc,
  NotLeftTriangleBar,
  NotLeftTriangle,
  NotLeftTriangleEqual,
  NotLess,
  NotLessEqual,
  NotLessGreater,
  NotLessLess,
  NotLessSlantEqual,
  NotLessTilde,
  NotNestedGreaterGreater,
  NotNestedLessLess,
  notni,
  notniva,
  notnivb,
  notnivc,
  NotPrecedes,
  NotPrecedesEqual,
  NotPrecedesSlantEqual,
  NotReverseElement,
  NotRightTriangleBar,
  NotRightTriangle,
  NotRightTriangleEqual,
  NotSquareSubset,
  NotSquareSubsetEqual,
  NotSquareSuperset,
  NotSquareSupersetEqual,
  NotSubset,
  NotSubsetEqual,
  NotSucceeds,
  NotSucceedsEqual,
  NotSucceedsSlantEqual,
  NotSucceedsTilde,
  NotSuperset,
  NotSupersetEqual,
  NotTilde,
  NotTildeEqual,
  NotTildeFullEqual,
  NotTildeTilde,
  NotVerticalBar,
  nparallel,
  npar,
  nparsl,
  npart,
  npolint,
  npr,
  nprcue,
  nprec,
  npreceq,
  npre,
  nrarrc,
  nrarr,
  nrArr,
  nrarrw,
  nrightarrow,
  nRightarrow,
  nrtri,
  nrtrie,
  nsc,
  nsccue,
  nsce,
  Nscr,
  nscr,
  nshortmid,
  nshortparallel,
  nsim,
  nsime,
  nsimeq,
  nsmid,
  nspar,
  nsqsube,
  nsqsupe,
  nsub,
  nsubE,
  nsube,
  nsubset,
  nsubseteq,
  nsubseteqq,
  nsucc,
  nsucceq,
  nsup,
  nsupE,
  nsupe,
  nsupset,
  nsupseteq,
  nsupseteqq,
  ntgl,
  Ntilde: Ntilde$1,
  ntilde: ntilde$1,
  ntlg,
  ntriangleleft,
  ntrianglelefteq,
  ntriangleright,
  ntrianglerighteq,
  Nu,
  nu,
  num,
  numero,
  numsp,
  nvap,
  nvdash,
  nvDash,
  nVdash,
  nVDash,
  nvge,
  nvgt,
  nvHarr,
  nvinfin,
  nvlArr,
  nvle,
  nvlt,
  nvltrie,
  nvrArr,
  nvrtrie,
  nvsim,
  nwarhk,
  nwarr,
  nwArr,
  nwarrow,
  nwnear,
  Oacute: Oacute$1,
  oacute: oacute$1,
  oast,
  Ocirc: Ocirc$1,
  ocirc: ocirc$1,
  ocir,
  Ocy,
  ocy,
  odash,
  Odblac,
  odblac,
  odiv,
  odot,
  odsold,
  OElig,
  oelig,
  ofcir,
  Ofr,
  ofr,
  ogon,
  Ograve: Ograve$1,
  ograve: ograve$1,
  ogt,
  ohbar,
  ohm,
  oint,
  olarr,
  olcir,
  olcross,
  oline,
  olt,
  Omacr,
  omacr,
  Omega,
  omega,
  Omicron,
  omicron,
  omid,
  ominus,
  Oopf,
  oopf,
  opar,
  OpenCurlyDoubleQuote,
  OpenCurlyQuote,
  operp,
  oplus,
  orarr,
  Or,
  or,
  ord,
  order,
  orderof,
  ordf: ordf$1,
  ordm: ordm$1,
  origof,
  oror,
  orslope,
  orv,
  oS,
  Oscr,
  oscr,
  Oslash: Oslash$1,
  oslash: oslash$1,
  osol,
  Otilde: Otilde$1,
  otilde: otilde$1,
  otimesas,
  Otimes,
  otimes,
  Ouml: Ouml$1,
  ouml: ouml$1,
  ovbar,
  OverBar,
  OverBrace,
  OverBracket,
  OverParenthesis,
  para: para$1,
  parallel,
  par,
  parsim,
  parsl,
  part,
  PartialD,
  Pcy,
  pcy,
  percnt,
  period,
  permil,
  perp,
  pertenk,
  Pfr,
  pfr,
  Phi,
  phi,
  phiv,
  phmmat,
  phone,
  Pi,
  pi,
  pitchfork,
  piv,
  planck,
  planckh,
  plankv,
  plusacir,
  plusb,
  pluscir,
  plus,
  plusdo,
  plusdu,
  pluse,
  PlusMinus,
  plusmn: plusmn$1,
  plussim,
  plustwo,
  pm,
  Poincareplane,
  pointint,
  popf,
  Popf,
  pound: pound$1,
  prap,
  Pr,
  pr,
  prcue,
  precapprox,
  prec,
  preccurlyeq,
  Precedes,
  PrecedesEqual,
  PrecedesSlantEqual,
  PrecedesTilde,
  preceq,
  precnapprox,
  precneqq,
  precnsim,
  pre,
  prE,
  precsim,
  prime,
  Prime,
  primes,
  prnap,
  prnE,
  prnsim,
  prod,
  Product,
  profalar,
  profline,
  profsurf,
  prop,
  Proportional,
  Proportion,
  propto,
  prsim,
  prurel,
  Pscr,
  pscr,
  Psi,
  psi,
  puncsp,
  Qfr,
  qfr,
  qint,
  qopf,
  Qopf,
  qprime,
  Qscr,
  qscr,
  quaternions,
  quatint,
  quest,
  questeq,
  quot: quot$2,
  QUOT: QUOT$1,
  rAarr,
  race,
  Racute,
  racute,
  radic,
  raemptyv,
  rang,
  Rang,
  rangd,
  range,
  rangle,
  raquo: raquo$1,
  rarrap,
  rarrb,
  rarrbfs,
  rarrc,
  rarr,
  Rarr,
  rArr,
  rarrfs,
  rarrhk,
  rarrlp,
  rarrpl,
  rarrsim,
  Rarrtl,
  rarrtl,
  rarrw,
  ratail,
  rAtail,
  ratio,
  rationals,
  rbarr,
  rBarr,
  RBarr,
  rbbrk,
  rbrace,
  rbrack,
  rbrke,
  rbrksld,
  rbrkslu,
  Rcaron,
  rcaron,
  Rcedil,
  rcedil,
  rceil,
  rcub,
  Rcy,
  rcy,
  rdca,
  rdldhar,
  rdquo,
  rdquor,
  rdsh,
  real,
  realine,
  realpart,
  reals,
  Re,
  rect,
  reg: reg$1,
  REG: REG$1,
  ReverseElement,
  ReverseEquilibrium,
  ReverseUpEquilibrium,
  rfisht,
  rfloor,
  rfr,
  Rfr,
  rHar,
  rhard,
  rharu,
  rharul,
  Rho,
  rho,
  rhov,
  RightAngleBracket,
  RightArrowBar,
  rightarrow,
  RightArrow,
  Rightarrow,
  RightArrowLeftArrow,
  rightarrowtail,
  RightCeiling,
  RightDoubleBracket,
  RightDownTeeVector,
  RightDownVectorBar,
  RightDownVector,
  RightFloor,
  rightharpoondown,
  rightharpoonup,
  rightleftarrows,
  rightleftharpoons,
  rightrightarrows,
  rightsquigarrow,
  RightTeeArrow,
  RightTee,
  RightTeeVector,
  rightthreetimes,
  RightTriangleBar,
  RightTriangle,
  RightTriangleEqual,
  RightUpDownVector,
  RightUpTeeVector,
  RightUpVectorBar,
  RightUpVector,
  RightVectorBar,
  RightVector,
  ring,
  risingdotseq,
  rlarr,
  rlhar,
  rlm,
  rmoustache,
  rmoust,
  rnmid,
  roang,
  roarr,
  robrk,
  ropar,
  ropf,
  Ropf,
  roplus,
  rotimes,
  RoundImplies,
  rpar,
  rpargt,
  rppolint,
  rrarr,
  Rrightarrow,
  rsaquo,
  rscr,
  Rscr,
  rsh,
  Rsh,
  rsqb,
  rsquo,
  rsquor,
  rthree,
  rtimes,
  rtri,
  rtrie,
  rtrif,
  rtriltri,
  RuleDelayed,
  ruluhar,
  rx,
  Sacute,
  sacute,
  sbquo,
  scap,
  Scaron,
  scaron,
  Sc,
  sc,
  sccue,
  sce,
  scE,
  Scedil,
  scedil,
  Scirc,
  scirc,
  scnap,
  scnE,
  scnsim,
  scpolint,
  scsim,
  Scy,
  scy,
  sdotb,
  sdot,
  sdote,
  searhk,
  searr,
  seArr,
  searrow,
  sect: sect$1,
  semi,
  seswar,
  setminus,
  setmn,
  sext,
  Sfr,
  sfr,
  sfrown,
  sharp,
  SHCHcy,
  shchcy,
  SHcy,
  shcy,
  ShortDownArrow,
  ShortLeftArrow,
  shortmid,
  shortparallel,
  ShortRightArrow,
  ShortUpArrow,
  shy: shy$1,
  Sigma,
  sigma,
  sigmaf,
  sigmav,
  sim,
  simdot,
  sime,
  simeq,
  simg,
  simgE,
  siml,
  simlE,
  simne,
  simplus,
  simrarr,
  slarr,
  SmallCircle,
  smallsetminus,
  smashp,
  smeparsl,
  smid,
  smile,
  smt,
  smte,
  smtes,
  SOFTcy,
  softcy,
  solbar,
  solb,
  sol,
  Sopf,
  sopf,
  spades,
  spadesuit,
  spar,
  sqcap,
  sqcaps,
  sqcup,
  sqcups,
  Sqrt,
  sqsub,
  sqsube,
  sqsubset,
  sqsubseteq,
  sqsup,
  sqsupe,
  sqsupset,
  sqsupseteq,
  square,
  Square,
  SquareIntersection,
  SquareSubset,
  SquareSubsetEqual,
  SquareSuperset,
  SquareSupersetEqual,
  SquareUnion,
  squarf,
  squ,
  squf,
  srarr,
  Sscr,
  sscr,
  ssetmn,
  ssmile,
  sstarf,
  Star,
  star,
  starf,
  straightepsilon,
  straightphi,
  strns,
  sub,
  Sub,
  subdot,
  subE,
  sube,
  subedot,
  submult,
  subnE,
  subne,
  subplus,
  subrarr,
  subset,
  Subset,
  subseteq,
  subseteqq,
  SubsetEqual,
  subsetneq,
  subsetneqq,
  subsim,
  subsub,
  subsup,
  succapprox,
  succ,
  succcurlyeq,
  Succeeds,
  SucceedsEqual,
  SucceedsSlantEqual,
  SucceedsTilde,
  succeq,
  succnapprox,
  succneqq,
  succnsim,
  succsim,
  SuchThat,
  sum,
  Sum,
  sung,
  sup1: sup1$1,
  sup2: sup2$1,
  sup3: sup3$1,
  sup,
  Sup,
  supdot,
  supdsub,
  supE,
  supe,
  supedot,
  Superset,
  SupersetEqual,
  suphsol,
  suphsub,
  suplarr,
  supmult,
  supnE,
  supne,
  supplus,
  supset,
  Supset,
  supseteq,
  supseteqq,
  supsetneq,
  supsetneqq,
  supsim,
  supsub,
  supsup,
  swarhk,
  swarr,
  swArr,
  swarrow,
  swnwar,
  szlig: szlig$1,
  Tab,
  target,
  Tau,
  tau,
  tbrk,
  Tcaron,
  tcaron,
  Tcedil,
  tcedil,
  Tcy,
  tcy,
  tdot,
  telrec,
  Tfr,
  tfr,
  there4,
  therefore,
  Therefore,
  Theta,
  theta,
  thetasym,
  thetav,
  thickapprox,
  thicksim,
  ThickSpace,
  ThinSpace,
  thinsp,
  thkap,
  thksim,
  THORN: THORN$1,
  thorn: thorn$1,
  tilde,
  Tilde,
  TildeEqual,
  TildeFullEqual,
  TildeTilde,
  timesbar,
  timesb,
  times: times$1,
  timesd,
  tint,
  toea,
  topbot,
  topcir,
  top,
  Topf,
  topf,
  topfork,
  tosa,
  tprime,
  trade,
  TRADE,
  triangle,
  triangledown,
  triangleleft,
  trianglelefteq,
  triangleq,
  triangleright,
  trianglerighteq,
  tridot,
  trie,
  triminus,
  TripleDot,
  triplus,
  trisb,
  tritime,
  trpezium,
  Tscr,
  tscr,
  TScy,
  tscy,
  TSHcy,
  tshcy,
  Tstrok,
  tstrok,
  twixt,
  twoheadleftarrow,
  twoheadrightarrow,
  Uacute: Uacute$1,
  uacute: uacute$1,
  uarr,
  Uarr,
  uArr,
  Uarrocir,
  Ubrcy,
  ubrcy,
  Ubreve,
  ubreve,
  Ucirc: Ucirc$1,
  ucirc: ucirc$1,
  Ucy,
  ucy,
  udarr,
  Udblac,
  udblac,
  udhar,
  ufisht,
  Ufr,
  ufr,
  Ugrave: Ugrave$1,
  ugrave: ugrave$1,
  uHar,
  uharl,
  uharr,
  uhblk,
  ulcorn,
  ulcorner,
  ulcrop,
  ultri,
  Umacr,
  umacr,
  uml: uml$1,
  UnderBar,
  UnderBrace,
  UnderBracket,
  UnderParenthesis,
  Union,
  UnionPlus,
  Uogon,
  uogon,
  Uopf,
  uopf,
  UpArrowBar,
  uparrow,
  UpArrow,
  Uparrow,
  UpArrowDownArrow,
  updownarrow,
  UpDownArrow,
  Updownarrow,
  UpEquilibrium,
  upharpoonleft,
  upharpoonright,
  uplus,
  UpperLeftArrow,
  UpperRightArrow,
  upsi,
  Upsi,
  upsih,
  Upsilon,
  upsilon,
  UpTeeArrow,
  UpTee,
  upuparrows,
  urcorn,
  urcorner,
  urcrop,
  Uring,
  uring,
  urtri,
  Uscr,
  uscr,
  utdot,
  Utilde,
  utilde,
  utri,
  utrif,
  uuarr,
  Uuml: Uuml$1,
  uuml: uuml$1,
  uwangle,
  vangrt,
  varepsilon,
  varkappa,
  varnothing,
  varphi,
  varpi,
  varpropto,
  varr,
  vArr,
  varrho,
  varsigma,
  varsubsetneq,
  varsubsetneqq,
  varsupsetneq,
  varsupsetneqq,
  vartheta,
  vartriangleleft,
  vartriangleright,
  vBar,
  Vbar,
  vBarv,
  Vcy,
  vcy,
  vdash,
  vDash,
  Vdash,
  VDash,
  Vdashl,
  veebar,
  vee,
  Vee,
  veeeq,
  vellip,
  verbar,
  Verbar,
  vert,
  Vert,
  VerticalBar,
  VerticalLine,
  VerticalSeparator,
  VerticalTilde,
  VeryThinSpace,
  Vfr,
  vfr,
  vltri,
  vnsub,
  vnsup,
  Vopf,
  vopf,
  vprop,
  vrtri,
  Vscr,
  vscr,
  vsubnE,
  vsubne,
  vsupnE,
  vsupne,
  Vvdash,
  vzigzag,
  Wcirc,
  wcirc,
  wedbar,
  wedge,
  Wedge,
  wedgeq,
  weierp,
  Wfr,
  wfr,
  Wopf,
  wopf,
  wp,
  wr,
  wreath,
  Wscr,
  wscr,
  xcap,
  xcirc,
  xcup,
  xdtri,
  Xfr,
  xfr,
  xharr,
  xhArr,
  Xi,
  xi,
  xlarr,
  xlArr,
  xmap,
  xnis,
  xodot,
  Xopf,
  xopf,
  xoplus,
  xotime,
  xrarr,
  xrArr,
  Xscr,
  xscr,
  xsqcup,
  xuplus,
  xutri,
  xvee,
  xwedge,
  Yacute: Yacute$1,
  yacute: yacute$1,
  YAcy,
  yacy,
  Ycirc,
  ycirc,
  Ycy,
  ycy,
  yen: yen$1,
  Yfr,
  yfr,
  YIcy,
  yicy,
  Yopf,
  yopf,
  Yscr,
  yscr,
  YUcy,
  yucy,
  yuml: yuml$1,
  Yuml,
  Zacute,
  zacute,
  Zcaron,
  zcaron,
  Zcy,
  zcy,
  Zdot,
  zdot,
  zeetrf,
  ZeroWidthSpace,
  Zeta,
  zeta,
  zfr,
  Zfr,
  ZHcy,
  zhcy,
  zigrarr,
  zopf,
  Zopf,
  Zscr,
  zscr,
  zwj,
  zwnj
};
var Aacute = "\xC1";
var aacute = "\xE1";
var Acirc = "\xC2";
var acirc = "\xE2";
var acute = "\xB4";
var AElig = "\xC6";
var aelig = "\xE6";
var Agrave = "\xC0";
var agrave = "\xE0";
var amp$1 = "&";
var AMP = "&";
var Aring = "\xC5";
var aring = "\xE5";
var Atilde = "\xC3";
var atilde = "\xE3";
var Auml = "\xC4";
var auml = "\xE4";
var brvbar = "\xA6";
var Ccedil = "\xC7";
var ccedil = "\xE7";
var cedil = "\xB8";
var cent = "\xA2";
var copy2 = "\xA9";
var COPY = "\xA9";
var curren = "\xA4";
var deg = "\xB0";
var divide = "\xF7";
var Eacute = "\xC9";
var eacute = "\xE9";
var Ecirc = "\xCA";
var ecirc = "\xEA";
var Egrave = "\xC8";
var egrave = "\xE8";
var ETH = "\xD0";
var eth = "\xF0";
var Euml = "\xCB";
var euml = "\xEB";
var frac12 = "\xBD";
var frac14 = "\xBC";
var frac34 = "\xBE";
var gt$1 = ">";
var GT = ">";
var Iacute = "\xCD";
var iacute = "\xED";
var Icirc = "\xCE";
var icirc = "\xEE";
var iexcl = "\xA1";
var Igrave = "\xCC";
var igrave = "\xEC";
var iquest = "\xBF";
var Iuml = "\xCF";
var iuml = "\xEF";
var laquo = "\xAB";
var lt$1 = "<";
var LT = "<";
var macr = "\xAF";
var micro = "\xB5";
var middot = "\xB7";
var nbsp = "\xA0";
var not = "\xAC";
var Ntilde = "\xD1";
var ntilde = "\xF1";
var Oacute = "\xD3";
var oacute = "\xF3";
var Ocirc = "\xD4";
var ocirc = "\xF4";
var Ograve = "\xD2";
var ograve = "\xF2";
var ordf = "\xAA";
var ordm = "\xBA";
var Oslash = "\xD8";
var oslash = "\xF8";
var Otilde = "\xD5";
var otilde = "\xF5";
var Ouml = "\xD6";
var ouml = "\xF6";
var para = "\xB6";
var plusmn = "\xB1";
var pound = "\xA3";
var quot$1 = '"';
var QUOT = '"';
var raquo = "\xBB";
var reg = "\xAE";
var REG = "\xAE";
var sect = "\xA7";
var shy = "\xAD";
var sup1 = "\xB9";
var sup2 = "\xB2";
var sup3 = "\xB3";
var szlig = "\xDF";
var THORN = "\xDE";
var thorn = "\xFE";
var times = "\xD7";
var Uacute = "\xDA";
var uacute = "\xFA";
var Ucirc = "\xDB";
var ucirc = "\xFB";
var Ugrave = "\xD9";
var ugrave = "\xF9";
var uml = "\xA8";
var Uuml = "\xDC";
var uuml = "\xFC";
var Yacute = "\xDD";
var yacute = "\xFD";
var yen = "\xA5";
var yuml = "\xFF";
var require$$1 = {
  Aacute,
  aacute,
  Acirc,
  acirc,
  acute,
  AElig,
  aelig,
  Agrave,
  agrave,
  amp: amp$1,
  AMP,
  Aring,
  aring,
  Atilde,
  atilde,
  Auml,
  auml,
  brvbar,
  Ccedil,
  ccedil,
  cedil,
  cent,
  copy: copy2,
  COPY,
  curren,
  deg,
  divide,
  Eacute,
  eacute,
  Ecirc,
  ecirc,
  Egrave,
  egrave,
  ETH,
  eth,
  Euml,
  euml,
  frac12,
  frac14,
  frac34,
  gt: gt$1,
  GT,
  Iacute,
  iacute,
  Icirc,
  icirc,
  iexcl,
  Igrave,
  igrave,
  iquest,
  Iuml,
  iuml,
  laquo,
  lt: lt$1,
  LT,
  macr,
  micro,
  middot,
  nbsp,
  not,
  Ntilde,
  ntilde,
  Oacute,
  oacute,
  Ocirc,
  ocirc,
  Ograve,
  ograve,
  ordf,
  ordm,
  Oslash,
  oslash,
  Otilde,
  otilde,
  Ouml,
  ouml,
  para,
  plusmn,
  pound,
  quot: quot$1,
  QUOT,
  raquo,
  reg,
  REG,
  sect,
  shy,
  sup1,
  sup2,
  sup3,
  szlig,
  THORN,
  thorn,
  times,
  Uacute,
  uacute,
  Ucirc,
  ucirc,
  Ugrave,
  ugrave,
  uml,
  Uuml,
  uuml,
  Yacute,
  yacute,
  yen,
  yuml
};
var amp = "&";
var apos = "'";
var gt = ">";
var lt = "<";
var quot = '"';
var require$$0$1 = {
  amp,
  apos,
  gt,
  lt,
  quot
};
var decode_codepoint = {};
var require$$0 = {
  "0": 65533,
  "128": 8364,
  "130": 8218,
  "131": 402,
  "132": 8222,
  "133": 8230,
  "134": 8224,
  "135": 8225,
  "136": 710,
  "137": 8240,
  "138": 352,
  "139": 8249,
  "140": 338,
  "142": 381,
  "145": 8216,
  "146": 8217,
  "147": 8220,
  "148": 8221,
  "149": 8226,
  "150": 8211,
  "151": 8212,
  "152": 732,
  "153": 8482,
  "154": 353,
  "155": 8250,
  "156": 339,
  "158": 382,
  "159": 376
};
var __importDefault$2 = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(decode_codepoint, "__esModule", { value: true });
var decode_json_1 = __importDefault$2(require$$0);
var fromCodePoint$2 = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  String.fromCodePoint || function(codePoint) {
    var output = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output += String.fromCharCode(codePoint);
    return output;
  }
);
function decodeCodePoint(codePoint) {
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return "\uFFFD";
  }
  if (codePoint in decode_json_1.default) {
    codePoint = decode_json_1.default[codePoint];
  }
  return fromCodePoint$2(codePoint);
}
decode_codepoint.default = decodeCodePoint;
var __importDefault$1 = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(decode, "__esModule", { value: true });
decode.decodeHTML = decode.decodeHTMLStrict = decode.decodeXML = void 0;
var entities_json_1$1 = __importDefault$1(require$$1$1);
var legacy_json_1 = __importDefault$1(require$$1);
var xml_json_1$1 = __importDefault$1(require$$0$1);
var decode_codepoint_1 = __importDefault$1(decode_codepoint);
var strictEntityRe = /&(?:[a-zA-Z0-9]+|#[xX][\da-fA-F]+|#\d+);/g;
decode.decodeXML = getStrictDecoder(xml_json_1$1.default);
decode.decodeHTMLStrict = getStrictDecoder(entities_json_1$1.default);
function getStrictDecoder(map3) {
  var replace2 = getReplacer(map3);
  return function(str) {
    return String(str).replace(strictEntityRe, replace2);
  };
}
var sorter = function(a, b) {
  return a < b ? 1 : -1;
};
decode.decodeHTML = (function() {
  var legacy = Object.keys(legacy_json_1.default).sort(sorter);
  var keys2 = Object.keys(entities_json_1$1.default).sort(sorter);
  for (var i = 0, j = 0; i < keys2.length; i++) {
    if (legacy[j] === keys2[i]) {
      keys2[i] += ";?";
      j++;
    } else {
      keys2[i] += ";";
    }
  }
  var re = new RegExp("&(?:" + keys2.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g");
  var replace2 = getReplacer(entities_json_1$1.default);
  function replacer(str) {
    if (str.substr(-1) !== ";")
      str += ";";
    return replace2(str);
  }
  return function(str) {
    return String(str).replace(re, replacer);
  };
})();
function getReplacer(map3) {
  return function replace2(str) {
    if (str.charAt(1) === "#") {
      var secondChar = str.charAt(2);
      if (secondChar === "X" || secondChar === "x") {
        return decode_codepoint_1.default(parseInt(str.substr(3), 16));
      }
      return decode_codepoint_1.default(parseInt(str.substr(2), 10));
    }
    return map3[str.slice(1, -1)] || str;
  };
}
var encode = {};
var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(encode, "__esModule", { value: true });
encode.escapeUTF8 = encode.escape = encode.encodeNonAsciiHTML = encode.encodeHTML = encode.encodeXML = void 0;
var xml_json_1 = __importDefault(require$$0$1);
var inverseXML = getInverseObj(xml_json_1.default);
var xmlReplacer = getInverseReplacer(inverseXML);
encode.encodeXML = getASCIIEncoder(inverseXML);
var entities_json_1 = __importDefault(require$$1$1);
var inverseHTML = getInverseObj(entities_json_1.default);
var htmlReplacer = getInverseReplacer(inverseHTML);
encode.encodeHTML = getInverse(inverseHTML, htmlReplacer);
encode.encodeNonAsciiHTML = getASCIIEncoder(inverseHTML);
function getInverseObj(obj) {
  return Object.keys(obj).sort().reduce(function(inverse, name) {
    inverse[obj[name]] = "&" + name + ";";
    return inverse;
  }, {});
}
function getInverseReplacer(inverse) {
  var single = [];
  var multiple = [];
  for (var _i = 0, _a = Object.keys(inverse); _i < _a.length; _i++) {
    var k = _a[_i];
    if (k.length === 1) {
      single.push("\\" + k);
    } else {
      multiple.push(k);
    }
  }
  single.sort();
  for (var start = 0; start < single.length - 1; start++) {
    var end = start;
    while (end < single.length - 1 && single[end].charCodeAt(1) + 1 === single[end + 1].charCodeAt(1)) {
      end += 1;
    }
    var count = 1 + end - start;
    if (count < 3)
      continue;
    single.splice(start, count, single[start] + "-" + single[end]);
  }
  multiple.unshift("[" + single.join("") + "]");
  return new RegExp(multiple.join("|"), "g");
}
var reNonASCII = /(?:[\x80-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g;
var getCodePoint = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  String.prototype.codePointAt != null ? (
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    function(str) {
      return str.codePointAt(0);
    }
  ) : (
    // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
    function(c) {
      return (c.charCodeAt(0) - 55296) * 1024 + c.charCodeAt(1) - 56320 + 65536;
    }
  )
);
function singleCharReplacer(c) {
  return "&#x" + (c.length > 1 ? getCodePoint(c) : c.charCodeAt(0)).toString(16).toUpperCase() + ";";
}
function getInverse(inverse, re) {
  return function(data) {
    return data.replace(re, function(name) {
      return inverse[name];
    }).replace(reNonASCII, singleCharReplacer);
  };
}
var reEscapeChars = new RegExp(xmlReplacer.source + "|" + reNonASCII.source, "g");
function escape(data) {
  return data.replace(reEscapeChars, singleCharReplacer);
}
encode.escape = escape;
function escapeUTF8(data) {
  return data.replace(xmlReplacer, singleCharReplacer);
}
encode.escapeUTF8 = escapeUTF8;
function getASCIIEncoder(obj) {
  return function(data) {
    return data.replace(reEscapeChars, function(c) {
      return obj[c] || singleCharReplacer(c);
    });
  };
}
(function(exports) {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.decodeXMLStrict = exports.decodeHTML5Strict = exports.decodeHTML4Strict = exports.decodeHTML5 = exports.decodeHTML4 = exports.decodeHTMLStrict = exports.decodeHTML = exports.decodeXML = exports.encodeHTML5 = exports.encodeHTML4 = exports.escapeUTF8 = exports.escape = exports.encodeNonAsciiHTML = exports.encodeHTML = exports.encodeXML = exports.encode = exports.decodeStrict = exports.decode = void 0;
  var decode_1 = decode;
  var encode_12 = encode;
  function decode$1(data, level) {
    return (!level || level <= 0 ? decode_1.decodeXML : decode_1.decodeHTML)(data);
  }
  exports.decode = decode$1;
  function decodeStrict(data, level) {
    return (!level || level <= 0 ? decode_1.decodeXML : decode_1.decodeHTMLStrict)(data);
  }
  exports.decodeStrict = decodeStrict;
  function encode$12(data, level) {
    return (!level || level <= 0 ? encode_12.encodeXML : encode_12.encodeHTML)(data);
  }
  exports.encode = encode$12;
  var encode_2 = encode;
  Object.defineProperty(exports, "encodeXML", { enumerable: true, get: function() {
    return encode_2.encodeXML;
  } });
  Object.defineProperty(exports, "encodeHTML", { enumerable: true, get: function() {
    return encode_2.encodeHTML;
  } });
  Object.defineProperty(exports, "encodeNonAsciiHTML", { enumerable: true, get: function() {
    return encode_2.encodeNonAsciiHTML;
  } });
  Object.defineProperty(exports, "escape", { enumerable: true, get: function() {
    return encode_2.escape;
  } });
  Object.defineProperty(exports, "escapeUTF8", { enumerable: true, get: function() {
    return encode_2.escapeUTF8;
  } });
  Object.defineProperty(exports, "encodeHTML4", { enumerable: true, get: function() {
    return encode_2.encodeHTML;
  } });
  Object.defineProperty(exports, "encodeHTML5", { enumerable: true, get: function() {
    return encode_2.encodeHTML;
  } });
  var decode_2 = decode;
  Object.defineProperty(exports, "decodeXML", { enumerable: true, get: function() {
    return decode_2.decodeXML;
  } });
  Object.defineProperty(exports, "decodeHTML", { enumerable: true, get: function() {
    return decode_2.decodeHTML;
  } });
  Object.defineProperty(exports, "decodeHTMLStrict", { enumerable: true, get: function() {
    return decode_2.decodeHTMLStrict;
  } });
  Object.defineProperty(exports, "decodeHTML4", { enumerable: true, get: function() {
    return decode_2.decodeHTML;
  } });
  Object.defineProperty(exports, "decodeHTML5", { enumerable: true, get: function() {
    return decode_2.decodeHTML;
  } });
  Object.defineProperty(exports, "decodeHTML4Strict", { enumerable: true, get: function() {
    return decode_2.decodeHTMLStrict;
  } });
  Object.defineProperty(exports, "decodeHTML5Strict", { enumerable: true, get: function() {
    return decode_2.decodeHTMLStrict;
  } });
  Object.defineProperty(exports, "decodeXMLStrict", { enumerable: true, get: function() {
    return decode_2.decodeXML;
  } });
})(lib);
var ENTITY = "&(?:#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});";
var C_BACKSLASH$1 = 92;
var reBackslashOrAmp = /[\\&]/;
var ESCAPABLE = "[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]";
var reEntityOrEscapedChar = new RegExp("\\\\" + ESCAPABLE + "|" + ENTITY, "gi");
var XMLSPECIAL = '[&<>"]';
var reXmlSpecial = new RegExp(XMLSPECIAL, "g");
var unescapeChar = function(s) {
  if (s.charCodeAt(0) === C_BACKSLASH$1) {
    return s.charAt(1);
  }
  return lib.decodeHTML(s);
};
function unescapeString(s) {
  if (reBackslashOrAmp.test(s)) {
    return s.replace(reEntityOrEscapedChar, unescapeChar);
  }
  return s;
}
function normalizeURI(uri) {
  try {
    return encode_1(uri);
  } catch (err) {
    return uri;
  }
}
function replaceUnsafeChar(s) {
  switch (s) {
    case "&":
      return "&amp;";
    case "<":
      return "&lt;";
    case ">":
      return "&gt;";
    case '"':
      return "&quot;";
    default:
      return s;
  }
}
function escapeXml(s) {
  if (reXmlSpecial.test(s)) {
    return s.replace(reXmlSpecial, replaceUnsafeChar);
  }
  return s;
}
function repeat(str, count) {
  var arr = [];
  for (var i = 0; i < count; i++) {
    arr.push(str);
  }
  return arr.join("");
}
function isEmpty(str) {
  if (!str) {
    return true;
  }
  return !/[^ \t]+/.test(str);
}
var NodeWalker = (
  /** @class */
  (function() {
    function NodeWalker2(root) {
      this.current = root;
      this.root = root;
      this.entering = true;
    }
    NodeWalker2.prototype.next = function() {
      var cur = this.current;
      var entering = this.entering;
      if (cur === null) {
        return null;
      }
      var container = isContainer$1(cur);
      if (entering && container) {
        if (cur.firstChild) {
          this.current = cur.firstChild;
          this.entering = true;
        } else {
          this.entering = false;
        }
      } else if (cur === this.root) {
        this.current = null;
      } else if (cur.next === null) {
        this.current = cur.parent;
        this.entering = false;
      } else {
        this.current = cur.next;
        this.entering = true;
      }
      return { entering, node: cur };
    };
    NodeWalker2.prototype.resumeAt = function(node, entering) {
      this.current = node;
      this.entering = entering === true;
    };
    return NodeWalker2;
  })()
);
function isContainer$1(node) {
  switch (node.type) {
    case "document":
    case "blockQuote":
    case "list":
    case "item":
    case "paragraph":
    case "heading":
    case "emph":
    case "strong":
    case "strike":
    case "link":
    case "image":
    case "table":
    case "tableHead":
    case "tableBody":
    case "tableRow":
    case "tableCell":
    case "tableDelimRow":
    case "customInline":
      return true;
    default:
      return false;
  }
}
var lastNodeId = 1;
var nodeMap = {};
function getNodeById(id) {
  return nodeMap[id];
}
function removeNodeById(id) {
  delete nodeMap[id];
}
function removeAllNode() {
  nodeMap = {};
}
var Node$1 = (
  /** @class */
  (function() {
    function Node3(nodeType, sourcepos) {
      this.parent = null;
      this.prev = null;
      this.next = null;
      this.firstChild = null;
      this.lastChild = null;
      this.literal = null;
      if (nodeType === "document") {
        this.id = -1;
      } else {
        this.id = lastNodeId++;
      }
      this.type = nodeType;
      this.sourcepos = sourcepos;
      nodeMap[this.id] = this;
    }
    Node3.prototype.isContainer = function() {
      return isContainer$1(this);
    };
    Node3.prototype.unlink = function() {
      if (this.prev) {
        this.prev.next = this.next;
      } else if (this.parent) {
        this.parent.firstChild = this.next;
      }
      if (this.next) {
        this.next.prev = this.prev;
      } else if (this.parent) {
        this.parent.lastChild = this.prev;
      }
      this.parent = null;
      this.next = null;
      this.prev = null;
    };
    Node3.prototype.replaceWith = function(node) {
      this.insertBefore(node);
      this.unlink();
    };
    Node3.prototype.insertAfter = function(sibling) {
      sibling.unlink();
      sibling.next = this.next;
      if (sibling.next) {
        sibling.next.prev = sibling;
      }
      sibling.prev = this;
      this.next = sibling;
      if (this.parent) {
        sibling.parent = this.parent;
        if (!sibling.next) {
          sibling.parent.lastChild = sibling;
        }
      }
    };
    Node3.prototype.insertBefore = function(sibling) {
      sibling.unlink();
      sibling.prev = this.prev;
      if (sibling.prev) {
        sibling.prev.next = sibling;
      }
      sibling.next = this;
      this.prev = sibling;
      sibling.parent = this.parent;
      if (!sibling.prev) {
        sibling.parent.firstChild = sibling;
      }
    };
    Node3.prototype.appendChild = function(child) {
      child.unlink();
      child.parent = this;
      if (this.lastChild) {
        this.lastChild.next = child;
        child.prev = this.lastChild;
        this.lastChild = child;
      } else {
        this.firstChild = child;
        this.lastChild = child;
      }
    };
    Node3.prototype.prependChild = function(child) {
      child.unlink();
      child.parent = this;
      if (this.firstChild) {
        this.firstChild.prev = child;
        child.next = this.firstChild;
        this.firstChild = child;
      } else {
        this.firstChild = child;
        this.lastChild = child;
      }
    };
    Node3.prototype.walker = function() {
      return new NodeWalker(this);
    };
    return Node3;
  })()
);
var BlockNode = (
  /** @class */
  (function(_super) {
    __extends(BlockNode2, _super);
    function BlockNode2(nodeType, sourcepos) {
      var _this = _super.call(this, nodeType, sourcepos) || this;
      _this.open = true;
      _this.lineOffsets = null;
      _this.stringContent = null;
      _this.lastLineBlank = false;
      _this.lastLineChecked = false;
      _this.type = nodeType;
      return _this;
    }
    return BlockNode2;
  })(Node$1)
);
var ListNode = (
  /** @class */
  (function(_super) {
    __extends(ListNode2, _super);
    function ListNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.listData = null;
      return _this;
    }
    return ListNode2;
  })(BlockNode)
);
var HeadingNode = (
  /** @class */
  (function(_super) {
    __extends(HeadingNode2, _super);
    function HeadingNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.level = 0;
      _this.headingType = "atx";
      return _this;
    }
    return HeadingNode2;
  })(BlockNode)
);
var CodeBlockNode = (
  /** @class */
  (function(_super) {
    __extends(CodeBlockNode2, _super);
    function CodeBlockNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.isFenced = false;
      _this.fenceChar = null;
      _this.fenceLength = 0;
      _this.fenceOffset = -1;
      _this.info = null;
      _this.infoPadding = 0;
      return _this;
    }
    return CodeBlockNode2;
  })(BlockNode)
);
var TableNode = (
  /** @class */
  (function(_super) {
    __extends(TableNode2, _super);
    function TableNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.columns = [];
      return _this;
    }
    return TableNode2;
  })(BlockNode)
);
var TableCellNode = (
  /** @class */
  (function(_super) {
    __extends(TableCellNode2, _super);
    function TableCellNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.startIdx = 0;
      _this.endIdx = 0;
      _this.paddingLeft = 0;
      _this.paddingRight = 0;
      _this.ignored = false;
      return _this;
    }
    return TableCellNode2;
  })(BlockNode)
);
var RefDefNode = (
  /** @class */
  (function(_super) {
    __extends(RefDefNode2, _super);
    function RefDefNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.title = "";
      _this.dest = "";
      _this.label = "";
      return _this;
    }
    return RefDefNode2;
  })(BlockNode)
);
var CustomBlockNode = (
  /** @class */
  (function(_super) {
    __extends(CustomBlockNode2, _super);
    function CustomBlockNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.syntaxLength = 0;
      _this.offset = -1;
      _this.info = "";
      return _this;
    }
    return CustomBlockNode2;
  })(BlockNode)
);
var HtmlBlockNode = (
  /** @class */
  (function(_super) {
    __extends(HtmlBlockNode2, _super);
    function HtmlBlockNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.htmlBlockType = -1;
      return _this;
    }
    return HtmlBlockNode2;
  })(BlockNode)
);
var LinkNode = (
  /** @class */
  (function(_super) {
    __extends(LinkNode2, _super);
    function LinkNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.destination = null;
      _this.title = null;
      _this.extendedAutolink = false;
      return _this;
    }
    return LinkNode2;
  })(Node$1)
);
var CodeNode = (
  /** @class */
  (function(_super) {
    __extends(CodeNode2, _super);
    function CodeNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.tickCount = 0;
      return _this;
    }
    return CodeNode2;
  })(Node$1)
);
var CustomInlineNode = (
  /** @class */
  (function(_super) {
    __extends(CustomInlineNode2, _super);
    function CustomInlineNode2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.info = "";
      return _this;
    }
    return CustomInlineNode2;
  })(Node$1)
);
function createNode$1(type, sourcepos) {
  switch (type) {
    case "heading":
      return new HeadingNode(type, sourcepos);
    case "list":
    case "item":
      return new ListNode(type, sourcepos);
    case "link":
    case "image":
      return new LinkNode(type, sourcepos);
    case "codeBlock":
      return new CodeBlockNode(type, sourcepos);
    case "htmlBlock":
      return new HtmlBlockNode(type, sourcepos);
    case "table":
      return new TableNode(type, sourcepos);
    case "tableCell":
      return new TableCellNode(type, sourcepos);
    case "document":
    case "paragraph":
    case "blockQuote":
    case "thematicBreak":
    case "tableRow":
    case "tableBody":
    case "tableHead":
    case "frontMatter":
      return new BlockNode(type, sourcepos);
    case "code":
      return new CodeNode(type, sourcepos);
    case "refDef":
      return new RefDefNode(type, sourcepos);
    case "customBlock":
      return new CustomBlockNode(type, sourcepos);
    case "customInline":
      return new CustomInlineNode(type, sourcepos);
    default:
      return new Node$1(type, sourcepos);
  }
}
function isCodeBlock(node) {
  return node.type === "codeBlock";
}
function isHtmlBlock(node) {
  return node.type === "htmlBlock";
}
function isHeading(node) {
  return node.type === "heading";
}
function isList(node) {
  return node.type === "list";
}
function isTable(node) {
  return node.type === "table";
}
function isRefDef(node) {
  return node.type === "refDef";
}
function isCustomBlock(node) {
  return node.type === "customBlock";
}
function isCustomInline(node) {
  return node.type === "customInline";
}
function text$1(s, sourcepos) {
  var node = createNode$1("text", sourcepos);
  node.literal = s;
  return node;
}
var TAGNAME = "[A-Za-z][A-Za-z0-9-]*";
var ATTRIBUTENAME = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
var UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+";
var SINGLEQUOTEDVALUE = "'[^']*'";
var DOUBLEQUOTEDVALUE = '"[^"]*"';
var ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE + "|" + DOUBLEQUOTEDVALUE + ")";
var ATTRIBUTEVALUESPEC = "(?:\\s*=\\s*" + ATTRIBUTEVALUE + ")";
var ATTRIBUTE = "(?:\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + "?)";
var OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*\\s*/?>";
var CLOSETAG = "</" + TAGNAME + "\\s*[>]";
var HTMLCOMMENT = "<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->";
var PROCESSINGINSTRUCTION = "[<][?].*?[?][>]";
var DECLARATION = "<![A-Z]+\\s+[^>]*>";
var CDATA = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
var HTMLTAG = "(?:" + OPENTAG + "|" + CLOSETAG + "|" + HTMLCOMMENT + "|" + PROCESSINGINSTRUCTION + "|" + DECLARATION + "|" + CDATA + ")";
var reHtmlTag = new RegExp("^" + HTMLTAG, "i");
var fromCodePoint;
if (String.fromCodePoint) {
  fromCodePoint = function(_) {
    try {
      return String.fromCodePoint(_);
    } catch (e) {
      if (e instanceof RangeError) {
        return String.fromCharCode(65533);
      }
      throw e;
    }
  };
} else {
  stringFromCharCode_1 = String.fromCharCode;
  floor_1 = Math.floor;
  fromCodePoint = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var MAX_SIZE = 16384;
    var codeUnits = [];
    var highSurrogate;
    var lowSurrogate;
    var index2 = -1;
    var length = args.length;
    if (!length) {
      return "";
    }
    var result = "";
    while (++index2 < length) {
      var codePoint = Number(args[index2]);
      if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
      codePoint < 0 || // not a valid Unicode code point
      codePoint > 1114111 || // not a valid Unicode code point
      floor_1(codePoint) !== codePoint) {
        return String.fromCharCode(65533);
      }
      if (codePoint <= 65535) {
        codeUnits.push(codePoint);
      } else {
        codePoint -= 65536;
        highSurrogate = (codePoint >> 10) + 55296;
        lowSurrogate = codePoint % 1024 + 56320;
        codeUnits.push(highSurrogate, lowSurrogate);
      }
      if (index2 + 1 === length || codeUnits.length > MAX_SIZE) {
        result += stringFromCharCode_1.apply(void 0, codeUnits);
        codeUnits.length = 0;
      }
    }
    return result;
  };
}
var stringFromCharCode_1;
var floor_1;
var fromCodePoint$1 = fromCodePoint;
var DOMAIN = "(?:[w-]+.)*[A-Za-z0-9-]+.[A-Za-z0-9-]+";
var PATH = "[^<\\s]*[^<?!.,:*_?~\\s]";
var EMAIL = "[\\w.+-]+@(?:[\\w-]+\\.)+[\\w-]+";
function trimUnmatchedTrailingParens(source) {
  var trailingParen = /\)+$/.exec(source);
  if (trailingParen) {
    var count = 0;
    for (var _i = 0, source_1 = source; _i < source_1.length; _i++) {
      var ch = source_1[_i];
      if (ch === "(") {
        if (count < 0) {
          count = 1;
        } else {
          count += 1;
        }
      } else if (ch === ")") {
        count -= 1;
      }
    }
    if (count < 0) {
      var trimCount = Math.min(-count, trailingParen[0].length);
      return source.substring(0, source.length - trimCount);
    }
  }
  return source;
}
function trimTrailingEntity(source) {
  return source.replace(/&[A-Za-z0-9]+;$/, "");
}
function parseEmailLink(source) {
  var reEmailLink = new RegExp(EMAIL, "g");
  var result = [];
  var m;
  while (m = reEmailLink.exec(source)) {
    var text_1 = m[0];
    if (!/[_-]+$/.test(text_1)) {
      result.push({
        text: text_1,
        range: [m.index, m.index + text_1.length - 1],
        url: "mailto:" + text_1
      });
    }
  }
  return result;
}
function parseUrlLink(source) {
  var reWwwAutolink = new RegExp("(www|https?://)." + DOMAIN + PATH, "g");
  var result = [];
  var m;
  while (m = reWwwAutolink.exec(source)) {
    var text_2 = trimTrailingEntity(trimUnmatchedTrailingParens(m[0]));
    var scheme = m[1] === "www" ? "http://" : "";
    result.push({
      text: text_2,
      range: [m.index, m.index + text_2.length - 1],
      url: "" + scheme + text_2
    });
  }
  return result;
}
function baseAutolinkParser(source) {
  return __spreadArray(__spreadArray([], parseUrlLink(source)), parseEmailLink(source)).sort(function(a, b) {
    return a.range[0] - b.range[0];
  });
}
function convertExtAutoLinks(walker, autolinkParser) {
  if (typeof autolinkParser === "boolean") {
    autolinkParser = baseAutolinkParser;
  }
  var event;
  var _loop_1 = function() {
    var entering = event.entering, node = event.node;
    if (entering && node.type === "text" && node.parent.type !== "link") {
      var literal = node.literal;
      var linkInfos = autolinkParser(literal);
      if (!linkInfos || !linkInfos.length) {
        return "continue";
      }
      var lastIdx = 0;
      var _a = node.sourcepos[0], lineNum_1 = _a[0], chPos_1 = _a[1];
      var sourcepos = function(startIdx, endIdx) {
        return [
          [lineNum_1, chPos_1 + startIdx],
          [lineNum_1, chPos_1 + endIdx]
        ];
      };
      var newNodes = [];
      for (var _i = 0, linkInfos_1 = linkInfos; _i < linkInfos_1.length; _i++) {
        var _b = linkInfos_1[_i], range2 = _b.range, url = _b.url, linkText = _b.text;
        if (range2[0] > lastIdx) {
          newNodes.push(text$1(literal.substring(lastIdx, range2[0]), sourcepos(lastIdx, range2[0] - 1)));
        }
        var linkNode = createNode$1("link", sourcepos.apply(void 0, range2));
        linkNode.appendChild(text$1(linkText, sourcepos.apply(void 0, range2)));
        linkNode.destination = url;
        linkNode.extendedAutolink = true;
        newNodes.push(linkNode);
        lastIdx = range2[1] + 1;
      }
      if (lastIdx < literal.length) {
        newNodes.push(text$1(literal.substring(lastIdx), sourcepos(lastIdx, literal.length - 1)));
      }
      for (var _c = 0, newNodes_1 = newNodes; _c < newNodes_1.length; _c++) {
        var newNode = newNodes_1[_c];
        node.insertBefore(newNode);
      }
      node.unlink();
    }
  };
  while (event = walker.next()) {
    _loop_1();
  }
}
function last(arr) {
  return arr[arr.length - 1];
}
function normalizeReference(str) {
  return str.slice(1, str.length - 1).trim().replace(/[ \t\r\n]+/, " ").toLowerCase().toUpperCase();
}
function iterateObject(obj, iteratee) {
  Object.keys(obj).forEach(function(key) {
    iteratee(key, obj[key]);
  });
}
function omit(obj) {
  var propNames = [];
  for (var _i = 1; _i < arguments.length; _i++) {
    propNames[_i - 1] = arguments[_i];
  }
  var resultMap = __assign({}, obj);
  propNames.forEach(function(key) {
    delete resultMap[key];
  });
  return resultMap;
}
function isEmptyObj(obj) {
  return !Object.keys(obj).length;
}
function clearObj(obj) {
  Object.keys(obj).forEach(function(key) {
    delete obj[key];
  });
}
var C_NEWLINE = 10;
var C_ASTERISK = 42;
var C_UNDERSCORE = 95;
var C_BACKTICK = 96;
var C_OPEN_BRACKET$1 = 91;
var C_CLOSE_BRACKET = 93;
var C_TILDE = 126;
var C_LESSTHAN$1 = 60;
var C_BANG = 33;
var C_BACKSLASH = 92;
var C_AMPERSAND = 38;
var C_OPEN_PAREN = 40;
var C_CLOSE_PAREN = 41;
var C_COLON = 58;
var C_SINGLEQUOTE = 39;
var C_DOUBLEQUOTE = 34;
var C_DOLLAR = 36;
var ESCAPED_CHAR = "\\\\" + ESCAPABLE;
var rePunctuation = new RegExp(/[!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~\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]/);
var reLinkTitle = new RegExp('^(?:"(' + ESCAPED_CHAR + '|[^"\\x00])*"|' + ("'(" + ESCAPED_CHAR + "|[^'\\x00])*'") + "|" + ("\\((" + ESCAPED_CHAR + "|[^()\\x00])*\\))"));
var reLinkDestinationBraces = /^(?:<(?:[^<>\n\\\x00]|\\.)*>)/;
var reEscapable = new RegExp("^" + ESCAPABLE);
var reEntityHere = new RegExp("^" + ENTITY, "i");
var reTicks = /`+/;
var reTicksHere = /^`+/;
var reEllipses = /\.\.\./g;
var reDash = /--+/g;
var reEmailAutolink = /^<([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])?)*)>/;
var reAutolink = /^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>/i;
var reSpnl = /^ *(?:\n *)?/;
var reWhitespaceChar = /^[ \t\n\x0b\x0c\x0d]/;
var reUnicodeWhitespaceChar = /^\s/;
var reFinalSpace = / *$/;
var reInitialSpace = /^ */;
var reSpaceAtEndOfLine = /^ *(?:\n|$)/;
var reLinkLabel = /^\[(?:[^\\\[\]]|\\.){0,1000}\]/;
var reMain = /^[^\n`\[\]\\!<&*_'"~$]+/m;
var InlineParser = (
  /** @class */
  (function() {
    function InlineParser2(options) {
      this.subject = "";
      this.delimiters = null;
      this.brackets = null;
      this.pos = 0;
      this.lineStartNum = 0;
      this.lineIdx = 0;
      this.lineOffsets = [0];
      this.linePosOffset = 0;
      this.refMap = {};
      this.refLinkCandidateMap = {};
      this.refDefCandidateMap = {};
      this.options = options;
    }
    InlineParser2.prototype.sourcepos = function(start, end) {
      var linePosOffset = this.linePosOffset + this.lineOffsets[this.lineIdx];
      var lineNum = this.lineStartNum + this.lineIdx;
      var startpos = [lineNum, start + linePosOffset];
      if (typeof end === "number") {
        return [startpos, [lineNum, end + linePosOffset]];
      }
      return startpos;
    };
    InlineParser2.prototype.nextLine = function() {
      this.lineIdx += 1;
      this.linePosOffset = -this.pos;
    };
    InlineParser2.prototype.match = function(re) {
      var m = re.exec(this.subject.slice(this.pos));
      if (m === null) {
        return null;
      }
      this.pos += m.index + m[0].length;
      return m[0];
    };
    InlineParser2.prototype.peek = function() {
      if (this.pos < this.subject.length) {
        return this.subject.charCodeAt(this.pos);
      }
      return -1;
    };
    InlineParser2.prototype.spnl = function() {
      this.match(reSpnl);
      return true;
    };
    InlineParser2.prototype.parseBackticks = function(block2) {
      var startpos = this.pos + 1;
      var ticks = this.match(reTicksHere);
      if (ticks === null) {
        return false;
      }
      var afterOpenTicks = this.pos;
      var matched;
      while ((matched = this.match(reTicks)) !== null) {
        if (matched === ticks) {
          var contents = this.subject.slice(afterOpenTicks, this.pos - ticks.length);
          var sourcepos = this.sourcepos(startpos, this.pos);
          var lines = contents.split("\n");
          if (lines.length > 1) {
            var lastLine = last(lines);
            this.lineIdx += lines.length - 1;
            this.linePosOffset = -(this.pos - lastLine.length - ticks.length);
            sourcepos[1] = this.sourcepos(this.pos);
            contents = lines.join(" ");
          }
          var node = createNode$1("code", sourcepos);
          if (contents.length > 0 && contents.match(/[^ ]/) !== null && contents[0] == " " && contents[contents.length - 1] == " ") {
            node.literal = contents.slice(1, contents.length - 1);
          } else {
            node.literal = contents;
          }
          node.tickCount = ticks.length;
          block2.appendChild(node);
          return true;
        }
      }
      this.pos = afterOpenTicks;
      block2.appendChild(text$1(ticks, this.sourcepos(startpos, this.pos - 1)));
      return true;
    };
    InlineParser2.prototype.parseBackslash = function(block2) {
      var subj = this.subject;
      var node;
      this.pos += 1;
      var startpos = this.pos;
      if (this.peek() === C_NEWLINE) {
        this.pos += 1;
        node = createNode$1("linebreak", this.sourcepos(this.pos - 1, this.pos));
        block2.appendChild(node);
        this.nextLine();
      } else if (reEscapable.test(subj.charAt(this.pos))) {
        block2.appendChild(text$1(subj.charAt(this.pos), this.sourcepos(startpos, this.pos)));
        this.pos += 1;
      } else {
        block2.appendChild(text$1("\\", this.sourcepos(startpos, startpos)));
      }
      return true;
    };
    InlineParser2.prototype.parseAutolink = function(block2) {
      var m;
      var dest;
      var node;
      var startpos = this.pos + 1;
      if (m = this.match(reEmailAutolink)) {
        dest = m.slice(1, m.length - 1);
        node = createNode$1("link", this.sourcepos(startpos, this.pos));
        node.destination = normalizeURI("mailto:" + dest);
        node.title = "";
        node.appendChild(text$1(dest, this.sourcepos(startpos + 1, this.pos - 1)));
        block2.appendChild(node);
        return true;
      }
      if (m = this.match(reAutolink)) {
        dest = m.slice(1, m.length - 1);
        node = createNode$1("link", this.sourcepos(startpos, this.pos));
        node.destination = normalizeURI(dest);
        node.title = "";
        node.appendChild(text$1(dest, this.sourcepos(startpos + 1, this.pos - 1)));
        block2.appendChild(node);
        return true;
      }
      return false;
    };
    InlineParser2.prototype.parseHtmlTag = function(block2) {
      var startpos = this.pos + 1;
      var m = this.match(reHtmlTag);
      if (m === null) {
        return false;
      }
      var node = createNode$1("htmlInline", this.sourcepos(startpos, this.pos));
      node.literal = m;
      block2.appendChild(node);
      return true;
    };
    InlineParser2.prototype.scanDelims = function(cc) {
      var numdelims = 0;
      var startpos = this.pos;
      if (cc === C_SINGLEQUOTE || cc === C_DOUBLEQUOTE) {
        numdelims++;
        this.pos++;
      } else {
        while (this.peek() === cc) {
          numdelims++;
          this.pos++;
        }
      }
      if (numdelims === 0 || numdelims < 2 && (cc === C_TILDE || cc === C_DOLLAR)) {
        this.pos = startpos;
        return null;
      }
      var charBefore = startpos === 0 ? "\n" : this.subject.charAt(startpos - 1);
      var ccAfter = this.peek();
      var charAfter;
      if (ccAfter === -1) {
        charAfter = "\n";
      } else {
        charAfter = fromCodePoint$1(ccAfter);
      }
      var afterIsWhitespace = reUnicodeWhitespaceChar.test(charAfter);
      var afterIsPunctuation = rePunctuation.test(charAfter);
      var beforeIsWhitespace = reUnicodeWhitespaceChar.test(charBefore);
      var beforeIsPunctuation = rePunctuation.test(charBefore);
      var leftFlanking = !afterIsWhitespace && (!afterIsPunctuation || beforeIsWhitespace || beforeIsPunctuation);
      var rightFlanking = !beforeIsWhitespace && (!beforeIsPunctuation || afterIsWhitespace || afterIsPunctuation);
      var canOpen;
      var canClose;
      if (cc === C_UNDERSCORE) {
        canOpen = leftFlanking && (!rightFlanking || beforeIsPunctuation);
        canClose = rightFlanking && (!leftFlanking || afterIsPunctuation);
      } else if (cc === C_SINGLEQUOTE || cc === C_DOUBLEQUOTE) {
        canOpen = leftFlanking && !rightFlanking;
        canClose = rightFlanking;
      } else if (cc === C_DOLLAR) {
        canOpen = !afterIsWhitespace;
        canClose = !beforeIsWhitespace;
      } else {
        canOpen = leftFlanking;
        canClose = rightFlanking;
      }
      this.pos = startpos;
      return { numdelims, canOpen, canClose };
    };
    InlineParser2.prototype.handleDelim = function(cc, block2) {
      var res = this.scanDelims(cc);
      if (!res) {
        return false;
      }
      var numdelims = res.numdelims;
      var startpos = this.pos + 1;
      var contents;
      this.pos += numdelims;
      if (cc === C_SINGLEQUOTE) {
        contents = "\u2019";
      } else if (cc === C_DOUBLEQUOTE) {
        contents = "\u201C";
      } else {
        contents = this.subject.slice(startpos - 1, this.pos);
      }
      var node = text$1(contents, this.sourcepos(startpos, this.pos));
      block2.appendChild(node);
      if ((res.canOpen || res.canClose) && (this.options.smart || cc !== C_SINGLEQUOTE && cc !== C_DOUBLEQUOTE)) {
        this.delimiters = {
          cc,
          numdelims,
          origdelims: numdelims,
          node,
          previous: this.delimiters,
          next: null,
          canOpen: res.canOpen,
          canClose: res.canClose
        };
        if (this.delimiters.previous) {
          this.delimiters.previous.next = this.delimiters;
        }
      }
      return true;
    };
    InlineParser2.prototype.removeDelimiter = function(delim) {
      if (delim.previous !== null) {
        delim.previous.next = delim.next;
      }
      if (delim.next === null) {
        this.delimiters = delim.previous;
      } else {
        delim.next.previous = delim.previous;
      }
    };
    InlineParser2.prototype.removeDelimitersBetween = function(bottom2, top2) {
      if (bottom2.next !== top2) {
        bottom2.next = top2;
        top2.previous = bottom2;
      }
    };
    InlineParser2.prototype.processEmphasis = function(stackBottom) {
      var _a;
      var opener;
      var closer;
      var oldCloser;
      var openerInl, closerInl;
      var openerFound;
      var oddMatch = false;
      var openersBottom = (_a = {}, _a[C_UNDERSCORE] = [stackBottom, stackBottom, stackBottom], _a[C_ASTERISK] = [stackBottom, stackBottom, stackBottom], _a[C_SINGLEQUOTE] = [stackBottom], _a[C_DOUBLEQUOTE] = [stackBottom], _a[C_TILDE] = [stackBottom], _a[C_DOLLAR] = [stackBottom], _a);
      closer = this.delimiters;
      while (closer !== null && closer.previous !== stackBottom) {
        closer = closer.previous;
      }
      while (closer !== null) {
        var closercc = closer.cc;
        var closerEmph = closercc === C_UNDERSCORE || closercc === C_ASTERISK;
        if (!closer.canClose) {
          closer = closer.next;
        } else {
          opener = closer.previous;
          openerFound = false;
          while (opener !== null && opener !== stackBottom && opener !== openersBottom[closercc][closerEmph ? closer.origdelims % 3 : 0]) {
            oddMatch = closerEmph && (closer.canOpen || opener.canClose) && closer.origdelims % 3 !== 0 && (opener.origdelims + closer.origdelims) % 3 === 0;
            if (opener.cc === closer.cc && opener.canOpen && !oddMatch) {
              openerFound = true;
              break;
            }
            opener = opener.previous;
          }
          oldCloser = closer;
          if (closerEmph || closercc === C_TILDE || closercc === C_DOLLAR) {
            if (!openerFound) {
              closer = closer.next;
            } else if (opener) {
              var useDelims = closer.numdelims >= 2 && opener.numdelims >= 2 ? 2 : 1;
              var emptyDelims = closerEmph ? 0 : 1;
              openerInl = opener.node;
              closerInl = closer.node;
              var nodeType = closerEmph ? useDelims === 1 ? "emph" : "strong" : "strike";
              if (closercc === C_DOLLAR) {
                nodeType = "customInline";
              }
              var newNode = createNode$1(nodeType);
              var openerEndPos = openerInl.sourcepos[1];
              var closerStartPos = closerInl.sourcepos[0];
              newNode.sourcepos = [
                [openerEndPos[0], openerEndPos[1] - useDelims + 1],
                [closerStartPos[0], closerStartPos[1] + useDelims - 1]
              ];
              openerInl.sourcepos[1][1] -= useDelims;
              closerInl.sourcepos[0][1] += useDelims;
              openerInl.literal = openerInl.literal.slice(useDelims);
              closerInl.literal = closerInl.literal.slice(useDelims);
              opener.numdelims -= useDelims;
              closer.numdelims -= useDelims;
              var tmp = openerInl.next;
              var next = void 0;
              while (tmp && tmp !== closerInl) {
                next = tmp.next;
                tmp.unlink();
                newNode.appendChild(tmp);
                tmp = next;
              }
              if (closercc === C_DOLLAR) {
                var textNode = newNode.firstChild;
                var literal = textNode.literal || "";
                var info = literal.split(/\s/)[0];
                newNode.info = info;
                if (literal.length <= info.length) {
                  textNode.unlink();
                } else {
                  textNode.sourcepos[0][1] += info.length;
                  textNode.literal = literal.replace(info + " ", "");
                }
              }
              openerInl.insertAfter(newNode);
              this.removeDelimitersBetween(opener, closer);
              if (opener.numdelims <= emptyDelims) {
                if (opener.numdelims === 0) {
                  openerInl.unlink();
                }
                this.removeDelimiter(opener);
              }
              if (closer.numdelims <= emptyDelims) {
                if (closer.numdelims === 0) {
                  closerInl.unlink();
                }
                var tempstack = closer.next;
                this.removeDelimiter(closer);
                closer = tempstack;
              }
            }
          } else if (closercc === C_SINGLEQUOTE) {
            closer.node.literal = "\u2019";
            if (openerFound) {
              opener.node.literal = "\u2018";
            }
            closer = closer.next;
          } else if (closercc === C_DOUBLEQUOTE) {
            closer.node.literal = "\u201D";
            if (openerFound) {
              opener.node.literal = "\u201C";
            }
            closer = closer.next;
          }
          if (!openerFound) {
            openersBottom[closercc][closerEmph ? oldCloser.origdelims % 3 : 0] = oldCloser.previous;
            if (!oldCloser.canOpen) {
              this.removeDelimiter(oldCloser);
            }
          }
        }
      }
      while (this.delimiters !== null && this.delimiters !== stackBottom) {
        this.removeDelimiter(this.delimiters);
      }
    };
    InlineParser2.prototype.parseLinkTitle = function() {
      var title = this.match(reLinkTitle);
      if (title === null) {
        return null;
      }
      return unescapeString(title.substr(1, title.length - 2));
    };
    InlineParser2.prototype.parseLinkDestination = function() {
      var res = this.match(reLinkDestinationBraces);
      if (res === null) {
        if (this.peek() === C_LESSTHAN$1) {
          return null;
        }
        var savepos = this.pos;
        var openparens = 0;
        var c = void 0;
        while ((c = this.peek()) !== -1) {
          if (c === C_BACKSLASH && reEscapable.test(this.subject.charAt(this.pos + 1))) {
            this.pos += 1;
            if (this.peek() !== -1) {
              this.pos += 1;
            }
          } else if (c === C_OPEN_PAREN) {
            this.pos += 1;
            openparens += 1;
          } else if (c === C_CLOSE_PAREN) {
            if (openparens < 1) {
              break;
            } else {
              this.pos += 1;
              openparens -= 1;
            }
          } else if (reWhitespaceChar.exec(fromCodePoint$1(c)) !== null) {
            break;
          } else {
            this.pos += 1;
          }
        }
        if (this.pos === savepos && c !== C_CLOSE_PAREN) {
          return null;
        }
        if (openparens !== 0) {
          return null;
        }
        res = this.subject.substr(savepos, this.pos - savepos);
        return normalizeURI(unescapeString(res));
      }
      return normalizeURI(unescapeString(res.substr(1, res.length - 2)));
    };
    InlineParser2.prototype.parseLinkLabel = function() {
      var m = this.match(reLinkLabel);
      if (m === null || m.length > 1001) {
        return 0;
      }
      return m.length;
    };
    InlineParser2.prototype.parseOpenBracket = function(block2) {
      var startpos = this.pos;
      this.pos += 1;
      var node = text$1("[", this.sourcepos(this.pos, this.pos));
      block2.appendChild(node);
      this.addBracket(node, startpos, false);
      return true;
    };
    InlineParser2.prototype.parseBang = function(block2) {
      var startpos = this.pos;
      this.pos += 1;
      if (this.peek() === C_OPEN_BRACKET$1) {
        this.pos += 1;
        var node = text$1("![", this.sourcepos(this.pos - 1, this.pos));
        block2.appendChild(node);
        this.addBracket(node, startpos + 1, true);
      } else {
        var node = text$1("!", this.sourcepos(this.pos, this.pos));
        block2.appendChild(node);
      }
      return true;
    };
    InlineParser2.prototype.parseCloseBracket = function(block2) {
      var dest = null;
      var title = null;
      var matched = false;
      this.pos += 1;
      var startpos = this.pos;
      var opener = this.brackets;
      if (opener === null) {
        block2.appendChild(text$1("]", this.sourcepos(startpos, startpos)));
        return true;
      }
      if (!opener.active) {
        block2.appendChild(text$1("]", this.sourcepos(startpos, startpos)));
        this.removeBracket();
        return true;
      }
      var isImage = opener.image;
      var savepos = this.pos;
      if (this.peek() === C_OPEN_PAREN) {
        this.pos++;
        if (this.spnl() && (dest = this.parseLinkDestination()) !== null && this.spnl() && // make sure there's a space before the title:
        (reWhitespaceChar.test(this.subject.charAt(this.pos - 1)) && (title = this.parseLinkTitle()) || true) && this.spnl() && this.peek() === C_CLOSE_PAREN) {
          this.pos += 1;
          matched = true;
        } else {
          this.pos = savepos;
        }
      }
      var refLabel = "";
      if (!matched) {
        var beforelabel = this.pos;
        var n = this.parseLinkLabel();
        if (n > 2) {
          refLabel = this.subject.slice(beforelabel, beforelabel + n);
        } else if (!opener.bracketAfter) {
          refLabel = this.subject.slice(opener.index, startpos);
        }
        if (n === 0) {
          this.pos = savepos;
        }
        if (refLabel) {
          refLabel = normalizeReference(refLabel);
          var link2 = this.refMap[refLabel];
          if (link2) {
            dest = link2.destination;
            title = link2.title;
            matched = true;
          }
        }
      }
      if (matched) {
        var node = createNode$1(isImage ? "image" : "link");
        node.destination = dest;
        node.title = title || "";
        node.sourcepos = [opener.startpos, this.sourcepos(this.pos)];
        var tmp = opener.node.next;
        var next = void 0;
        while (tmp) {
          next = tmp.next;
          tmp.unlink();
          node.appendChild(tmp);
          tmp = next;
        }
        block2.appendChild(node);
        this.processEmphasis(opener.previousDelimiter);
        this.removeBracket();
        opener.node.unlink();
        if (!isImage) {
          opener = this.brackets;
          while (opener !== null) {
            if (!opener.image) {
              opener.active = false;
            }
            opener = opener.previous;
          }
        }
        if (this.options.referenceDefinition) {
          this.refLinkCandidateMap[block2.id] = { node: block2, refLabel };
        }
        return true;
      }
      this.removeBracket();
      this.pos = startpos;
      block2.appendChild(text$1("]", this.sourcepos(startpos, startpos)));
      if (this.options.referenceDefinition) {
        this.refLinkCandidateMap[block2.id] = { node: block2, refLabel };
      }
      return true;
    };
    InlineParser2.prototype.addBracket = function(node, index2, image2) {
      if (this.brackets !== null) {
        this.brackets.bracketAfter = true;
      }
      this.brackets = {
        node,
        startpos: this.sourcepos(index2 + (image2 ? 0 : 1)),
        previous: this.brackets,
        previousDelimiter: this.delimiters,
        index: index2,
        image: image2,
        active: true
      };
    };
    InlineParser2.prototype.removeBracket = function() {
      if (this.brackets) {
        this.brackets = this.brackets.previous;
      }
    };
    InlineParser2.prototype.parseEntity = function(block2) {
      var m;
      var startpos = this.pos + 1;
      if (m = this.match(reEntityHere)) {
        block2.appendChild(text$1(lib.decodeHTML(m), this.sourcepos(startpos, this.pos)));
        return true;
      }
      return false;
    };
    InlineParser2.prototype.parseString = function(block2) {
      var m;
      var startpos = this.pos + 1;
      if (m = this.match(reMain)) {
        if (this.options.smart) {
          var lit = m.replace(reEllipses, "\u2026").replace(reDash, function(chars) {
            var enCount = 0;
            var emCount = 0;
            if (chars.length % 3 === 0) {
              emCount = chars.length / 3;
            } else if (chars.length % 2 === 0) {
              enCount = chars.length / 2;
            } else if (chars.length % 3 === 2) {
              enCount = 1;
              emCount = (chars.length - 2) / 3;
            } else {
              enCount = 2;
              emCount = (chars.length - 4) / 3;
            }
            return repeat("\u2014", emCount) + repeat("\u2013", enCount);
          });
          block2.appendChild(text$1(lit, this.sourcepos(startpos, this.pos)));
        } else {
          var node = text$1(m, this.sourcepos(startpos, this.pos));
          block2.appendChild(node);
        }
        return true;
      }
      return false;
    };
    InlineParser2.prototype.parseNewline = function(block2) {
      this.pos += 1;
      var lastc = block2.lastChild;
      if (lastc && lastc.type === "text" && lastc.literal[lastc.literal.length - 1] === " ") {
        var hardbreak = lastc.literal[lastc.literal.length - 2] === " ";
        var litLen = lastc.literal.length;
        lastc.literal = lastc.literal.replace(reFinalSpace, "");
        var finalSpaceLen = litLen - lastc.literal.length;
        lastc.sourcepos[1][1] -= finalSpaceLen;
        block2.appendChild(createNode$1(hardbreak ? "linebreak" : "softbreak", this.sourcepos(this.pos - finalSpaceLen, this.pos)));
      } else {
        block2.appendChild(createNode$1("softbreak", this.sourcepos(this.pos, this.pos)));
      }
      this.nextLine();
      this.match(reInitialSpace);
      return true;
    };
    InlineParser2.prototype.parseReference = function(block2, refMap) {
      if (!this.options.referenceDefinition) {
        return 0;
      }
      this.subject = block2.stringContent;
      this.pos = 0;
      var title = null;
      var startpos = this.pos;
      var matchChars = this.parseLinkLabel();
      if (matchChars === 0) {
        return 0;
      }
      var rawlabel = this.subject.substr(0, matchChars);
      if (this.peek() === C_COLON) {
        this.pos++;
      } else {
        this.pos = startpos;
        return 0;
      }
      this.spnl();
      var dest = this.parseLinkDestination();
      if (dest === null) {
        this.pos = startpos;
        return 0;
      }
      var beforetitle = this.pos;
      this.spnl();
      if (this.pos !== beforetitle) {
        title = this.parseLinkTitle();
      }
      if (title === null) {
        title = "";
        this.pos = beforetitle;
      }
      var atLineEnd = true;
      if (this.match(reSpaceAtEndOfLine) === null) {
        if (title === "") {
          atLineEnd = false;
        } else {
          title = "";
          this.pos = beforetitle;
          atLineEnd = this.match(reSpaceAtEndOfLine) !== null;
        }
      }
      if (!atLineEnd) {
        this.pos = startpos;
        return 0;
      }
      var normalLabel = normalizeReference(rawlabel);
      if (normalLabel === "") {
        this.pos = startpos;
        return 0;
      }
      var sourcepos = this.getReferenceDefSourcepos(block2);
      block2.sourcepos[0][0] = sourcepos[1][0] + 1;
      var node = createNode$1("refDef", sourcepos);
      node.title = title;
      node.dest = dest;
      node.label = normalLabel;
      block2.insertBefore(node);
      if (!refMap[normalLabel]) {
        refMap[normalLabel] = createRefDefState(node);
      } else {
        this.refDefCandidateMap[node.id] = node;
      }
      return this.pos - startpos;
    };
    InlineParser2.prototype.mergeTextNodes = function(walker) {
      var event;
      var textNodes = [];
      while (event = walker.next()) {
        var entering = event.entering, node = event.node;
        if (entering && node.type === "text") {
          textNodes.push(node);
        } else if (textNodes.length === 1) {
          textNodes = [];
        } else if (textNodes.length > 1) {
          var firstNode = textNodes[0];
          var lastNode = textNodes[textNodes.length - 1];
          if (firstNode.sourcepos && lastNode.sourcepos) {
            firstNode.sourcepos[1] = lastNode.sourcepos[1];
          }
          firstNode.next = lastNode.next;
          if (firstNode.next) {
            firstNode.next.prev = firstNode;
          }
          for (var i = 1; i < textNodes.length; i += 1) {
            firstNode.literal += textNodes[i].literal;
            textNodes[i].unlink();
          }
          textNodes = [];
        }
      }
    };
    InlineParser2.prototype.getReferenceDefSourcepos = function(block2) {
      var lines = block2.stringContent.split(/\n|\r\n/);
      var passedUrlLine = false;
      var quotationCount = 0;
      var lastLineOffset = { line: 0, ch: 0 };
      for (var i = 0; i < lines.length; i += 1) {
        var line = lines[i];
        if (reWhitespaceChar.test(line)) {
          break;
        }
        if (/\:/.test(line) && quotationCount === 0) {
          if (passedUrlLine) {
            break;
          }
          var lineOffset = line.indexOf(":") === line.length - 1 ? i + 1 : i;
          lastLineOffset = { line: lineOffset, ch: lines[lineOffset].length };
          passedUrlLine = true;
        }
        var matched = line.match(/'|"/g);
        if (matched) {
          quotationCount += matched.length;
        }
        if (quotationCount === 2) {
          lastLineOffset = { line: i, ch: line.length };
          break;
        }
      }
      return [
        [block2.sourcepos[0][0], block2.sourcepos[0][1]],
        [block2.sourcepos[0][0] + lastLineOffset.line, lastLineOffset.ch]
      ];
    };
    InlineParser2.prototype.parseInline = function(block2) {
      var _a;
      var res = false;
      var c = this.peek();
      if (c === -1) {
        return false;
      }
      switch (c) {
        case C_NEWLINE:
          res = this.parseNewline(block2);
          break;
        case C_BACKSLASH:
          res = this.parseBackslash(block2);
          break;
        case C_BACKTICK:
          res = this.parseBackticks(block2);
          break;
        case C_ASTERISK:
        case C_UNDERSCORE:
        case C_TILDE:
        case C_DOLLAR:
          res = this.handleDelim(c, block2);
          break;
        case C_SINGLEQUOTE:
        case C_DOUBLEQUOTE:
          res = !!((_a = this.options) === null || _a === void 0 ? void 0 : _a.smart) && this.handleDelim(c, block2);
          break;
        case C_OPEN_BRACKET$1:
          res = this.parseOpenBracket(block2);
          break;
        case C_BANG:
          res = this.parseBang(block2);
          break;
        case C_CLOSE_BRACKET:
          res = this.parseCloseBracket(block2);
          break;
        case C_LESSTHAN$1:
          res = this.parseAutolink(block2) || this.parseHtmlTag(block2);
          break;
        case C_AMPERSAND:
          if (!block2.disabledEntityParse) {
            res = this.parseEntity(block2);
          }
          break;
        default:
          res = this.parseString(block2);
          break;
      }
      if (!res) {
        this.pos += 1;
        block2.appendChild(text$1(fromCodePoint$1(c), this.sourcepos(this.pos, this.pos + 1)));
      }
      return true;
    };
    InlineParser2.prototype.parse = function(block2) {
      this.subject = block2.stringContent.trim();
      this.pos = 0;
      this.delimiters = null;
      this.brackets = null;
      this.lineOffsets = block2.lineOffsets || [0];
      this.lineIdx = 0;
      this.linePosOffset = 0;
      this.lineStartNum = block2.sourcepos[0][0];
      if (isHeading(block2)) {
        this.lineOffsets[0] += block2.level + 1;
      }
      while (this.parseInline(block2)) {
      }
      block2.stringContent = null;
      this.processEmphasis(null);
      this.mergeTextNodes(block2.walker());
      var _a = this.options, extendedAutolinks = _a.extendedAutolinks, customParser = _a.customParser;
      if (extendedAutolinks) {
        convertExtAutoLinks(block2.walker(), extendedAutolinks);
      }
      if (customParser && block2.firstChild) {
        var event_1;
        var walker = block2.firstChild.walker();
        while (event_1 = walker.next()) {
          var node = event_1.node, entering = event_1.entering;
          if (customParser[node.type]) {
            customParser[node.type](node, { entering, options: this.options });
          }
        }
      }
    };
    return InlineParser2;
  })()
);
var reTaskListItemMarker = /^\[([ \txX])\][ \t]+/;
function taskListItemFinalize(_, block2) {
  if (block2.firstChild && block2.firstChild.type === "paragraph") {
    var p = block2.firstChild;
    var m = p.stringContent.match(reTaskListItemMarker);
    if (m) {
      var mLen = m[0].length;
      p.stringContent = p.stringContent.substring(mLen - 1);
      p.sourcepos[0][1] += mLen;
      p.lineOffsets[0] += mLen;
      block2.listData.task = true;
      block2.listData.checked = /[xX]/.test(m[1]);
    }
  }
}
var table = {
  continue: function() {
    return 0;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t === "tableHead" || t === "tableBody";
  },
  acceptsLines: false
};
var tableBody$1 = {
  continue: function() {
    return 0;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t === "tableRow";
  },
  acceptsLines: false
};
var tableHead$1 = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t === "tableRow" || t === "tableDelimRow";
  },
  acceptsLines: false
};
var tableDelimRow = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t === "tableDelimCell";
  },
  acceptsLines: false
};
var tableDelimCell = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function() {
    return false;
  },
  acceptsLines: false
};
var tableRow = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t === "tableCell";
  },
  acceptsLines: false
};
var tableCell = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function() {
    return false;
  },
  acceptsLines: false
};
var CODE_INDENT = 4;
var C_TAB = 9;
var C_GREATERTHAN = 62;
var C_LESSTHAN = 60;
var C_SPACE = 32;
var C_OPEN_BRACKET = 91;
var reNonSpace = /[^ \t\f\v\r\n]/;
var reClosingCodeFence = /^(?:`{3,}|~{3,})(?= *$)/;
function endsWithBlankLine(block2) {
  var curBlock = block2;
  while (curBlock) {
    if (curBlock.lastLineBlank) {
      return true;
    }
    var t = curBlock.type;
    if (!curBlock.lastLineChecked && (t === "list" || t === "item")) {
      curBlock.lastLineChecked = true;
      curBlock = curBlock.lastChild;
    } else {
      curBlock.lastLineChecked = true;
      break;
    }
  }
  return false;
}
function peek(ln, pos) {
  if (pos < ln.length) {
    return ln.charCodeAt(pos);
  }
  return -1;
}
function isBlank(s) {
  return !reNonSpace.test(s);
}
function isSpaceOrTab(c) {
  return c === C_SPACE || c === C_TAB;
}
var reClosingCustomBlock = /^\$\$$/;
var customBlock$1 = {
  continue: function(parser, container) {
    var line = parser.currentLine;
    var match = line.match(reClosingCustomBlock);
    if (match) {
      parser.lastLineLength = match[0].length;
      parser.finalize(container, parser.lineNumber);
      return 2;
    }
    var i = container.offset;
    while (i > 0 && isSpaceOrTab(peek(line, parser.offset))) {
      parser.advanceOffset(1, true);
      i--;
    }
    return 0;
  },
  finalize: function(_, block2) {
    if (block2.stringContent === null) {
      return;
    }
    var content = block2.stringContent;
    var newlinePos = content.indexOf("\n");
    var firstLine = content.slice(0, newlinePos);
    var rest = content.slice(newlinePos + 1);
    var infoString = firstLine.match(/^(\s*)(.*)/);
    block2.info = unescapeString(infoString[2].trim());
    block2.literal = rest;
    block2.stringContent = null;
  },
  canContain: function() {
    return false;
  },
  acceptsLines: true
};
var noop = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function() {
    return false;
  },
  acceptsLines: true
};
var document$1 = {
  continue: function() {
    return 0;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t !== "item";
  },
  acceptsLines: false
};
var list = {
  continue: function() {
    return 0;
  },
  finalize: function(_, block2) {
    var item2 = block2.firstChild;
    while (item2) {
      if (endsWithBlankLine(item2) && item2.next) {
        block2.listData.tight = false;
        break;
      }
      var subitem = item2.firstChild;
      while (subitem) {
        if (endsWithBlankLine(subitem) && (item2.next || subitem.next)) {
          block2.listData.tight = false;
          break;
        }
        subitem = subitem.next;
      }
      item2 = item2.next;
    }
  },
  canContain: function(t) {
    return t === "item";
  },
  acceptsLines: false
};
var blockQuote$1 = {
  continue: function(parser) {
    var ln = parser.currentLine;
    if (!parser.indented && peek(ln, parser.nextNonspace) === C_GREATERTHAN) {
      parser.advanceNextNonspace();
      parser.advanceOffset(1, false);
      if (isSpaceOrTab(peek(ln, parser.offset))) {
        parser.advanceOffset(1, true);
      }
    } else {
      return 1;
    }
    return 0;
  },
  finalize: function() {
  },
  canContain: function(t) {
    return t !== "item";
  },
  acceptsLines: false
};
var item = {
  continue: function(parser, container) {
    if (parser.blank) {
      if (container.firstChild === null) {
        return 1;
      }
      parser.advanceNextNonspace();
    } else if (parser.indent >= container.listData.markerOffset + container.listData.padding) {
      parser.advanceOffset(container.listData.markerOffset + container.listData.padding, true);
    } else {
      return 1;
    }
    return 0;
  },
  finalize: taskListItemFinalize,
  canContain: function(t) {
    return t !== "item";
  },
  acceptsLines: false
};
var heading = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function() {
    return false;
  },
  acceptsLines: false
};
var thematicBreak$1 = {
  continue: function() {
    return 1;
  },
  finalize: function() {
  },
  canContain: function() {
    return false;
  },
  acceptsLines: false
};
var codeBlock = {
  continue: function(parser, container) {
    var ln = parser.currentLine;
    var indent2 = parser.indent;
    if (container.isFenced) {
      var match = indent2 <= 3 && ln.charAt(parser.nextNonspace) === container.fenceChar && ln.slice(parser.nextNonspace).match(reClosingCodeFence);
      if (match && match[0].length >= container.fenceLength) {
        parser.lastLineLength = parser.offset + indent2 + match[0].length;
        parser.finalize(container, parser.lineNumber);
        return 2;
      }
      var i = container.fenceOffset;
      while (i > 0 && isSpaceOrTab(peek(ln, parser.offset))) {
        parser.advanceOffset(1, true);
        i--;
      }
    } else {
      if (indent2 >= CODE_INDENT) {
        parser.advanceOffset(CODE_INDENT, true);
      } else if (parser.blank) {
        parser.advanceNextNonspace();
      } else {
        return 1;
      }
    }
    return 0;
  },
  finalize: function(_, block2) {
    var _a;
    if (block2.stringContent === null) {
      return;
    }
    if (block2.isFenced) {
      var content = block2.stringContent;
      var newlinePos = content.indexOf("\n");
      var firstLine = content.slice(0, newlinePos);
      var rest = content.slice(newlinePos + 1);
      var infoString = firstLine.match(/^(\s*)(.*)/);
      block2.infoPadding = infoString[1].length;
      block2.info = unescapeString(infoString[2].trim());
      block2.literal = rest;
    } else {
      block2.literal = (_a = block2.stringContent) === null || _a === void 0 ? void 0 : _a.replace(/(\n *)+$/, "\n");
    }
    block2.stringContent = null;
  },
  canContain: function() {
    return false;
  },
  acceptsLines: true
};
var htmlBlock$1 = {
  continue: function(parser, container) {
    return parser.blank && (container.htmlBlockType === 6 || container.htmlBlockType === 7) ? 1 : 0;
  },
  finalize: function(_, block2) {
    var _a;
    block2.literal = ((_a = block2.stringContent) === null || _a === void 0 ? void 0 : _a.replace(/(\n *)+$/, "")) || null;
    block2.stringContent = null;
  },
  canContain: function() {
    return false;
  },
  acceptsLines: true
};
var paragraph = {
  continue: function(parser) {
    return parser.blank ? 1 : 0;
  },
  finalize: function(parser, block2) {
    if (block2.stringContent === null) {
      return;
    }
    var pos;
    var hasReferenceDefs = false;
    while (peek(block2.stringContent, 0) === C_OPEN_BRACKET && (pos = parser.inlineParser.parseReference(block2, parser.refMap))) {
      block2.stringContent = block2.stringContent.slice(pos);
      hasReferenceDefs = true;
    }
    if (hasReferenceDefs && isBlank(block2.stringContent)) {
      block2.unlink();
    }
  },
  canContain: function() {
    return false;
  },
  acceptsLines: true
};
var refDef = noop;
var frontMatter$2 = noop;
var blockHandlers = {
  document: document$1,
  list,
  blockQuote: blockQuote$1,
  item,
  heading,
  thematicBreak: thematicBreak$1,
  codeBlock,
  htmlBlock: htmlBlock$1,
  paragraph,
  table,
  tableBody: tableBody$1,
  tableHead: tableHead$1,
  tableRow,
  tableCell,
  tableDelimRow,
  tableDelimCell,
  refDef,
  customBlock: customBlock$1,
  frontMatter: frontMatter$2
};
function parseRowContent(content) {
  var startIdx = 0;
  var offset = 0;
  var cells = [];
  for (var i = 0; i < content.length; i += 1) {
    if (content[i] === "|" && content[i - 1] !== "\\") {
      var cell = content.substring(startIdx, i);
      if (startIdx === 0 && isEmpty(cell)) {
        offset = i + 1;
      } else {
        cells.push(cell);
      }
      startIdx = i + 1;
    }
  }
  if (startIdx < content.length) {
    var cell = content.substring(startIdx, content.length);
    if (!isEmpty(cell)) {
      cells.push(cell);
    }
  }
  return [offset, cells];
}
function generateTableCells(cellType, contents, lineNum, chPos) {
  var cells = [];
  for (var _i = 0, contents_1 = contents; _i < contents_1.length; _i++) {
    var content = contents_1[_i];
    var preSpaces = content.match(/^[ \t]+/);
    var paddingLeft = preSpaces ? preSpaces[0].length : 0;
    var paddingRight = void 0, trimmed = void 0;
    if (paddingLeft === content.length) {
      paddingLeft = 0;
      paddingRight = 0;
      trimmed = "";
    } else {
      var postSpaces = content.match(/[ \t]+$/);
      paddingRight = postSpaces ? postSpaces[0].length : 0;
      trimmed = content.slice(paddingLeft, content.length - paddingRight);
    }
    var chPosStart = chPos + paddingLeft;
    var tableCell2 = createNode$1(cellType, [
      [lineNum, chPos],
      [lineNum, chPos + content.length - 1]
    ]);
    tableCell2.stringContent = trimmed.replace(/\\\|/g, "|");
    tableCell2.startIdx = cells.length;
    tableCell2.endIdx = cells.length;
    tableCell2.lineOffsets = [chPosStart - 1];
    tableCell2.paddingLeft = paddingLeft;
    tableCell2.paddingRight = paddingRight;
    cells.push(tableCell2);
    chPos += content.length + 1;
  }
  return cells;
}
function getColumnFromDelimCell(cellNode) {
  var align = null;
  var content = cellNode.stringContent;
  var firstCh = content[0];
  var lastCh = content[content.length - 1];
  if (lastCh === ":") {
    align = firstCh === ":" ? "center" : "right";
  } else if (firstCh === ":") {
    align = "left";
  }
  return { align };
}
var tableHead = function(parser, container) {
  var stringContent = container.stringContent;
  if (container.type === "paragraph" && !parser.indented && !parser.blank) {
    var lastNewLineIdx = stringContent.length - 1;
    var lastLineStartIdx = stringContent.lastIndexOf("\n", lastNewLineIdx - 1) + 1;
    var headerContent = stringContent.slice(lastLineStartIdx, lastNewLineIdx);
    var delimContent = parser.currentLine.slice(parser.nextNonspace);
    var _a = parseRowContent(headerContent), headerOffset = _a[0], headerCells = _a[1];
    var _b = parseRowContent(delimContent), delimOffset = _b[0], delimCells = _b[1];
    var reValidDelimCell_1 = /^[ \t]*:?-+:?[ \t]*$/;
    if (
      // not checking if the number of header cells and delimiter cells are the same
      // to consider the case of merged-column (via plugin)
      !headerCells.length || !delimCells.length || delimCells.some(function(cell) {
        return !reValidDelimCell_1.test(cell);
      }) || // to prevent to regard setTextHeading as tabel delim cell with 'disallowDeepHeading' option
      delimCells.length === 1 && delimContent.indexOf("|") !== 0
    ) {
      return 0;
    }
    var lineOffsets = container.lineOffsets;
    var firstLineNum = parser.lineNumber - 1;
    var firstLineStart = last(lineOffsets) + 1;
    var table2 = createNode$1("table", [
      [firstLineNum, firstLineStart],
      [parser.lineNumber, parser.offset]
    ]);
    table2.columns = delimCells.map(function() {
      return { align: null };
    });
    container.insertAfter(table2);
    if (lineOffsets.length === 1) {
      container.unlink();
    } else {
      container.stringContent = stringContent.slice(0, lastLineStartIdx);
      var paraLastLineStartIdx = stringContent.lastIndexOf("\n", lastLineStartIdx - 2) + 1;
      var paraLastLineLen = lastLineStartIdx - paraLastLineStartIdx - 1;
      parser.lastLineLength = lineOffsets[lineOffsets.length - 2] + paraLastLineLen;
      parser.finalize(container, firstLineNum - 1);
    }
    parser.advanceOffset(parser.currentLine.length - parser.offset, false);
    var tableHead_1 = createNode$1("tableHead", [
      [firstLineNum, firstLineStart],
      [parser.lineNumber, parser.offset]
    ]);
    table2.appendChild(tableHead_1);
    var tableHeadRow_1 = createNode$1("tableRow", [
      [firstLineNum, firstLineStart],
      [firstLineNum, firstLineStart + headerContent.length - 1]
    ]);
    var tableDelimRow_1 = createNode$1("tableDelimRow", [
      [parser.lineNumber, parser.nextNonspace + 1],
      [parser.lineNumber, parser.offset]
    ]);
    tableHead_1.appendChild(tableHeadRow_1);
    tableHead_1.appendChild(tableDelimRow_1);
    generateTableCells("tableCell", headerCells, firstLineNum, firstLineStart + headerOffset).forEach(function(cellNode) {
      tableHeadRow_1.appendChild(cellNode);
    });
    var delimCellNodes = generateTableCells("tableDelimCell", delimCells, parser.lineNumber, parser.nextNonspace + 1 + delimOffset);
    delimCellNodes.forEach(function(cellNode) {
      tableDelimRow_1.appendChild(cellNode);
    });
    table2.columns = delimCellNodes.map(getColumnFromDelimCell);
    parser.tip = table2;
    return 2;
  }
  return 0;
};
var tableBody = function(parser, container) {
  if (container.type !== "table" && container.type !== "tableBody" || !parser.blank && parser.currentLine.indexOf("|") === -1) {
    return 0;
  }
  parser.advanceOffset(parser.currentLine.length - parser.offset, false);
  if (parser.blank) {
    var table_1 = container;
    if (container.type === "tableBody") {
      table_1 = container.parent;
      parser.finalize(container, parser.lineNumber - 1);
    }
    parser.finalize(table_1, parser.lineNumber - 1);
    return 0;
  }
  var tableBody2 = container;
  if (container.type === "table") {
    tableBody2 = parser.addChild("tableBody", parser.nextNonspace);
    tableBody2.stringContent = null;
  }
  var tableRow2 = createNode$1("tableRow", [
    [parser.lineNumber, parser.nextNonspace + 1],
    [parser.lineNumber, parser.currentLine.length]
  ]);
  tableBody2.appendChild(tableRow2);
  var table2 = tableBody2.parent;
  var content = parser.currentLine.slice(parser.nextNonspace);
  var _a = parseRowContent(content), offset = _a[0], cellContents = _a[1];
  generateTableCells("tableCell", cellContents, parser.lineNumber, parser.nextNonspace + 1 + offset).forEach(function(cellNode, idx) {
    if (idx >= table2.columns.length) {
      cellNode.ignored = true;
    }
    tableRow2.appendChild(cellNode);
  });
  return 2;
};
var reCustomBlock = /^(\$\$)(\s*[a-zA-Z])+/;
var reCanBeCustomInline = /^(\$\$)(\s*[a-zA-Z])+.*(\$\$)/;
var customBlock = function(parser) {
  var match;
  if (!parser.indented && !reCanBeCustomInline.test(parser.currentLine) && (match = parser.currentLine.match(reCustomBlock))) {
    var syntaxLength = match[1].length;
    parser.closeUnmatchedBlocks();
    var container = parser.addChild("customBlock", parser.nextNonspace);
    container.syntaxLength = syntaxLength;
    container.offset = parser.indent;
    parser.advanceNextNonspace();
    parser.advanceOffset(syntaxLength, false);
    return 2;
  }
  return 0;
};
var reCodeFence = /^`{3,}(?!.*`)|^~{3,}/;
var reHtmlBlockOpen = [
  /./,
  /^<(?:script|pre|style)(?:\s|>|$)/i,
  /^<!--/,
  /^<[?]/,
  /^<![A-Z]/,
  /^<!\[CDATA\[/,
  /^<[/]?(?: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[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|[/]?[>]|$)/i,
  new RegExp("^(?:" + OPENTAG + "|" + CLOSETAG + ")\\s*$", "i")
];
var reSetextHeadingLine = /^(?:=+|-+)[ \t]*$/;
var reATXHeadingMarker = /^#{1,6}(?:[ \t]+|$)/;
var reThematicBreak = /^(?:(?:\*[ \t]*){3,}|(?:_[ \t]*){3,}|(?:-[ \t]*){3,})[ \t]*$/;
var reBulletListMarker = /^[*+-]/;
var reOrderedListMarker = /^(\d{1,9})([.)])/;
function parseListMarker(parser, container) {
  var rest = parser.currentLine.slice(parser.nextNonspace);
  var match;
  var nextc;
  var data = {
    type: "bullet",
    tight: true,
    bulletChar: "",
    start: 0,
    delimiter: "",
    padding: 0,
    markerOffset: parser.indent,
    // GFM: Task List Item
    task: false,
    checked: false
  };
  if (parser.indent >= 4) {
    return null;
  }
  if (match = rest.match(reBulletListMarker)) {
    data.type = "bullet";
    data.bulletChar = match[0][0];
  } else if ((match = rest.match(reOrderedListMarker)) && (container.type !== "paragraph" || match[1] === "1")) {
    data.type = "ordered";
    data.start = parseInt(match[1], 10);
    data.delimiter = match[2];
  } else {
    return null;
  }
  nextc = peek(parser.currentLine, parser.nextNonspace + match[0].length);
  if (!(nextc === -1 || nextc === C_TAB || nextc === C_SPACE)) {
    return null;
  }
  if (container.type === "paragraph" && !parser.currentLine.slice(parser.nextNonspace + match[0].length).match(reNonSpace)) {
    return null;
  }
  parser.advanceNextNonspace();
  parser.advanceOffset(match[0].length, true);
  var spacesStartCol = parser.column;
  var spacesStartOffset = parser.offset;
  do {
    parser.advanceOffset(1, true);
    nextc = peek(parser.currentLine, parser.offset);
  } while (parser.column - spacesStartCol < 5 && isSpaceOrTab(nextc));
  var blankItem = peek(parser.currentLine, parser.offset) === -1;
  var spacesAfterMarker = parser.column - spacesStartCol;
  if (spacesAfterMarker >= 5 || spacesAfterMarker < 1 || blankItem) {
    data.padding = match[0].length + 1;
    parser.column = spacesStartCol;
    parser.offset = spacesStartOffset;
    if (isSpaceOrTab(peek(parser.currentLine, parser.offset))) {
      parser.advanceOffset(1, true);
    }
  } else {
    data.padding = match[0].length + spacesAfterMarker;
  }
  return data;
}
function listsMatch(listData, itemData) {
  return listData.type === itemData.type && listData.delimiter === itemData.delimiter && listData.bulletChar === itemData.bulletChar;
}
function isDisallowedDeepHeading(parser, node) {
  return parser.options.disallowDeepHeading && (node.type === "blockQuote" || node.type === "item");
}
var blockQuote = function(parser) {
  if (!parser.indented && peek(parser.currentLine, parser.nextNonspace) === C_GREATERTHAN) {
    parser.advanceNextNonspace();
    parser.advanceOffset(1, false);
    if (isSpaceOrTab(peek(parser.currentLine, parser.offset))) {
      parser.advanceOffset(1, true);
    }
    parser.closeUnmatchedBlocks();
    parser.addChild("blockQuote", parser.nextNonspace);
    return 1;
  }
  return 0;
};
var atxHeading = function(parser, container) {
  var match;
  if (!parser.indented && // The nested Heading is disallowed in list and blockquote with 'disallowDeepHeading' option
  !isDisallowedDeepHeading(parser, container) && (match = parser.currentLine.slice(parser.nextNonspace).match(reATXHeadingMarker))) {
    parser.advanceNextNonspace();
    parser.advanceOffset(match[0].length, false);
    parser.closeUnmatchedBlocks();
    var heading2 = parser.addChild("heading", parser.nextNonspace);
    heading2.level = match[0].trim().length;
    heading2.headingType = "atx";
    heading2.stringContent = parser.currentLine.slice(parser.offset).replace(/^[ \t]*#+[ \t]*$/, "").replace(/[ \t]+#+[ \t]*$/, "");
    parser.advanceOffset(parser.currentLine.length - parser.offset);
    return 2;
  }
  return 0;
};
var fencedCodeBlock = function(parser) {
  var match;
  if (!parser.indented && (match = parser.currentLine.slice(parser.nextNonspace).match(reCodeFence))) {
    var fenceLength = match[0].length;
    parser.closeUnmatchedBlocks();
    var container = parser.addChild("codeBlock", parser.nextNonspace);
    container.isFenced = true;
    container.fenceLength = fenceLength;
    container.fenceChar = match[0][0];
    container.fenceOffset = parser.indent;
    parser.advanceNextNonspace();
    parser.advanceOffset(fenceLength, false);
    return 2;
  }
  return 0;
};
var htmlBlock = function(parser, container) {
  if (!parser.indented && peek(parser.currentLine, parser.nextNonspace) === C_LESSTHAN) {
    var s = parser.currentLine.slice(parser.nextNonspace);
    var disallowedTags2 = parser.options.disallowedHtmlBlockTags;
    var blockType = void 0;
    for (blockType = 1; blockType <= 7; blockType++) {
      var matched = s.match(reHtmlBlockOpen[blockType]);
      if (matched) {
        if (blockType === 7) {
          if (container.type === "paragraph") {
            return 0;
          }
          if (disallowedTags2.length > 0) {
            var reDisallowedTags = new RegExp("</?(?:" + disallowedTags2.join("|") + ")", "i");
            if (reDisallowedTags.test(matched[0])) {
              return 0;
            }
          }
        }
        parser.closeUnmatchedBlocks();
        var b = parser.addChild("htmlBlock", parser.offset);
        b.htmlBlockType = blockType;
        return 2;
      }
    }
  }
  return 0;
};
var seTextHeading = function(parser, container) {
  var match;
  if (container.stringContent !== null && !parser.indented && container.type === "paragraph" && // The nested Heading is disallowed in list and blockquote with 'disallowDeepHeading' option
  !isDisallowedDeepHeading(parser, container.parent) && (match = parser.currentLine.slice(parser.nextNonspace).match(reSetextHeadingLine))) {
    parser.closeUnmatchedBlocks();
    var pos = void 0;
    while (peek(container.stringContent, 0) === C_OPEN_BRACKET && (pos = parser.inlineParser.parseReference(container, parser.refMap))) {
      container.stringContent = container.stringContent.slice(pos);
    }
    if (container.stringContent.length > 0) {
      var heading2 = createNode$1("heading", container.sourcepos);
      heading2.level = match[0][0] === "=" ? 1 : 2;
      heading2.headingType = "setext";
      heading2.stringContent = container.stringContent;
      container.insertAfter(heading2);
      container.unlink();
      parser.tip = heading2;
      parser.advanceOffset(parser.currentLine.length - parser.offset, false);
      return 2;
    }
    return 0;
  }
  return 0;
};
var thematicBreak = function(parser) {
  if (!parser.indented && reThematicBreak.test(parser.currentLine.slice(parser.nextNonspace))) {
    parser.closeUnmatchedBlocks();
    parser.addChild("thematicBreak", parser.nextNonspace);
    parser.advanceOffset(parser.currentLine.length - parser.offset, false);
    return 2;
  }
  return 0;
};
var listItem = function(parser, container) {
  var data;
  var currNode = container;
  if ((!parser.indented || container.type === "list") && (data = parseListMarker(parser, currNode))) {
    parser.closeUnmatchedBlocks();
    if (parser.tip.type !== "list" || !listsMatch(currNode.listData, data)) {
      currNode = parser.addChild("list", parser.nextNonspace);
      currNode.listData = data;
    }
    currNode = parser.addChild("item", parser.nextNonspace);
    currNode.listData = data;
    return 1;
  }
  return 0;
};
var indentedCodeBlock = function(parser) {
  if (parser.indented && parser.tip.type !== "paragraph" && !parser.blank) {
    parser.advanceOffset(CODE_INDENT, true);
    parser.closeUnmatchedBlocks();
    parser.addChild("codeBlock", parser.offset);
    return 2;
  }
  return 0;
};
var blockStarts = [
  blockQuote,
  atxHeading,
  fencedCodeBlock,
  htmlBlock,
  seTextHeading,
  thematicBreak,
  listItem,
  indentedCodeBlock,
  tableHead,
  tableBody,
  customBlock
];
var reFrontMatter = /^(-{3}|\+{3}|;{3})$/;
var frontMatter$1 = function(parser, container) {
  var currentLine = parser.currentLine, lineNumber = parser.lineNumber, indented = parser.indented;
  if (lineNumber === 1 && !indented && container.type === "document" && reFrontMatter.test(currentLine)) {
    parser.closeUnmatchedBlocks();
    var frontMatter_1 = parser.addChild("frontMatter", parser.nextNonspace);
    frontMatter_1.stringContent = currentLine;
    parser.advanceNextNonspace();
    parser.advanceOffset(currentLine.length, false);
    return 2;
  }
  return 0;
};
var frontMatter = {
  continue: function(parser, container) {
    var line = parser.currentLine;
    var match = line.match(reFrontMatter);
    if (container.type === "frontMatter" && match) {
      container.stringContent += line;
      parser.lastLineLength = match[0].length;
      parser.finalize(container, parser.lineNumber);
      return 2;
    }
    return 0;
  },
  finalize: function(_, block2) {
    if (block2.stringContent === null) {
      return;
    }
    block2.literal = block2.stringContent;
    block2.stringContent = null;
  },
  canContain: function() {
    return false;
  },
  acceptsLines: true
};
var reHtmlBlockClose = [
  /./,
  /<\/(?:script|pre|style)>/i,
  /-->/,
  /\?>/,
  />/,
  /\]\]>/
];
var reMaybeSpecial = /^[#`~*+_=<>0-9-;$]/;
var reLineEnding$1 = /\r\n|\n|\r/;
function document$2() {
  return createNode$1("document", [
    [1, 1],
    [0, 0]
  ]);
}
var defaultOptions$1 = {
  smart: false,
  tagFilter: false,
  extendedAutolinks: false,
  disallowedHtmlBlockTags: [],
  referenceDefinition: false,
  disallowDeepHeading: false,
  customParser: null,
  frontMatter: false
};
var Parser = (
  /** @class */
  (function() {
    function Parser2(options) {
      this.options = __assign(__assign({}, defaultOptions$1), options);
      this.doc = document$2();
      this.tip = this.doc;
      this.oldtip = this.doc;
      this.lineNumber = 0;
      this.offset = 0;
      this.column = 0;
      this.nextNonspace = 0;
      this.nextNonspaceColumn = 0;
      this.indent = 0;
      this.currentLine = "";
      this.indented = false;
      this.blank = false;
      this.partiallyConsumedTab = false;
      this.allClosed = true;
      this.lastMatchedContainer = this.doc;
      this.refMap = {};
      this.refLinkCandidateMap = {};
      this.refDefCandidateMap = {};
      this.lastLineLength = 0;
      this.lines = [];
      if (this.options.frontMatter) {
        blockHandlers.frontMatter = frontMatter;
        blockStarts.unshift(frontMatter$1);
      }
      this.inlineParser = new InlineParser(this.options);
    }
    Parser2.prototype.advanceOffset = function(count, columns) {
      if (columns === void 0) {
        columns = false;
      }
      var currentLine = this.currentLine;
      var charsToTab, charsToAdvance;
      var c;
      while (count > 0 && (c = currentLine[this.offset])) {
        if (c === "	") {
          charsToTab = 4 - this.column % 4;
          if (columns) {
            this.partiallyConsumedTab = charsToTab > count;
            charsToAdvance = charsToTab > count ? count : charsToTab;
            this.column += charsToAdvance;
            this.offset += this.partiallyConsumedTab ? 0 : 1;
            count -= charsToAdvance;
          } else {
            this.partiallyConsumedTab = false;
            this.column += charsToTab;
            this.offset += 1;
            count -= 1;
          }
        } else {
          this.partiallyConsumedTab = false;
          this.offset += 1;
          this.column += 1;
          count -= 1;
        }
      }
    };
    Parser2.prototype.advanceNextNonspace = function() {
      this.offset = this.nextNonspace;
      this.column = this.nextNonspaceColumn;
      this.partiallyConsumedTab = false;
    };
    Parser2.prototype.findNextNonspace = function() {
      var currentLine = this.currentLine;
      var i = this.offset;
      var cols = this.column;
      var c;
      while ((c = currentLine.charAt(i)) !== "") {
        if (c === " ") {
          i++;
          cols++;
        } else if (c === "	") {
          i++;
          cols += 4 - cols % 4;
        } else {
          break;
        }
      }
      this.blank = c === "\n" || c === "\r" || c === "";
      this.nextNonspace = i;
      this.nextNonspaceColumn = cols;
      this.indent = this.nextNonspaceColumn - this.column;
      this.indented = this.indent >= CODE_INDENT;
    };
    Parser2.prototype.addLine = function() {
      if (this.partiallyConsumedTab) {
        this.offset += 1;
        var charsToTab = 4 - this.column % 4;
        this.tip.stringContent += repeat(" ", charsToTab);
      }
      if (this.tip.lineOffsets) {
        this.tip.lineOffsets.push(this.offset);
      } else {
        this.tip.lineOffsets = [this.offset];
      }
      this.tip.stringContent += this.currentLine.slice(this.offset) + "\n";
    };
    Parser2.prototype.addChild = function(tag, offset) {
      while (!blockHandlers[this.tip.type].canContain(tag)) {
        this.finalize(this.tip, this.lineNumber - 1);
      }
      var columnNumber = offset + 1;
      var newBlock = createNode$1(tag, [
        [this.lineNumber, columnNumber],
        [0, 0]
      ]);
      newBlock.stringContent = "";
      this.tip.appendChild(newBlock);
      this.tip = newBlock;
      return newBlock;
    };
    Parser2.prototype.closeUnmatchedBlocks = function() {
      if (!this.allClosed) {
        while (this.oldtip !== this.lastMatchedContainer) {
          var parent_1 = this.oldtip.parent;
          this.finalize(this.oldtip, this.lineNumber - 1);
          this.oldtip = parent_1;
        }
        this.allClosed = true;
      }
    };
    Parser2.prototype.finalize = function(block2, lineNumber) {
      var above = block2.parent;
      block2.open = false;
      block2.sourcepos[1] = [lineNumber, this.lastLineLength];
      blockHandlers[block2.type].finalize(this, block2);
      this.tip = above;
    };
    Parser2.prototype.processInlines = function(block2) {
      var event;
      var customParser = this.options.customParser;
      var walker = block2.walker();
      this.inlineParser.refMap = this.refMap;
      this.inlineParser.refLinkCandidateMap = this.refLinkCandidateMap;
      this.inlineParser.refDefCandidateMap = this.refDefCandidateMap;
      this.inlineParser.options = this.options;
      while (event = walker.next()) {
        var node = event.node, entering = event.entering;
        var t = node.type;
        if (customParser && customParser[t]) {
          customParser[t](node, { entering, options: this.options });
        }
        if (!entering && (t === "paragraph" || t === "heading" || t === "tableCell" && !node.ignored)) {
          this.inlineParser.parse(node);
        }
      }
    };
    Parser2.prototype.incorporateLine = function(ln) {
      var container = this.doc;
      this.oldtip = this.tip;
      this.offset = 0;
      this.column = 0;
      this.blank = false;
      this.partiallyConsumedTab = false;
      this.lineNumber += 1;
      if (ln.indexOf("\0") !== -1) {
        ln = ln.replace(/\0/g, "\uFFFD");
      }
      this.currentLine = ln;
      var allMatched = true;
      var lastChild;
      while ((lastChild = container.lastChild) && lastChild.open) {
        container = lastChild;
        this.findNextNonspace();
        switch (blockHandlers[container.type]["continue"](this, container)) {
          case 0:
            break;
          case 1:
            allMatched = false;
            break;
          case 2:
            this.lastLineLength = ln.length;
            return;
          default:
            throw new Error("continue returned illegal value, must be 0, 1, or 2");
        }
        if (!allMatched) {
          container = container.parent;
          break;
        }
      }
      this.allClosed = container === this.oldtip;
      this.lastMatchedContainer = container;
      var matchedLeaf = container.type !== "paragraph" && blockHandlers[container.type].acceptsLines;
      var blockStartsLen = blockStarts.length;
      while (!matchedLeaf) {
        this.findNextNonspace();
        if (container.type !== "table" && container.type !== "tableBody" && container.type !== "paragraph" && !this.indented && !reMaybeSpecial.test(ln.slice(this.nextNonspace))) {
          this.advanceNextNonspace();
          break;
        }
        var i = 0;
        while (i < blockStartsLen) {
          var res = blockStarts[i](this, container);
          if (res === 1) {
            container = this.tip;
            break;
          } else if (res === 2) {
            container = this.tip;
            matchedLeaf = true;
            break;
          } else {
            i++;
          }
        }
        if (i === blockStartsLen) {
          this.advanceNextNonspace();
          break;
        }
      }
      if (!this.allClosed && !this.blank && this.tip.type === "paragraph") {
        this.addLine();
      } else {
        this.closeUnmatchedBlocks();
        if (this.blank && container.lastChild) {
          container.lastChild.lastLineBlank = true;
        }
        var t = container.type;
        var lastLineBlank = this.blank && !(t === "blockQuote" || isCodeBlock(container) && container.isFenced || t === "item" && !container.firstChild && container.sourcepos[0][0] === this.lineNumber);
        var cont = container;
        while (cont) {
          cont.lastLineBlank = lastLineBlank;
          cont = cont.parent;
        }
        if (blockHandlers[t].acceptsLines) {
          this.addLine();
          if (isHtmlBlock(container) && container.htmlBlockType >= 1 && container.htmlBlockType <= 5 && reHtmlBlockClose[container.htmlBlockType].test(this.currentLine.slice(this.offset))) {
            this.lastLineLength = ln.length;
            this.finalize(container, this.lineNumber);
          }
        } else if (this.offset < ln.length && !this.blank) {
          container = this.addChild("paragraph", this.offset);
          this.advanceNextNonspace();
          this.addLine();
        }
      }
      this.lastLineLength = ln.length;
    };
    Parser2.prototype.parse = function(input, lineTexts) {
      this.doc = document$2();
      this.tip = this.doc;
      this.lineNumber = 0;
      this.lastLineLength = 0;
      this.offset = 0;
      this.column = 0;
      this.lastMatchedContainer = this.doc;
      this.currentLine = "";
      var lines = input.split(reLineEnding$1);
      var len = lines.length;
      this.lines = lineTexts ? lineTexts : lines;
      if (this.options.referenceDefinition) {
        this.clearRefMaps();
      }
      if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
        len -= 1;
      }
      for (var i = 0; i < len; i++) {
        this.incorporateLine(lines[i]);
      }
      while (this.tip) {
        this.finalize(this.tip, len);
      }
      this.processInlines(this.doc);
      return this.doc;
    };
    Parser2.prototype.partialParseStart = function(lineNumber, lines) {
      this.doc = document$2();
      this.tip = this.doc;
      this.lineNumber = lineNumber - 1;
      this.lastLineLength = 0;
      this.offset = 0;
      this.column = 0;
      this.lastMatchedContainer = this.doc;
      this.currentLine = "";
      var len = lines.length;
      for (var i = 0; i < len; i++) {
        this.incorporateLine(lines[i]);
      }
      return this.doc;
    };
    Parser2.prototype.partialParseExtends = function(lines) {
      for (var i = 0; i < lines.length; i++) {
        this.incorporateLine(lines[i]);
      }
    };
    Parser2.prototype.partialParseFinish = function() {
      while (this.tip) {
        this.finalize(this.tip, this.lineNumber);
      }
      this.processInlines(this.doc);
    };
    Parser2.prototype.setRefMaps = function(refMap, refLinkCandidateMap, refDefCandidateMap) {
      this.refMap = refMap;
      this.refLinkCandidateMap = refLinkCandidateMap;
      this.refDefCandidateMap = refDefCandidateMap;
    };
    Parser2.prototype.clearRefMaps = function() {
      [this.refMap, this.refLinkCandidateMap, this.refDefCandidateMap].forEach(function(map3) {
        clearObj(map3);
      });
    };
    return Parser2;
  })()
);
function comparePos(p1, p2) {
  if (p1[0] < p2[0]) {
    return 1;
  }
  if (p1[0] > p2[0]) {
    return -1;
  }
  if (p1[1] < p2[1]) {
    return 1;
  }
  if (p1[1] > p2[1]) {
    return -1;
  }
  return 0;
}
function compareRangeAndPos(_a, pos) {
  var startPos = _a[0], endPos = _a[1];
  if (comparePos(endPos, pos) === 1) {
    return 1;
  }
  if (comparePos(startPos, pos) === -1) {
    return -1;
  }
  return 0;
}
function removeNextUntil(node, last2) {
  if (node.parent !== last2.parent || node === last2) {
    return;
  }
  var next = node.next;
  while (next && next !== last2) {
    var temp = next.next;
    for (var _i = 0, _a = ["parent", "prev", "next"]; _i < _a.length; _i++) {
      var type = _a[_i];
      if (next[type]) {
        removeNodeById(next[type].id);
        next[type] = null;
      }
    }
    next = temp;
  }
  node.next = last2.next;
  if (last2.next) {
    last2.next.prev = node;
  } else {
    node.parent.lastChild = node;
  }
}
function getChildNodes(parent) {
  var nodes = [];
  var curr = parent.firstChild;
  while (curr) {
    nodes.push(curr);
    curr = curr.next;
  }
  return nodes;
}
function insertNodesBefore(target2, nodes) {
  for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
    var node = nodes_1[_i];
    target2.insertBefore(node);
  }
}
function prependChildNodes(parent, nodes) {
  for (var i = nodes.length - 1; i >= 0; i -= 1) {
    parent.prependChild(nodes[i]);
  }
}
function updateNextLineNumbers(base2, diff2) {
  if (!base2 || !base2.parent || diff2 === 0) {
    return;
  }
  var walker = base2.parent.walker();
  walker.resumeAt(base2, true);
  var event;
  while (event = walker.next()) {
    var node = event.node, entering = event.entering;
    if (entering) {
      node.sourcepos[0][0] += diff2;
      node.sourcepos[1][0] += diff2;
    }
  }
}
function compareRangeAndLine(_a, line) {
  var startPos = _a[0], endPos = _a[1];
  if (endPos[0] < line) {
    return 1;
  }
  if (startPos[0] > line) {
    return -1;
  }
  return 0;
}
function findChildNodeAtLine(parent, line) {
  var node = parent.firstChild;
  while (node) {
    var comp2 = compareRangeAndLine(node.sourcepos, line);
    if (comp2 === 0) {
      return node;
    }
    if (comp2 === -1) {
      return node.prev || node;
    }
    node = node.next;
  }
  return parent.lastChild;
}
function lastLeafNode(node) {
  while (node.lastChild) {
    node = node.lastChild;
  }
  return node;
}
function sameLineTopAncestor(node) {
  while (node.parent && node.parent.type !== "document" && node.parent.sourcepos[0][0] === node.sourcepos[0][0]) {
    node = node.parent;
  }
  return node;
}
function findFirstNodeAtLine(parent, line) {
  var node = parent.firstChild;
  var prev = null;
  while (node) {
    var comp2 = compareRangeAndLine(node.sourcepos, line);
    if (comp2 === 0) {
      if (node.sourcepos[0][0] === line || !node.firstChild) {
        return node;
      }
      prev = node;
      node = node.firstChild;
    } else if (comp2 === -1) {
      break;
    } else {
      prev = node;
      node = node.next;
    }
  }
  if (prev) {
    return sameLineTopAncestor(lastLeafNode(prev));
  }
  return null;
}
function findNodeAtPosition(parent, pos) {
  var node = parent;
  var prev = null;
  while (node) {
    var comp2 = compareRangeAndPos(node.sourcepos, pos);
    if (comp2 === 0) {
      if (node.firstChild) {
        prev = node;
        node = node.firstChild;
      } else {
        return node;
      }
    } else if (comp2 === -1) {
      return prev;
    } else if (node.next) {
      node = node.next;
    } else {
      return prev;
    }
  }
  return node;
}
function findNodeById(id) {
  return getNodeById(id) || null;
}
function invokeNextUntil(callback, start, end) {
  if (end === void 0) {
    end = null;
  }
  if (start) {
    var walker = start.walker();
    while (start && start !== end) {
      callback(start);
      var next = walker.next();
      if (next) {
        start = next.node;
      } else {
        break;
      }
    }
  }
}
function isUnlinked(id) {
  var node = findNodeById(id);
  if (!node) {
    return true;
  }
  while (node && node.type !== "document") {
    if (!node.parent && !node.prev && !node.next) {
      return true;
    }
    node = node.parent;
  }
  return false;
}
var reLineEnding = /\r\n|\n|\r/;
function canBeContinuedListItem(lineText) {
  var spaceMatch = lineText.match(/^[ \t]+/);
  if (spaceMatch && (spaceMatch[0].length >= 2 || /\t/.test(spaceMatch[0]))) {
    return true;
  }
  var leftTrimmed = spaceMatch ? lineText.slice(spaceMatch.length) : lineText;
  return reBulletListMarker.test(leftTrimmed) || reOrderedListMarker.test(leftTrimmed);
}
function canBeContinuedTableBody(lineText) {
  return !isBlank(lineText) && lineText.indexOf("|") !== -1;
}
function createRefDefState(node) {
  var id = node.id, title = node.title, sourcepos = node.sourcepos, dest = node.dest;
  return {
    id,
    title,
    sourcepos,
    unlinked: false,
    destination: dest
  };
}
var ToastMark = (
  /** @class */
  (function() {
    function ToastMark2(contents, options) {
      this.refMap = {};
      this.refLinkCandidateMap = {};
      this.refDefCandidateMap = {};
      this.referenceDefinition = !!(options === null || options === void 0 ? void 0 : options.referenceDefinition);
      this.parser = new Parser(options);
      this.parser.setRefMaps(this.refMap, this.refLinkCandidateMap, this.refDefCandidateMap);
      this.eventHandlerMap = { change: [] };
      contents = contents || "";
      this.lineTexts = contents.split(reLineEnding);
      this.root = this.parser.parse(contents, this.lineTexts);
    }
    ToastMark2.prototype.updateLineTexts = function(startPos, endPos, newText) {
      var _a;
      var startLine = startPos[0], startCol = startPos[1];
      var endLine = endPos[0], endCol = endPos[1];
      var newLines = newText.split(reLineEnding);
      var newLineLen = newLines.length;
      var startLineText = this.lineTexts[startLine - 1];
      var endLineText = this.lineTexts[endLine - 1];
      newLines[0] = startLineText.slice(0, startCol - 1) + newLines[0];
      newLines[newLineLen - 1] = newLines[newLineLen - 1] + endLineText.slice(endCol - 1);
      var removedLineLen = endLine - startLine + 1;
      (_a = this.lineTexts).splice.apply(_a, __spreadArray([startLine - 1, removedLineLen], newLines));
      return newLineLen - removedLineLen;
    };
    ToastMark2.prototype.updateRootNodeState = function() {
      if (this.lineTexts.length === 1 && this.lineTexts[0] === "") {
        this.root.lastLineBlank = true;
        this.root.sourcepos = [
          [1, 1],
          [1, 0]
        ];
        return;
      }
      if (this.root.lastChild) {
        this.root.lastLineBlank = this.root.lastChild.lastLineBlank;
      }
      var lineTexts = this.lineTexts;
      var idx = lineTexts.length - 1;
      while (lineTexts[idx] === "") {
        idx -= 1;
      }
      if (lineTexts.length - 2 > idx) {
        idx += 1;
      }
      this.root.sourcepos[1] = [idx + 1, lineTexts[idx].length];
    };
    ToastMark2.prototype.replaceRangeNodes = function(startNode, endNode, newNodes) {
      if (!startNode) {
        if (endNode) {
          insertNodesBefore(endNode, newNodes);
          removeNodeById(endNode.id);
          endNode.unlink();
        } else {
          prependChildNodes(this.root, newNodes);
        }
      } else {
        insertNodesBefore(startNode, newNodes);
        removeNextUntil(startNode, endNode);
        [startNode.id, endNode.id].forEach(function(id) {
          return removeNodeById(id);
        });
        startNode.unlink();
      }
    };
    ToastMark2.prototype.getNodeRange = function(startPos, endPos) {
      var startNode = findChildNodeAtLine(this.root, startPos[0]);
      var endNode = findChildNodeAtLine(this.root, endPos[0]);
      if (endNode && endNode.next && endPos[0] + 1 === endNode.next.sourcepos[0][0]) {
        endNode = endNode.next;
      }
      return [startNode, endNode];
    };
    ToastMark2.prototype.trigger = function(eventName, param) {
      this.eventHandlerMap[eventName].forEach(function(handler) {
        handler(param);
      });
    };
    ToastMark2.prototype.extendEndLine = function(line) {
      while (this.lineTexts[line] === "") {
        line += 1;
      }
      return line;
    };
    ToastMark2.prototype.parseRange = function(startNode, endNode, startLine, endLine) {
      if (startNode && startNode.prev && (isList(startNode.prev) && canBeContinuedListItem(this.lineTexts[startLine - 1]) || isTable(startNode.prev) && canBeContinuedTableBody(this.lineTexts[startLine - 1]))) {
        startNode = startNode.prev;
        startLine = startNode.sourcepos[0][0];
      }
      var editedLines = this.lineTexts.slice(startLine - 1, endLine);
      var root = this.parser.partialParseStart(startLine, editedLines);
      var nextNode = endNode ? endNode.next : this.root.firstChild;
      var lastChild = root.lastChild;
      var isOpenedLastChildCodeBlock = lastChild && isCodeBlock(lastChild) && lastChild.open;
      var isOpenedLastChildCustomBlock = lastChild && isCustomBlock(lastChild) && lastChild.open;
      var isLastChildList = lastChild && isList(lastChild);
      while ((isOpenedLastChildCodeBlock || isOpenedLastChildCustomBlock) && nextNode || isLastChildList && nextNode && (nextNode.type === "list" || nextNode.sourcepos[0][1] >= 2)) {
        var newEndLine = this.extendEndLine(nextNode.sourcepos[1][0]);
        this.parser.partialParseExtends(this.lineTexts.slice(endLine, newEndLine));
        if (!startNode) {
          startNode = endNode;
        }
        endNode = nextNode;
        endLine = newEndLine;
        nextNode = nextNode.next;
      }
      this.parser.partialParseFinish();
      var newNodes = getChildNodes(root);
      return { newNodes, extStartNode: startNode, extEndNode: endNode };
    };
    ToastMark2.prototype.getRemovedNodeRange = function(extStartNode, extEndNode) {
      if (!extStartNode || extStartNode && isRefDef(extStartNode) || extEndNode && isRefDef(extEndNode)) {
        return null;
      }
      return {
        id: [extStartNode.id, extEndNode.id],
        line: [extStartNode.sourcepos[0][0] - 1, extEndNode.sourcepos[1][0] - 1]
      };
    };
    ToastMark2.prototype.markDeletedRefMap = function(extStartNode, extEndNode) {
      var _this = this;
      if (!isEmptyObj(this.refMap)) {
        var markDeleted = function(node) {
          if (isRefDef(node)) {
            var refDefState = _this.refMap[node.label];
            if (refDefState && node.id === refDefState.id) {
              refDefState.unlinked = true;
            }
          }
        };
        if (extStartNode) {
          invokeNextUntil(markDeleted, extStartNode.parent, extEndNode);
        }
        if (extEndNode) {
          invokeNextUntil(markDeleted, extEndNode);
        }
      }
    };
    ToastMark2.prototype.replaceWithNewRefDefState = function(nodes) {
      var _this = this;
      if (!isEmptyObj(this.refMap)) {
        var replaceWith_1 = function(node) {
          if (isRefDef(node)) {
            var label = node.label;
            var refDefState = _this.refMap[label];
            if (!refDefState || refDefState.unlinked) {
              _this.refMap[label] = createRefDefState(node);
            }
          }
        };
        nodes.forEach(function(node) {
          invokeNextUntil(replaceWith_1, node);
        });
      }
    };
    ToastMark2.prototype.replaceWithRefDefCandidate = function() {
      var _this = this;
      if (!isEmptyObj(this.refDefCandidateMap)) {
        iterateObject(this.refDefCandidateMap, function(_, candidate) {
          var label = candidate.label, sourcepos = candidate.sourcepos;
          var refDefState = _this.refMap[label];
          if (!refDefState || refDefState.unlinked || refDefState.sourcepos[0][0] > sourcepos[0][0]) {
            _this.refMap[label] = createRefDefState(candidate);
          }
        });
      }
    };
    ToastMark2.prototype.getRangeWithRefDef = function(startLine, endLine, startNode, endNode, lineDiff) {
      if (this.referenceDefinition && !isEmptyObj(this.refMap)) {
        var prevNode = findChildNodeAtLine(this.root, startLine - 1);
        var nextNode = findChildNodeAtLine(this.root, endLine + 1);
        if (prevNode && isRefDef(prevNode) && prevNode !== startNode && prevNode !== endNode) {
          startNode = prevNode;
          startLine = startNode.sourcepos[0][0];
        }
        if (nextNode && isRefDef(nextNode) && nextNode !== startNode && nextNode !== endNode) {
          endNode = nextNode;
          endLine = this.extendEndLine(endNode.sourcepos[1][0] + lineDiff);
        }
      }
      return [startNode, endNode, startLine, endLine];
    };
    ToastMark2.prototype.parse = function(startPos, endPos, lineDiff) {
      if (lineDiff === void 0) {
        lineDiff = 0;
      }
      var range2 = this.getNodeRange(startPos, endPos);
      var startNode = range2[0], endNode = range2[1];
      var startLine = startNode ? Math.min(startNode.sourcepos[0][0], startPos[0]) : startPos[0];
      var endLine = this.extendEndLine((endNode ? Math.max(endNode.sourcepos[1][0], endPos[0]) : endPos[0]) + lineDiff);
      var parseResult = this.parseRange.apply(this, this.getRangeWithRefDef(startLine, endLine, startNode, endNode, lineDiff));
      var newNodes = parseResult.newNodes, extStartNode = parseResult.extStartNode, extEndNode = parseResult.extEndNode;
      var removedNodeRange = this.getRemovedNodeRange(extStartNode, extEndNode);
      var nextNode = extEndNode ? extEndNode.next : this.root.firstChild;
      if (this.referenceDefinition) {
        this.markDeletedRefMap(extStartNode, extEndNode);
        this.replaceRangeNodes(extStartNode, extEndNode, newNodes);
        this.replaceWithNewRefDefState(newNodes);
      } else {
        this.replaceRangeNodes(extStartNode, extEndNode, newNodes);
      }
      return { nodes: newNodes, removedNodeRange, nextNode };
    };
    ToastMark2.prototype.parseRefLink = function() {
      var _this = this;
      var result = [];
      if (!isEmptyObj(this.refMap)) {
        iterateObject(this.refMap, function(label, value) {
          if (value.unlinked) {
            delete _this.refMap[label];
          }
          iterateObject(_this.refLinkCandidateMap, function(_, candidate) {
            var node = candidate.node, refLabel = candidate.refLabel;
            if (refLabel === label) {
              result.push(_this.parse(node.sourcepos[0], node.sourcepos[1]));
            }
          });
        });
      }
      return result;
    };
    ToastMark2.prototype.removeUnlinkedCandidate = function() {
      if (!isEmptyObj(this.refDefCandidateMap)) {
        [this.refLinkCandidateMap, this.refDefCandidateMap].forEach(function(candidateMap) {
          iterateObject(candidateMap, function(id) {
            if (isUnlinked(id)) {
              delete candidateMap[id];
            }
          });
        });
      }
    };
    ToastMark2.prototype.editMarkdown = function(startPos, endPos, newText) {
      var lineDiff = this.updateLineTexts(startPos, endPos, newText);
      var parseResult = this.parse(startPos, endPos, lineDiff);
      var editResult = omit(parseResult, "nextNode");
      updateNextLineNumbers(parseResult.nextNode, lineDiff);
      this.updateRootNodeState();
      var result = [editResult];
      if (this.referenceDefinition) {
        this.removeUnlinkedCandidate();
        this.replaceWithRefDefCandidate();
        result = result.concat(this.parseRefLink());
      }
      this.trigger("change", result);
      return result;
    };
    ToastMark2.prototype.getLineTexts = function() {
      return this.lineTexts;
    };
    ToastMark2.prototype.getRootNode = function() {
      return this.root;
    };
    ToastMark2.prototype.findNodeAtPosition = function(pos) {
      var node = findNodeAtPosition(this.root, pos);
      if (!node || node === this.root) {
        return null;
      }
      return node;
    };
    ToastMark2.prototype.findFirstNodeAtLine = function(line) {
      return findFirstNodeAtLine(this.root, line);
    };
    ToastMark2.prototype.on = function(eventName, callback) {
      this.eventHandlerMap[eventName].push(callback);
    };
    ToastMark2.prototype.off = function(eventName, callback) {
      var handlers2 = this.eventHandlerMap[eventName];
      var idx = handlers2.indexOf(callback);
      handlers2.splice(idx, 1);
    };
    ToastMark2.prototype.findNodeById = function(id) {
      return findNodeById(id);
    };
    ToastMark2.prototype.removeAllNode = function() {
      removeAllNode();
    };
    return ToastMark2;
  })()
);
var disallowedTags = [
  "title",
  "textarea",
  "style",
  "xmp",
  "iframe",
  "noembed",
  "noframes",
  "script",
  "plaintext"
];
var reDisallowedTag = new RegExp("<(/?(?:" + disallowedTags.join("|") + ")[^>]*>)", "ig");
function filterDisallowedTags(str) {
  if (reDisallowedTag.test(str)) {
    return str.replace(reDisallowedTag, function(_, group) {
      return "&lt;" + group;
    });
  }
  return str;
}
var baseConvertors$1 = {
  heading: function(node, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "h" + node.level,
      outerNewLine: true
    };
  },
  text: function(node) {
    return {
      type: "text",
      content: node.literal
    };
  },
  softbreak: function(_, _a) {
    var options = _a.options;
    return {
      type: "html",
      content: options.softbreak
    };
  },
  linebreak: function() {
    return {
      type: "html",
      content: "<br />\n"
    };
  },
  emph: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "em"
    };
  },
  strong: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "strong"
    };
  },
  paragraph: function(node, _a) {
    var _b;
    var entering = _a.entering;
    var grandparent = (_b = node.parent) === null || _b === void 0 ? void 0 : _b.parent;
    if (grandparent && grandparent.type === "list") {
      if (grandparent.listData.tight) {
        return null;
      }
    }
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "p",
      outerNewLine: true
    };
  },
  thematicBreak: function() {
    return {
      type: "openTag",
      tagName: "hr",
      outerNewLine: true,
      selfClose: true
    };
  },
  blockQuote: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "blockquote",
      outerNewLine: true,
      innerNewLine: true
    };
  },
  list: function(node, _a) {
    var entering = _a.entering;
    var _b = node.listData, type = _b.type, start = _b.start;
    var tagName = type === "bullet" ? "ul" : "ol";
    var attributes = {};
    if (tagName === "ol" && start !== null && start !== 1) {
      attributes.start = start.toString();
    }
    return {
      type: entering ? "openTag" : "closeTag",
      tagName,
      attributes,
      outerNewLine: true
    };
  },
  item: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "li",
      outerNewLine: true
    };
  },
  htmlInline: function(node, _a) {
    var options = _a.options;
    var content = options.tagFilter ? filterDisallowedTags(node.literal) : node.literal;
    return { type: "html", content };
  },
  htmlBlock: function(node, _a) {
    var options = _a.options;
    var content = options.tagFilter ? filterDisallowedTags(node.literal) : node.literal;
    if (options.nodeId) {
      return [
        { type: "openTag", tagName: "div", outerNewLine: true },
        { type: "html", content },
        { type: "closeTag", tagName: "div", outerNewLine: true }
      ];
    }
    return { type: "html", content, outerNewLine: true };
  },
  code: function(node) {
    return [
      { type: "openTag", tagName: "code" },
      { type: "text", content: node.literal },
      { type: "closeTag", tagName: "code" }
    ];
  },
  codeBlock: function(node) {
    var infoStr = node.info;
    var infoWords = infoStr ? infoStr.split(/\s+/) : [];
    var codeClassNames = [];
    if (infoWords.length > 0 && infoWords[0].length > 0) {
      codeClassNames.push("language-" + escapeXml(infoWords[0]));
    }
    return [
      { type: "openTag", tagName: "pre", outerNewLine: true },
      { type: "openTag", tagName: "code", classNames: codeClassNames },
      { type: "text", content: node.literal },
      { type: "closeTag", tagName: "code" },
      { type: "closeTag", tagName: "pre", outerNewLine: true }
    ];
  },
  link: function(node, _a) {
    var entering = _a.entering;
    if (entering) {
      var _b = node, title = _b.title, destination = _b.destination;
      return {
        type: "openTag",
        tagName: "a",
        attributes: __assign({ href: escapeXml(destination) }, title && { title: escapeXml(title) })
      };
    }
    return { type: "closeTag", tagName: "a" };
  },
  image: function(node, _a) {
    var getChildrenText2 = _a.getChildrenText, skipChildren = _a.skipChildren;
    var _b = node, title = _b.title, destination = _b.destination;
    skipChildren();
    return {
      type: "openTag",
      tagName: "img",
      selfClose: true,
      attributes: __assign({ src: escapeXml(destination), alt: getChildrenText2(node) }, title && { title: escapeXml(title) })
    };
  },
  customBlock: function(node, context, convertors2) {
    var info = node.info.trim().toLowerCase();
    var customConvertor = convertors2[info];
    if (customConvertor) {
      try {
        return customConvertor(node, context);
      } catch (e) {
        console.warn("[@toast-ui/editor] - The error occurred when " + info + " block node was parsed in markdown renderer: " + e);
      }
    }
    return [
      { type: "openTag", tagName: "div", outerNewLine: true },
      { type: "text", content: node.literal },
      { type: "closeTag", tagName: "div", outerNewLine: true }
    ];
  },
  frontMatter: function(node) {
    return [
      {
        type: "openTag",
        tagName: "div",
        outerNewLine: true,
        // Because front matter is metadata, it should not be render.
        attributes: { style: "white-space: pre; display: none;" }
      },
      { type: "text", content: node.literal },
      { type: "closeTag", tagName: "div", outerNewLine: true }
    ];
  },
  customInline: function(node, context, convertors2) {
    var _a = node, info = _a.info, firstChild = _a.firstChild;
    var nomalizedInfo = info.trim().toLowerCase();
    var customConvertor = convertors2[nomalizedInfo];
    var entering = context.entering;
    if (customConvertor) {
      try {
        return customConvertor(node, context);
      } catch (e) {
        console.warn("[@toast-ui/editor] - The error occurred when " + nomalizedInfo + " inline node was parsed in markdown renderer: " + e);
      }
    }
    return entering ? [
      { type: "openTag", tagName: "span" },
      { type: "text", content: "$$" + info + (firstChild ? " " : "") }
    ] : [
      { type: "text", content: "$$" },
      { type: "closeTag", tagName: "span" }
    ];
  }
};
var gfmConvertors = {
  strike: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "del"
    };
  },
  item: function(node, _a) {
    var entering = _a.entering;
    var _b = node.listData, checked = _b.checked, task2 = _b.task;
    if (entering) {
      var itemTag = {
        type: "openTag",
        tagName: "li",
        outerNewLine: true
      };
      if (task2) {
        return [
          itemTag,
          {
            type: "openTag",
            tagName: "input",
            selfClose: true,
            attributes: __assign(__assign({}, checked && { checked: "" }), { disabled: "", type: "checkbox" })
          },
          {
            type: "text",
            content: " "
          }
        ];
      }
      return itemTag;
    }
    return {
      type: "closeTag",
      tagName: "li",
      outerNewLine: true
    };
  },
  table: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "table",
      outerNewLine: true
    };
  },
  tableHead: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "thead",
      outerNewLine: true
    };
  },
  tableBody: function(_, _a) {
    var entering = _a.entering;
    return {
      type: entering ? "openTag" : "closeTag",
      tagName: "tbody",
      outerNewLine: true
    };
  },
  tableRow: function(node, _a) {
    var entering = _a.entering;
    if (entering) {
      return {
        type: "openTag",
        tagName: "tr",
        outerNewLine: true
      };
    }
    var result = [];
    if (node.lastChild) {
      var columnLen = node.parent.parent.columns.length;
      var lastColIdx = node.lastChild.endIdx;
      for (var i = lastColIdx + 1; i < columnLen; i += 1) {
        result.push({
          type: "openTag",
          tagName: "td",
          outerNewLine: true
        }, {
          type: "closeTag",
          tagName: "td",
          outerNewLine: true
        });
      }
    }
    result.push({
      type: "closeTag",
      tagName: "tr",
      outerNewLine: true
    });
    return result;
  },
  tableCell: function(node, _a) {
    var entering = _a.entering;
    if (node.ignored) {
      return {
        type: "text",
        content: ""
      };
    }
    var tablePart = node.parent.parent;
    var tagName = tablePart.type === "tableHead" ? "th" : "td";
    var table2 = tablePart.parent;
    var columnInfo = table2.columns[node.startIdx];
    var attributes = (columnInfo === null || columnInfo === void 0 ? void 0 : columnInfo.align) ? { align: columnInfo.align } : null;
    if (entering) {
      return __assign({ type: "openTag", tagName, outerNewLine: true }, attributes && { attributes });
    }
    return {
      type: "closeTag",
      tagName,
      outerNewLine: true
    };
  }
};
var defaultOptions = {
  softbreak: "\n",
  gfm: false,
  tagFilter: false,
  nodeId: false
};
function getChildrenText(node) {
  var buffer = [];
  var walker = node.walker();
  var event = null;
  while (event = walker.next()) {
    var node_1 = event.node;
    if (node_1.type === "text") {
      buffer.push(node_1.literal);
    }
  }
  return buffer.join("");
}
var Renderer = (
  /** @class */
  (function() {
    function Renderer2(customOptions) {
      this.buffer = [];
      this.options = __assign(__assign({}, defaultOptions), customOptions);
      this.convertors = this.createConvertors();
      delete this.options.convertors;
    }
    Renderer2.prototype.createConvertors = function() {
      var convertors2 = __assign({}, baseConvertors$1);
      if (this.options.gfm) {
        convertors2 = __assign(__assign({}, convertors2), gfmConvertors);
      }
      if (this.options.convertors) {
        var customConvertors_1 = this.options.convertors;
        var nodeTypes = Object.keys(customConvertors_1);
        var defaultConvertors_1 = __assign(__assign({}, baseConvertors$1), gfmConvertors);
        nodeTypes.forEach(function(nodeType) {
          var orgConvertor = convertors2[nodeType];
          var convertor = customConvertors_1[nodeType];
          var convertorType = Object.keys(defaultConvertors_1).indexOf(nodeType) === -1 ? nodeType.toLowerCase() : nodeType;
          if (orgConvertor) {
            convertors2[convertorType] = function(node, context, convertors3) {
              context.origin = function() {
                return orgConvertor(node, context, convertors3);
              };
              return convertor(node, context);
            };
          } else {
            convertors2[convertorType] = convertor;
          }
        });
      }
      return convertors2;
    };
    Renderer2.prototype.getConvertors = function() {
      return this.convertors;
    };
    Renderer2.prototype.getOptions = function() {
      return this.options;
    };
    Renderer2.prototype.render = function(rootNode) {
      var _this = this;
      this.buffer = [];
      var walker = rootNode.walker();
      var event = null;
      var _loop_1 = function() {
        var node = event.node, entering = event.entering;
        var convertor = this_1.convertors[node.type];
        if (!convertor) {
          return "continue";
        }
        var skipped = false;
        var context = {
          entering,
          leaf: !isContainer$1(node),
          options: this_1.options,
          getChildrenText,
          skipChildren: function() {
            skipped = true;
          }
        };
        var converted = isCustomBlock(node) || isCustomInline(node) ? convertor(node, context, this_1.convertors) : convertor(node, context);
        if (converted) {
          var htmlNodes = Array.isArray(converted) ? converted : [converted];
          htmlNodes.forEach(function(htmlNode, index2) {
            if (htmlNode.type === "openTag" && _this.options.nodeId && index2 === 0) {
              if (!htmlNode.attributes) {
                htmlNode.attributes = {};
              }
              htmlNode.attributes["data-nodeid"] = String(node.id);
            }
            _this.renderHTMLNode(htmlNode);
          });
          if (skipped) {
            walker.resumeAt(node, false);
            walker.next();
          }
        }
      };
      var this_1 = this;
      while (event = walker.next()) {
        _loop_1();
      }
      this.addNewLine();
      return this.buffer.join("");
    };
    Renderer2.prototype.renderHTMLNode = function(node) {
      switch (node.type) {
        case "openTag":
        case "closeTag":
          this.renderElementNode(node);
          break;
        case "text":
          this.renderTextNode(node);
          break;
        case "html":
          this.renderRawHtmlNode(node);
          break;
      }
    };
    Renderer2.prototype.generateOpenTagString = function(node) {
      var _this = this;
      var tagName = node.tagName, classNames = node.classNames, attributes = node.attributes;
      this.buffer.push("<" + tagName);
      if (classNames && classNames.length > 0) {
        this.buffer.push(' class="' + classNames.join(" ") + '"');
      }
      if (attributes) {
        Object.keys(attributes).forEach(function(attrName) {
          var attrValue = attributes[attrName];
          _this.buffer.push(" " + attrName + '="' + attrValue + '"');
        });
      }
      if (node.selfClose) {
        this.buffer.push(" /");
      }
      this.buffer.push(">");
    };
    Renderer2.prototype.generateCloseTagString = function(_a) {
      var tagName = _a.tagName;
      this.buffer.push("</" + tagName + ">");
    };
    Renderer2.prototype.addNewLine = function() {
      if (this.buffer.length && last(last(this.buffer)) !== "\n") {
        this.buffer.push("\n");
      }
    };
    Renderer2.prototype.addOuterNewLine = function(node) {
      if (node.outerNewLine) {
        this.addNewLine();
      }
    };
    Renderer2.prototype.addInnerNewLine = function(node) {
      if (node.innerNewLine) {
        this.addNewLine();
      }
    };
    Renderer2.prototype.renderTextNode = function(node) {
      this.buffer.push(escapeXml(node.content));
    };
    Renderer2.prototype.renderRawHtmlNode = function(node) {
      this.addOuterNewLine(node);
      this.buffer.push(node.content);
      this.addOuterNewLine(node);
    };
    Renderer2.prototype.renderElementNode = function(node) {
      if (node.type === "openTag") {
        this.addOuterNewLine(node);
        this.generateOpenTagString(node);
        if (node.selfClose) {
          this.addOuterNewLine(node);
        } else {
          this.addInnerNewLine(node);
        }
      } else {
        this.addInnerNewLine(node);
        this.generateCloseTagString(node);
        this.addOuterNewLine(node);
      }
    };
    return Renderer2;
  })()
);
function _toConsumableArray(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  } else {
    return Array.from(arr);
  }
}
var hasOwnProperty = Object.hasOwnProperty;
var setPrototypeOf = Object.setPrototypeOf;
var isFrozen = Object.isFrozen;
var getPrototypeOf = Object.getPrototypeOf;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var freeze = Object.freeze;
var seal = Object.seal;
var create = Object.create;
var _ref = typeof Reflect !== "undefined" && Reflect;
var apply2 = _ref.apply;
var construct = _ref.construct;
if (!apply2) {
  apply2 = function apply3(fun, thisValue, args) {
    return fun.apply(thisValue, args);
  };
}
if (!freeze) {
  freeze = function freeze2(x) {
    return x;
  };
}
if (!seal) {
  seal = function seal2(x) {
    return x;
  };
}
if (!construct) {
  construct = function construct2(Func, args) {
    return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
  };
}
var arrayForEach = unapply(Array.prototype.forEach);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim);
var regExpTest = unapply(RegExp.prototype.test);
var typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
  return function(thisArg) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return apply2(func, thisArg, args);
  };
}
function unconstruct(func) {
  return function() {
    for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    return construct(func, args);
  };
}
function addToSet(set, array) {
  if (setPrototypeOf) {
    setPrototypeOf(set, null);
  }
  var l = array.length;
  while (l--) {
    var element = array[l];
    if (typeof element === "string") {
      var lcElement = stringToLowerCase(element);
      if (lcElement !== element) {
        if (!isFrozen(array)) {
          array[l] = lcElement;
        }
        element = lcElement;
      }
    }
    set[element] = true;
  }
  return set;
}
function clone(object) {
  var newObject = create(null);
  var property = void 0;
  for (property in object) {
    if (apply2(hasOwnProperty, object, [property])) {
      newObject[property] = object[property];
    }
  }
  return newObject;
}
function lookupGetter(object, prop2) {
  while (object !== null) {
    var desc = getOwnPropertyDescriptor(object, prop2);
    if (desc) {
      if (desc.get) {
        return unapply(desc.get);
      }
      if (typeof desc.value === "function") {
        return unapply(desc.value);
      }
    }
    object = getPrototypeOf(object);
  }
  function fallbackValue(element) {
    console.warn("fallback value for", element);
    return null;
  }
  return fallbackValue;
}
var html$2 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]);
var svg = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]);
var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]);
var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "fedropshadow", "feimage", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]);
var mathMl = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover"]);
var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]);
var text = freeze(["#text"]);
var html$1$1 = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "xmlns", "slot"]);
var svg$1 = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "targetx", "targety", "transform", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]);
var mathMl$1 = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]);
var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]);
var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm);
var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
var IS_ALLOWED_URI = seal(
  /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  // eslint-disable-line no-useless-escape
);
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(
  /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
  // eslint-disable-line no-control-regex
);
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
  return typeof obj;
} : function(obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _toConsumableArray$1(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  } else {
    return Array.from(arr);
  }
}
var getGlobal = function getGlobal2() {
  return typeof window === "undefined" ? null : window;
};
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, document2) {
  if ((typeof trustedTypes === "undefined" ? "undefined" : _typeof(trustedTypes)) !== "object" || typeof trustedTypes.createPolicy !== "function") {
    return null;
  }
  var suffix = null;
  var ATTR_NAME = "data-tt-policy-suffix";
  if (document2.currentScript && document2.currentScript.hasAttribute(ATTR_NAME)) {
    suffix = document2.currentScript.getAttribute(ATTR_NAME);
  }
  var policyName = "dompurify" + (suffix ? "#" + suffix : "");
  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML: function createHTML(html$$1) {
        return html$$1;
      }
    });
  } catch (_) {
    console.warn("TrustedTypes policy " + policyName + " could not be created.");
    return null;
  }
};
function createDOMPurify() {
  var window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
  var DOMPurify = function DOMPurify2(root) {
    return createDOMPurify(root);
  };
  DOMPurify.version = "2.3.3";
  DOMPurify.removed = [];
  if (!window2 || !window2.document || window2.document.nodeType !== 9) {
    DOMPurify.isSupported = false;
    return DOMPurify;
  }
  var originalDocument = window2.document;
  var document2 = window2.document;
  var DocumentFragment = window2.DocumentFragment, HTMLTemplateElement = window2.HTMLTemplateElement, Node3 = window2.Node, Element2 = window2.Element, NodeFilter = window2.NodeFilter, _window$NamedNodeMap = window2.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window2.NamedNodeMap || window2.MozNamedAttrMap : _window$NamedNodeMap, Text2 = window2.Text, Comment = window2.Comment, DOMParser2 = window2.DOMParser, trustedTypes = window2.trustedTypes;
  var ElementPrototype = Element2.prototype;
  var cloneNode = lookupGetter(ElementPrototype, "cloneNode");
  var getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
  var getChildNodes2 = lookupGetter(ElementPrototype, "childNodes");
  var getParentNode2 = lookupGetter(ElementPrototype, "parentNode");
  if (typeof HTMLTemplateElement === "function") {
    var template = document2.createElement("template");
    if (template.content && template.content.ownerDocument) {
      document2 = template.content.ownerDocument;
    }
  }
  var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML("") : "";
  var _document = document2, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
  var importNode = originalDocument.importNode;
  var documentMode = {};
  try {
    documentMode = clone(document2).documentMode ? document2.documentMode : {};
  } catch (_) {
  }
  var hooks = {};
  DOMPurify.isSupported = typeof getParentNode2 === "function" && implementation && typeof implementation.createHTMLDocument !== "undefined" && documentMode !== 9;
  var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR, ERB_EXPR$$1 = ERB_EXPR, DATA_ATTR$$1 = DATA_ATTR, ARIA_ATTR$$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
  var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
  var ALLOWED_TAGS = null;
  var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html$2), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));
  var ALLOWED_ATTR = null;
  var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));
  var FORBID_TAGS = null;
  var FORBID_ATTR = null;
  var ALLOW_ARIA_ATTR = true;
  var ALLOW_DATA_ATTR = true;
  var ALLOW_UNKNOWN_PROTOCOLS = false;
  var SAFE_FOR_TEMPLATES = false;
  var WHOLE_DOCUMENT = false;
  var SET_CONFIG = false;
  var FORCE_BODY = false;
  var RETURN_DOM = false;
  var RETURN_DOM_FRAGMENT = false;
  var RETURN_DOM_IMPORT = true;
  var RETURN_TRUSTED_TYPE = false;
  var SANITIZE_DOM = true;
  var KEEP_CONTENT = true;
  var IN_PLACE = false;
  var USE_PROFILES = {};
  var FORBID_CONTENTS = null;
  var DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
  var DATA_URI_TAGS = null;
  var DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
  var URI_SAFE_ATTRIBUTES = null;
  var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
  var MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
  var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
  var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
  var NAMESPACE = HTML_NAMESPACE;
  var IS_EMPTY_INPUT = false;
  var PARSER_MEDIA_TYPE = void 0;
  var SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"];
  var DEFAULT_PARSER_MEDIA_TYPE = "text/html";
  var transformCaseFunc = void 0;
  var CONFIG = null;
  var formElement = document2.createElement("form");
  var _parseConfig = function _parseConfig2(cfg) {
    if (CONFIG && CONFIG === cfg) {
      return;
    }
    if (!cfg || (typeof cfg === "undefined" ? "undefined" : _typeof(cfg)) !== "object") {
      cfg = {};
    }
    cfg = clone(cfg);
    ALLOWED_TAGS = "ALLOWED_TAGS" in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
    ALLOWED_ATTR = "ALLOWED_ATTR" in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
    URI_SAFE_ATTRIBUTES = "ADD_URI_SAFE_ATTR" in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
    DATA_URI_TAGS = "ADD_DATA_URI_TAGS" in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
    FORBID_CONTENTS = "FORBID_CONTENTS" in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
    FORBID_TAGS = "FORBID_TAGS" in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
    FORBID_ATTR = "FORBID_ATTR" in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
    USE_PROFILES = "USE_PROFILES" in cfg ? cfg.USE_PROFILES : false;
    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
    RETURN_DOM = cfg.RETURN_DOM || false;
    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
    RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false;
    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
    FORCE_BODY = cfg.FORCE_BODY || false;
    SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
    KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
    IN_PLACE = cfg.IN_PLACE || false;
    IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
    NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
    PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
    SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
    transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? function(x) {
      return x;
    } : stringToLowerCase;
    if (SAFE_FOR_TEMPLATES) {
      ALLOW_DATA_ATTR = false;
    }
    if (RETURN_DOM_FRAGMENT) {
      RETURN_DOM = true;
    }
    if (USE_PROFILES) {
      ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
      ALLOWED_ATTR = [];
      if (USE_PROFILES.html === true) {
        addToSet(ALLOWED_TAGS, html$2);
        addToSet(ALLOWED_ATTR, html$1$1);
      }
      if (USE_PROFILES.svg === true) {
        addToSet(ALLOWED_TAGS, svg);
        addToSet(ALLOWED_ATTR, svg$1);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.svgFilters === true) {
        addToSet(ALLOWED_TAGS, svgFilters);
        addToSet(ALLOWED_ATTR, svg$1);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.mathMl === true) {
        addToSet(ALLOWED_TAGS, mathMl);
        addToSet(ALLOWED_ATTR, mathMl$1);
        addToSet(ALLOWED_ATTR, xml);
      }
    }
    if (cfg.ADD_TAGS) {
      if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
        ALLOWED_TAGS = clone(ALLOWED_TAGS);
      }
      addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
    }
    if (cfg.ADD_ATTR) {
      if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
        ALLOWED_ATTR = clone(ALLOWED_ATTR);
      }
      addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
    }
    if (cfg.ADD_URI_SAFE_ATTR) {
      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
    }
    if (cfg.FORBID_CONTENTS) {
      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
        FORBID_CONTENTS = clone(FORBID_CONTENTS);
      }
      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
    }
    if (KEEP_CONTENT) {
      ALLOWED_TAGS["#text"] = true;
    }
    if (WHOLE_DOCUMENT) {
      addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
    }
    if (ALLOWED_TAGS.table) {
      addToSet(ALLOWED_TAGS, ["tbody"]);
      delete FORBID_TAGS.tbody;
    }
    if (freeze) {
      freeze(cfg);
    }
    CONFIG = cfg;
  };
  var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
  var HTML_INTEGRATION_POINTS = addToSet({}, ["foreignobject", "desc", "title", "annotation-xml"]);
  var ALL_SVG_TAGS = addToSet({}, svg);
  addToSet(ALL_SVG_TAGS, svgFilters);
  addToSet(ALL_SVG_TAGS, svgDisallowed);
  var ALL_MATHML_TAGS = addToSet({}, mathMl);
  addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  var _checkValidNamespace = function _checkValidNamespace2(element) {
    var parent = getParentNode2(element);
    if (!parent || !parent.tagName) {
      parent = {
        namespaceURI: HTML_NAMESPACE,
        tagName: "template"
      };
    }
    var tagName = stringToLowerCase(element.tagName);
    var parentTagName = stringToLowerCase(parent.tagName);
    if (element.namespaceURI === SVG_NAMESPACE) {
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === "svg";
      }
      if (parent.namespaceURI === MATHML_NAMESPACE) {
        return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
      }
      return Boolean(ALL_SVG_TAGS[tagName]);
    }
    if (element.namespaceURI === MATHML_NAMESPACE) {
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === "math";
      }
      if (parent.namespaceURI === SVG_NAMESPACE) {
        return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
      }
      return Boolean(ALL_MATHML_TAGS[tagName]);
    }
    if (element.namespaceURI === HTML_NAMESPACE) {
      if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      var commonSvgAndHTMLElements = addToSet({}, ["title", "style", "font", "a", "script"]);
      return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);
    }
    return false;
  };
  var _forceRemove = function _forceRemove2(node) {
    arrayPush(DOMPurify.removed, { element: node });
    try {
      node.parentNode.removeChild(node);
    } catch (_) {
      try {
        node.outerHTML = emptyHTML;
      } catch (_2) {
        node.remove();
      }
    }
  };
  var _removeAttribute = function _removeAttribute2(name, node) {
    try {
      arrayPush(DOMPurify.removed, {
        attribute: node.getAttributeNode(name),
        from: node
      });
    } catch (_) {
      arrayPush(DOMPurify.removed, {
        attribute: null,
        from: node
      });
    }
    node.removeAttribute(name);
    if (name === "is" && !ALLOWED_ATTR[name]) {
      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
        try {
          _forceRemove(node);
        } catch (_) {
        }
      } else {
        try {
          node.setAttribute(name, "");
        } catch (_) {
        }
      }
    }
  };
  var _initDocument = function _initDocument2(dirty) {
    var doc3 = void 0;
    var leadingWhitespace = void 0;
    if (FORCE_BODY) {
      dirty = "<remove></remove>" + dirty;
    } else {
      var matches3 = stringMatch(dirty, /^[\r\n\t ]+/);
      leadingWhitespace = matches3 && matches3[0];
    }
    if (PARSER_MEDIA_TYPE === "application/xhtml+xml") {
      dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + "</body></html>";
    }
    var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
    if (NAMESPACE === HTML_NAMESPACE) {
      try {
        doc3 = new DOMParser2().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
      } catch (_) {
      }
    }
    if (!doc3 || !doc3.documentElement) {
      doc3 = implementation.createDocument(NAMESPACE, "template", null);
      try {
        doc3.documentElement.innerHTML = IS_EMPTY_INPUT ? "" : dirtyPayload;
      } catch (_) {
      }
    }
    var body = doc3.body || doc3.documentElement;
    if (dirty && leadingWhitespace) {
      body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null);
    }
    if (NAMESPACE === HTML_NAMESPACE) {
      return getElementsByTagName.call(doc3, WHOLE_DOCUMENT ? "html" : "body")[0];
    }
    return WHOLE_DOCUMENT ? doc3.documentElement : body;
  };
  var _createIterator = function _createIterator2(root) {
    return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  };
  var _isClobbered = function _isClobbered2(elm) {
    if (elm instanceof Text2 || elm instanceof Comment) {
      return false;
    }
    if (typeof elm.nodeName !== "string" || typeof elm.textContent !== "string" || typeof elm.removeChild !== "function" || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== "function" || typeof elm.setAttribute !== "function" || typeof elm.namespaceURI !== "string" || typeof elm.insertBefore !== "function") {
      return true;
    }
    return false;
  };
  var _isNode = function _isNode2(object) {
    return (typeof Node3 === "undefined" ? "undefined" : _typeof(Node3)) === "object" ? object instanceof Node3 : object && (typeof object === "undefined" ? "undefined" : _typeof(object)) === "object" && typeof object.nodeType === "number" && typeof object.nodeName === "string";
  };
  var _executeHook = function _executeHook2(entryPoint, currentNode, data) {
    if (!hooks[entryPoint]) {
      return;
    }
    arrayForEach(hooks[entryPoint], function(hook) {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  };
  var _sanitizeElements = function _sanitizeElements2(currentNode) {
    var content = void 0;
    _executeHook("beforeSanitizeElements", currentNode, null);
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
      _forceRemove(currentNode);
      return true;
    }
    var tagName = transformCaseFunc(currentNode.nodeName);
    _executeHook("uponSanitizeElement", currentNode, {
      tagName,
      allowedTags: ALLOWED_TAGS
    });
    if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }
    if (tagName === "select" && regExpTest(/<template/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
        var parentNode2 = getParentNode2(currentNode) || currentNode.parentNode;
        var childNodes = getChildNodes2(currentNode) || currentNode.childNodes;
        if (childNodes && parentNode2) {
          var childCount = childNodes.length;
          for (var i = childCount - 1; i >= 0; --i) {
            parentNode2.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
          }
        }
      }
      _forceRemove(currentNode);
      return true;
    }
    if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    if ((tagName === "noscript" || tagName === "noembed") && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
      content = currentNode.textContent;
      content = stringReplace(content, MUSTACHE_EXPR$$1, " ");
      content = stringReplace(content, ERB_EXPR$$1, " ");
      if (currentNode.textContent !== content) {
        arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
        currentNode.textContent = content;
      }
    }
    _executeHook("afterSanitizeElements", currentNode, null);
    return false;
  };
  var _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) {
    if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) {
      return false;
    }
    if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName)) ;
    else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName)) ;
    else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
      return false;
    } else if (URI_SAFE_ATTRIBUTES[lcName]) ;
    else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, ""))) ;
    else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ;
    else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, ""))) ;
    else if (!value) ;
    else {
      return false;
    }
    return true;
  };
  var _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
    var attr = void 0;
    var value = void 0;
    var lcName = void 0;
    var l = void 0;
    _executeHook("beforeSanitizeAttributes", currentNode, null);
    var attributes = currentNode.attributes;
    if (!attributes) {
      return;
    }
    var hookEvent = {
      attrName: "",
      attrValue: "",
      keepAttr: true,
      allowedAttributes: ALLOWED_ATTR
    };
    l = attributes.length;
    while (l--) {
      attr = attributes[l];
      var _attr = attr, name = _attr.name, namespaceURI = _attr.namespaceURI;
      value = stringTrim(attr.value);
      lcName = transformCaseFunc(name);
      hookEvent.attrName = lcName;
      hookEvent.attrValue = value;
      hookEvent.keepAttr = true;
      hookEvent.forceKeepAttr = void 0;
      _executeHook("uponSanitizeAttribute", currentNode, hookEvent);
      value = hookEvent.attrValue;
      if (hookEvent.forceKeepAttr) {
        continue;
      }
      _removeAttribute(name, currentNode);
      if (!hookEvent.keepAttr) {
        continue;
      }
      if (regExpTest(/\/>/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }
      if (SAFE_FOR_TEMPLATES) {
        value = stringReplace(value, MUSTACHE_EXPR$$1, " ");
        value = stringReplace(value, ERB_EXPR$$1, " ");
      }
      var lcTag = transformCaseFunc(currentNode.nodeName);
      if (!_isValidAttribute(lcTag, lcName, value)) {
        continue;
      }
      try {
        if (namespaceURI) {
          currentNode.setAttributeNS(namespaceURI, name, value);
        } else {
          currentNode.setAttribute(name, value);
        }
        arrayPop(DOMPurify.removed);
      } catch (_) {
      }
    }
    _executeHook("afterSanitizeAttributes", currentNode, null);
  };
  var _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
    var shadowNode = void 0;
    var shadowIterator = _createIterator(fragment);
    _executeHook("beforeSanitizeShadowDOM", fragment, null);
    while (shadowNode = shadowIterator.nextNode()) {
      _executeHook("uponSanitizeShadowNode", shadowNode, null);
      if (_sanitizeElements(shadowNode)) {
        continue;
      }
      if (shadowNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM2(shadowNode.content);
      }
      _sanitizeAttributes(shadowNode);
    }
    _executeHook("afterSanitizeShadowDOM", fragment, null);
  };
  DOMPurify.sanitize = function(dirty, cfg) {
    var body = void 0;
    var importedNode = void 0;
    var currentNode = void 0;
    var oldNode = void 0;
    var returnNode = void 0;
    IS_EMPTY_INPUT = !dirty;
    if (IS_EMPTY_INPUT) {
      dirty = "<!-->";
    }
    if (typeof dirty !== "string" && !_isNode(dirty)) {
      if (typeof dirty.toString !== "function") {
        throw typeErrorCreate("toString is not a function");
      } else {
        dirty = dirty.toString();
        if (typeof dirty !== "string") {
          throw typeErrorCreate("dirty is not a string, aborting");
        }
      }
    }
    if (!DOMPurify.isSupported) {
      if (_typeof(window2.toStaticHTML) === "object" || typeof window2.toStaticHTML === "function") {
        if (typeof dirty === "string") {
          return window2.toStaticHTML(dirty);
        }
        if (_isNode(dirty)) {
          return window2.toStaticHTML(dirty.outerHTML);
        }
      }
      return dirty;
    }
    if (!SET_CONFIG) {
      _parseConfig(cfg);
    }
    DOMPurify.removed = [];
    if (typeof dirty === "string") {
      IN_PLACE = false;
    }
    if (IN_PLACE) ;
    else if (dirty instanceof Node3) {
      body = _initDocument("<!---->");
      importedNode = body.ownerDocument.importNode(dirty, true);
      if (importedNode.nodeType === 1 && importedNode.nodeName === "BODY") {
        body = importedNode;
      } else if (importedNode.nodeName === "HTML") {
        body = importedNode;
      } else {
        body.appendChild(importedNode);
      }
    } else {
      if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
      dirty.indexOf("<") === -1) {
        return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
      }
      body = _initDocument(dirty);
      if (!body) {
        return RETURN_DOM ? null : emptyHTML;
      }
    }
    if (body && FORCE_BODY) {
      _forceRemove(body.firstChild);
    }
    var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
    while (currentNode = nodeIterator.nextNode()) {
      if (currentNode.nodeType === 3 && currentNode === oldNode) {
        continue;
      }
      if (_sanitizeElements(currentNode)) {
        continue;
      }
      if (currentNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(currentNode.content);
      }
      _sanitizeAttributes(currentNode);
      oldNode = currentNode;
    }
    oldNode = null;
    if (IN_PLACE) {
      return dirty;
    }
    if (RETURN_DOM) {
      if (RETURN_DOM_FRAGMENT) {
        returnNode = createDocumentFragment.call(body.ownerDocument);
        while (body.firstChild) {
          returnNode.appendChild(body.firstChild);
        }
      } else {
        returnNode = body;
      }
      if (RETURN_DOM_IMPORT) {
        returnNode = importNode.call(originalDocument, returnNode, true);
      }
      return returnNode;
    }
    var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
    if (SAFE_FOR_TEMPLATES) {
      serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, " ");
      serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, " ");
    }
    return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  };
  DOMPurify.setConfig = function(cfg) {
    _parseConfig(cfg);
    SET_CONFIG = true;
  };
  DOMPurify.clearConfig = function() {
    CONFIG = null;
    SET_CONFIG = false;
  };
  DOMPurify.isValidAttribute = function(tag, attr, value) {
    if (!CONFIG) {
      _parseConfig({});
    }
    var lcTag = transformCaseFunc(tag);
    var lcName = transformCaseFunc(attr);
    return _isValidAttribute(lcTag, lcName, value);
  };
  DOMPurify.addHook = function(entryPoint, hookFunction) {
    if (typeof hookFunction !== "function") {
      return;
    }
    hooks[entryPoint] = hooks[entryPoint] || [];
    arrayPush(hooks[entryPoint], hookFunction);
  };
  DOMPurify.removeHook = function(entryPoint) {
    if (hooks[entryPoint]) {
      arrayPop(hooks[entryPoint]);
    }
  };
  DOMPurify.removeHooks = function(entryPoint) {
    if (hooks[entryPoint]) {
      hooks[entryPoint] = [];
    }
  };
  DOMPurify.removeAllHooks = function() {
    hooks = {};
  };
  return DOMPurify;
}
var purify = createDOMPurify();
var CAN_BE_WHITE_TAG_LIST = ["iframe", "embed"];
var whiteTagList = [];
function registerTagWhitelistIfPossible(tagName) {
  if (includes(CAN_BE_WHITE_TAG_LIST, tagName)) {
    whiteTagList.push(tagName.toLowerCase());
  }
}
function sanitizeHTML(html2, options) {
  return purify.sanitize(html2, __assign$1({ ADD_TAGS: whiteTagList, ADD_ATTR: ["rel", "target", "hreflang", "type"], FORBID_TAGS: [
    "input",
    "script",
    "textarea",
    "form",
    "button",
    "select",
    "meta",
    "style",
    "link",
    "title",
    "object",
    "base"
  ] }, options));
}
function getChildrenHTML(node, typeName) {
  return node.literal.replace(new RegExp("(<\\s*" + typeName + "[^>]*>)|(</" + typeName + "\\s*[>])", "ig"), "").trim();
}
function getHTMLAttrsByHTMLString(html2) {
  html2 = html2.match(reHTMLTag)[0];
  var attrs = html2.match(new RegExp(ATTRIBUTE$1, "g"));
  return attrs ? attrs.reduce(function(acc, attr) {
    var _a = attr.trim().split("="), name = _a[0], values = _a.slice(1);
    if (values.length) {
      acc[name] = values.join("=").replace(/'|"/g, "").trim();
    }
    return acc;
  }, {}) : {};
}
function getHTMLAttrs(dom) {
  return toArray_1(dom.attributes).reduce(function(acc, attr) {
    acc[attr.nodeName] = attr.nodeValue;
    return acc;
  }, {});
}
function sanitizeDOM(node, typeName, sanitizer, wwToDOMAdaptor) {
  var dom = wwToDOMAdaptor.getToDOMNode(typeName)(node);
  var html2 = sanitizer(dom.outerHTML);
  var container = document.createElement("div");
  container.innerHTML = html2;
  dom = container.firstChild;
  var htmlAttrs = getHTMLAttrs(dom);
  return { dom, htmlAttrs };
}
var schemaFactory = {
  htmlBlock: function(typeName, sanitizeHTML2, wwToDOMAdaptor) {
    return {
      atom: true,
      content: "block+",
      group: "block",
      attrs: {
        htmlAttrs: { default: {} },
        childrenHTML: { default: "" },
        htmlBlock: { default: true }
      },
      parseDOM: [
        {
          tag: typeName,
          getAttrs: function(dom) {
            return {
              htmlAttrs: getHTMLAttrs(dom),
              childrenHTML: dom.innerHTML
            };
          }
        }
      ],
      toDOM: function(node) {
        var _a = sanitizeDOM(node, typeName, sanitizeHTML2, wwToDOMAdaptor), dom = _a.dom, htmlAttrs = _a.htmlAttrs;
        htmlAttrs.class = htmlAttrs.class ? htmlAttrs.class + " html-block" : "html-block";
        return __spreadArray$1([typeName, htmlAttrs], toArray_1(dom.childNodes));
      }
    };
  },
  htmlInline: function(typeName, sanitizeHTML2, wwToDOMAdaptor) {
    return {
      attrs: {
        htmlAttrs: { default: {} },
        htmlInline: { default: true }
      },
      parseDOM: [
        {
          tag: typeName,
          getAttrs: function(dom) {
            return {
              htmlAttrs: getHTMLAttrs(dom)
            };
          }
        }
      ],
      toDOM: function(node) {
        var htmlAttrs = sanitizeDOM(node, typeName, sanitizeHTML2, wwToDOMAdaptor).htmlAttrs;
        return [typeName, htmlAttrs, 0];
      }
    };
  }
};
function createHTMLSchemaMap(convertorMap, sanitizeHTML2, wwToDOMAdaptor) {
  var htmlSchemaMap = { nodes: {}, marks: {} };
  ["htmlBlock", "htmlInline"].forEach(function(htmlType) {
    if (convertorMap[htmlType]) {
      Object.keys(convertorMap[htmlType]).forEach(function(type) {
        var targetType = htmlType === "htmlBlock" ? "nodes" : "marks";
        registerTagWhitelistIfPossible(type);
        htmlSchemaMap[targetType][type] = schemaFactory[htmlType](type, sanitizeHTML2, wwToDOMAdaptor);
      });
    }
  });
  return htmlSchemaMap;
}
var reCloseTag = /^\s*<\s*\//;
var baseConvertors = {
  paragraph: function(_, _a) {
    var entering = _a.entering, origin = _a.origin, options = _a.options;
    if (options.nodeId) {
      return {
        type: entering ? "openTag" : "closeTag",
        outerNewLine: true,
        tagName: "p"
      };
    }
    return origin();
  },
  softbreak: function(node) {
    var isPrevNodeHTML = node.prev && node.prev.type === "htmlInline";
    var isPrevBR = isPrevNodeHTML && /<br ?\/?>/.test(node.prev.literal);
    var content = isPrevBR ? "\n" : "<br>\n";
    return { type: "html", content };
  },
  item: function(node, _a) {
    var entering = _a.entering;
    if (entering) {
      var attributes = {};
      var classNames = [];
      if (node.listData.task) {
        attributes["data-task"] = "";
        classNames.push("task-list-item");
        if (node.listData.checked) {
          classNames.push("checked");
          attributes["data-task-checked"] = "";
        }
      }
      return {
        type: "openTag",
        tagName: "li",
        classNames,
        attributes,
        outerNewLine: true
      };
    }
    return {
      type: "closeTag",
      tagName: "li",
      outerNewLine: true
    };
  },
  code: function(node) {
    var attributes = { "data-backticks": String(node.tickCount) };
    return [
      { type: "openTag", tagName: "code", attributes },
      { type: "text", content: node.literal },
      { type: "closeTag", tagName: "code" }
    ];
  },
  codeBlock: function(node) {
    var _a = node, fenceLength = _a.fenceLength, info = _a.info;
    var infoWords = info ? info.split(/\s+/) : [];
    var preClasses = [];
    var codeAttrs = {};
    if (fenceLength > 3) {
      codeAttrs["data-backticks"] = fenceLength;
    }
    if (infoWords.length > 0 && infoWords[0].length > 0) {
      var lang2 = infoWords[0];
      preClasses.push("lang-" + lang2);
      codeAttrs["data-language"] = lang2;
    }
    return [
      { type: "openTag", tagName: "pre", classNames: preClasses },
      { type: "openTag", tagName: "code", attributes: codeAttrs },
      { type: "text", content: node.literal },
      { type: "closeTag", tagName: "code" },
      { type: "closeTag", tagName: "pre" }
    ];
  },
  customInline: function(node, _a) {
    var origin = _a.origin, entering = _a.entering, skipChildren = _a.skipChildren;
    var info = node.info;
    if (info.indexOf("widget") !== -1 && entering) {
      skipChildren();
      var content = getWidgetContent(node);
      var htmlInline = widgetToDOM(info, content).outerHTML;
      return [
        { type: "openTag", tagName: "span", classNames: ["tui-widget"] },
        { type: "html", content: htmlInline },
        { type: "closeTag", tagName: "span" }
      ];
    }
    return origin();
  }
};
function getHTMLRenderConvertors(linkAttributes, customConvertors) {
  var convertors2 = __assign$1({}, baseConvertors);
  if (linkAttributes) {
    convertors2.link = function(_, _a) {
      var entering = _a.entering, origin = _a.origin;
      var result = origin();
      if (entering) {
        result.attributes = __assign$1(__assign$1({}, result.attributes), linkAttributes);
      }
      return result;
    };
  }
  if (customConvertors) {
    Object.keys(customConvertors).forEach(function(nodeType) {
      var orgConvertor = convertors2[nodeType];
      var customConvertor = customConvertors[nodeType];
      if (orgConvertor && isFunction_1(customConvertor)) {
        convertors2[nodeType] = function(node, context) {
          var newContext = __assign$1({}, context);
          newContext.origin = function() {
            return orgConvertor(node, context);
          };
          return customConvertor(node, newContext);
        };
      } else if (includes(["htmlBlock", "htmlInline"], nodeType) && !isFunction_1(customConvertor)) {
        convertors2[nodeType] = function(node, context) {
          var matched = node.literal.match(reHTMLTag);
          if (matched) {
            var rootHTML = matched[0], openTagName = matched[1], closeTagName = matched[3];
            var typeName = (openTagName || closeTagName).toLowerCase();
            var htmlConvertor = customConvertor[typeName];
            var childrenHTML = getChildrenHTML(node, typeName);
            if (htmlConvertor) {
              var newNode = __assign$1({}, node);
              newNode.attrs = getHTMLAttrsByHTMLString(rootHTML);
              newNode.childrenHTML = childrenHTML;
              newNode.type = typeName;
              context.entering = !reCloseTag.test(node.literal);
              return htmlConvertor(newNode, context);
            }
          }
          return context.origin();
        };
      } else {
        convertors2[nodeType] = customConvertor;
      }
    });
  }
  return convertors2;
}
var nestableTypes = ["list", "item", "blockQuote"];
var nestableTagNames = ["UL", "OL", "BLOCKQUOTE"];
function isBlankLine(doc3, index2) {
  var _a;
  var pmNode = doc3.child(index2);
  return !pmNode.childCount || pmNode.childCount === 1 && !((_a = pmNode.firstChild.text) === null || _a === void 0 ? void 0 : _a.trim());
}
function getEditorRangeHeightInfo(doc3, mdNode, children) {
  var start = getMdStartLine(mdNode) - 1;
  var end = getMdEndLine(mdNode) - 1;
  var rect2 = children[start].getBoundingClientRect();
  var height = children[end].offsetTop - children[start].offsetTop + children[end].clientHeight;
  return {
    height: height <= 0 ? children[start].clientHeight : height + getBlankLinesHeight(doc3, children, Math.min(end + 1, doc3.childCount - 1)),
    rect: rect2
  };
}
function getBlankLinesHeight(doc3, children, start) {
  var end = doc3.childCount - 1;
  var height = 0;
  while (start <= end && isBlankLine(doc3, start)) {
    height += children[start].clientHeight;
    start += 1;
  }
  return height;
}
function findAncestorHavingId(el2, root) {
  while (!el2.getAttribute("data-nodeid") && el2.parentElement !== root) {
    el2 = el2.parentElement;
  }
  return el2;
}
function getTotalOffsetTop(el2, root) {
  var offsetTop = 0;
  while (el2 && el2 !== root) {
    if (!includes(nestableTagNames, el2.tagName)) {
      offsetTop += el2.offsetTop;
    }
    if (el2.offsetParent === root.offsetParent) {
      break;
    }
    el2 = el2.parentElement;
  }
  return offsetTop;
}
function findAdjacentElementToScrollTop(scrollTop, root) {
  var el2 = root;
  var prev = null;
  while (el2) {
    var firstElementChild = el2.firstElementChild;
    if (!firstElementChild) {
      break;
    }
    var lastSibling = findLastSiblingElementToScrollTop(firstElementChild, scrollTop, getTotalOffsetTop(el2, root));
    prev = el2;
    el2 = lastSibling;
  }
  var adjacentEl = el2 || prev;
  return adjacentEl === root ? null : adjacentEl;
}
function findLastSiblingElementToScrollTop(el2, scrollTop, offsetTop) {
  if (el2 && scrollTop > offsetTop + el2.offsetTop) {
    return findLastSiblingElementToScrollTop(el2.nextElementSibling, scrollTop, offsetTop) || el2;
  }
  return null;
}
function getAdditionalPos(scrollTop, offsetTop, height, targetNodeHeight) {
  var ratio2 = Math.min((scrollTop - offsetTop) / height, 1);
  return ratio2 * targetNodeHeight;
}
function getParentNodeObj(previewContent, mdNode) {
  var el2 = previewContent.querySelector('[data-nodeid="' + mdNode.id + '"]');
  while (!el2 || isStyledInlineNode(mdNode)) {
    mdNode = mdNode.parent;
    el2 = previewContent.querySelector('[data-nodeid="' + mdNode.id + '"]');
  }
  return getNonNestableNodeObj({ mdNode, el: el2 });
}
function getNonNestableNodeObj(_a) {
  var mdNode = _a.mdNode, el2 = _a.el;
  while ((includes(nestableTypes, mdNode.type) || mdNode.type === "table") && mdNode.firstChild) {
    mdNode = mdNode.firstChild;
    el2 = el2.firstElementChild;
  }
  return { mdNode, el: el2 };
}
var offsetInfoMap = {};
function setHeight(id, height) {
  offsetInfoMap[id] = offsetInfoMap[id] || {};
  offsetInfoMap[id].height = height;
}
function setOffsetTop(id, offsetTop) {
  offsetInfoMap[id] = offsetInfoMap[id] || {};
  offsetInfoMap[id].offsetTop = offsetTop;
}
function getHeight(id) {
  return offsetInfoMap[id] && offsetInfoMap[id].height;
}
function getOffsetTop(id) {
  return offsetInfoMap[id] && offsetInfoMap[id].offsetTop;
}
function removeOffsetInfoByNode(node) {
  if (node) {
    delete offsetInfoMap[Number(node.getAttribute("data-nodeid"))];
    toArray_1(node.children).forEach(function(child) {
      removeOffsetInfoByNode(child);
    });
  }
}
function getAndSaveOffsetInfo(node, root, mdNodeId) {
  var cachedHeight = getHeight(mdNodeId);
  var cachedTop = getOffsetTop(mdNodeId);
  var nodeHeight = cachedHeight || node.clientHeight;
  var offsetTop = cachedTop || getTotalOffsetTop(node, root) || node.offsetTop;
  if (!cachedHeight) {
    setHeight(mdNodeId, nodeHeight);
  }
  if (!cachedTop) {
    setOffsetTop(mdNodeId, offsetTop);
  }
  return { nodeHeight, offsetTop };
}
var CLASS_HIGHLIGHT = cls("md-preview-highlight");
function findTableCell(tableRow2, chOffset) {
  var cell = tableRow2.firstChild;
  while (cell && cell.next) {
    if (getMdStartCh(cell.next) > chOffset + 1) {
      break;
    }
    cell = cell.next;
  }
  return cell;
}
var MarkdownPreview = (
  /** @class */
  (function() {
    function MarkdownPreview2(eventEmitter, options) {
      var el2 = document.createElement("div");
      this.el = el2;
      this.eventEmitter = eventEmitter;
      this.isViewer = !!options.isViewer;
      this.el.className = cls("md-preview");
      var linkAttributes = options.linkAttributes, customHTMLRenderer = options.customHTMLRenderer, sanitizer = options.sanitizer, _a = options.highlight, highlight = _a === void 0 ? false : _a;
      this.renderer = new Renderer({
        gfm: true,
        nodeId: true,
        convertors: getHTMLRenderConvertors(linkAttributes, customHTMLRenderer)
      });
      this.cursorNodeId = null;
      this.sanitizer = sanitizer;
      this.initEvent(highlight);
      this.initContentSection();
      if (this.isViewer) {
        this.previewContent.style.overflowWrap = "break-word";
      }
    }
    MarkdownPreview2.prototype.initContentSection = function() {
      this.previewContent = createElementWith('<div class="' + cls("contents") + '"></div>');
      if (!this.isViewer) {
        this.el.appendChild(this.previewContent);
      }
    };
    MarkdownPreview2.prototype.toggleActive = function(active) {
      toggleClass(this.el, "active", active);
    };
    MarkdownPreview2.prototype.initEvent = function(highlight) {
      var _this = this;
      this.eventEmitter.listen("updatePreview", this.update.bind(this));
      if (this.isViewer) {
        return;
      }
      if (highlight) {
        this.eventEmitter.listen("changeToolbarState", function(_a) {
          var mdNode = _a.mdNode, cursorPos = _a.cursorPos;
          _this.updateCursorNode(mdNode, cursorPos);
        });
        this.eventEmitter.listen("blur", function() {
          _this.removeHighlight();
        });
      }
      on_1(this.el, "scroll", function(event) {
        _this.eventEmitter.emit("scroll", "preview", findAdjacentElementToScrollTop(event.target.scrollTop, _this.previewContent));
      });
      this.eventEmitter.listen("changePreviewTabPreview", function() {
        return _this.toggleActive(true);
      });
      this.eventEmitter.listen("changePreviewTabWrite", function() {
        return _this.toggleActive(false);
      });
    };
    MarkdownPreview2.prototype.removeHighlight = function() {
      if (this.cursorNodeId) {
        var currentEl = this.getElementByNodeId(this.cursorNodeId);
        if (currentEl) {
          removeClass_1(currentEl, CLASS_HIGHLIGHT);
        }
      }
    };
    MarkdownPreview2.prototype.updateCursorNode = function(cursorNode, cursorPos) {
      if (cursorNode) {
        cursorNode = findClosestNode(cursorNode, function(mdNode) {
          return !isInlineNode$1(mdNode);
        });
        if (cursorNode.type === "tableRow") {
          cursorNode = findTableCell(cursorNode, cursorPos[1]);
        } else if (cursorNode.type === "tableBody") {
          cursorNode = null;
        }
      }
      var cursorNodeId = cursorNode ? cursorNode.id : null;
      if (this.cursorNodeId === cursorNodeId) {
        return;
      }
      var oldEL = this.getElementByNodeId(this.cursorNodeId);
      var newEL = this.getElementByNodeId(cursorNodeId);
      if (oldEL) {
        removeClass_1(oldEL, CLASS_HIGHLIGHT);
      }
      if (newEL) {
        addClass_1(newEL, CLASS_HIGHLIGHT);
      }
      this.cursorNodeId = cursorNodeId;
    };
    MarkdownPreview2.prototype.getElementByNodeId = function(nodeId) {
      return nodeId ? this.previewContent.querySelector('[data-nodeid="' + nodeId + '"]') : null;
    };
    MarkdownPreview2.prototype.update = function(changed) {
      var _this = this;
      changed.forEach(function(editResult) {
        return _this.replaceRangeNodes(editResult);
      });
      this.eventEmitter.emit("afterPreviewRender", this);
    };
    MarkdownPreview2.prototype.replaceRangeNodes = function(editResult) {
      var _this = this;
      var nodes = editResult.nodes, removedNodeRange = editResult.removedNodeRange;
      var contentEl = this.previewContent;
      var newHtml = this.eventEmitter.emitReduce("beforePreviewRender", this.sanitizer(nodes.map(function(node) {
        return _this.renderer.render(node);
      }).join("")));
      if (!removedNodeRange) {
        contentEl.insertAdjacentHTML("afterbegin", newHtml);
      } else {
        var _a = removedNodeRange.id, startNodeId = _a[0], endNodeId = _a[1];
        var startEl = this.getElementByNodeId(startNodeId);
        var endEl = this.getElementByNodeId(endNodeId);
        if (startEl) {
          startEl.insertAdjacentHTML("beforebegin", newHtml);
          var el2 = startEl;
          while (el2 && el2 !== endEl) {
            var nextEl = el2.nextElementSibling;
            removeNode$1(el2);
            removeOffsetInfoByNode(el2);
            el2 = nextEl;
          }
          if (el2 === null || el2 === void 0 ? void 0 : el2.parentNode) {
            removeNode$1(el2);
            removeOffsetInfoByNode(el2);
          }
        }
      }
    };
    MarkdownPreview2.prototype.getRenderer = function() {
      return this.renderer;
    };
    MarkdownPreview2.prototype.destroy = function() {
      off_1(this.el, "scroll");
      this.el = null;
    };
    MarkdownPreview2.prototype.getElement = function() {
      return this.el;
    };
    MarkdownPreview2.prototype.getHTML = function() {
      return removeProseMirrorHackNodes(this.previewContent.innerHTML);
    };
    MarkdownPreview2.prototype.setHTML = function(html2) {
      this.previewContent.innerHTML = html2;
    };
    MarkdownPreview2.prototype.setHeight = function(height) {
      css_1(this.el, { height: height + "px" });
    };
    MarkdownPreview2.prototype.setMinHeight = function(minHeight) {
      css_1(this.el, { minHeight: minHeight + "px" });
    };
    return MarkdownPreview2;
  })()
);
function findNodeBy(pos, condition) {
  var depth = pos.depth;
  while (depth) {
    var node = pos.node(depth);
    if (condition(node, depth)) {
      return {
        node,
        depth,
        offset: depth > 0 ? pos.before(depth) : 0
      };
    }
    depth -= 1;
  }
  return null;
}
function isInListNode(pos) {
  return !!findNodeBy(pos, function(_a) {
    var type = _a.type;
    return type.name === "listItem" || type.name === "bulletList" || type.name === "orderedList";
  });
}
function isInTableNode(pos) {
  return !!findNodeBy(pos, function(_a) {
    var type = _a.type;
    return type.name === "tableHeadCell" || type.name === "tableBodyCell";
  });
}
function findListItem(pos) {
  return findNodeBy(pos, function(_a) {
    var type = _a.type;
    return type.name === "listItem";
  });
}
function createDOMInfoParsedRawHTML(tag) {
  return {
    tag,
    getAttrs: function(dom) {
      var rawHTML = dom.getAttribute("data-raw-html");
      return __assign$1({}, rawHTML && { rawHTML });
    }
  };
}
function createCellAttrs(attrs) {
  return Object.keys(attrs).reduce(function(acc, attrName) {
    if (attrName !== "rawHTML" && attrs[attrName]) {
      attrName = attrName === "className" ? "class" : attrName;
      acc[attrName] = attrs[attrName];
    }
    return acc;
  }, {});
}
function createParsedCellDOM(tag) {
  return {
    tag,
    getAttrs: function(dom) {
      return ["rawHTML", "colspan", "rowspan", "extended"].reduce(function(acc, attrName) {
        var attrNameInDOM = attrName === "rawHTML" ? "data-raw-html" : attrName;
        var attrValue = dom.getAttribute(attrNameInDOM);
        if (attrValue) {
          acc[attrName] = includes(["rawHTML", "extended"], attrName) ? attrValue : Number(attrValue);
        }
        return acc;
      }, {});
    }
  };
}
function getDefaultCustomAttrs() {
  return {
    htmlAttrs: { default: null },
    classNames: { default: null }
  };
}
function getCustomAttrs(attrs) {
  var htmlAttrs = attrs.htmlAttrs, classNames = attrs.classNames;
  return __assign$1(__assign$1({}, htmlAttrs), { class: classNames ? classNames.join(" ") : null });
}
function findWrappingOutside2(range2, type) {
  var parent = range2.parent, startIndex = range2.startIndex, endIndex = range2.endIndex;
  var around = parent.contentMatchAt(startIndex).findWrapping(type);
  if (around) {
    var outer = around.length ? around[0] : type;
    return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
  }
  return null;
}
function findWrappingInside2(range2, type) {
  var parent = range2.parent, startIndex = range2.startIndex, endIndex = range2.endIndex;
  var inner = parent.child(startIndex);
  var inside = type.contentMatch.findWrapping(inner.type);
  if (inside) {
    var lastType = inside.length ? inside[inside.length - 1] : type;
    var innerMatch = lastType.contentMatch;
    for (var i = startIndex; innerMatch && i < endIndex; i += 1) {
      innerMatch = innerMatch.matchType(parent.child(i).type);
    }
    if (innerMatch && innerMatch.validEnd) {
      return inside;
    }
  }
  return null;
}
function findWrappers(range2, innerRange, nodeType, attrs) {
  var around = findWrappingOutside2(range2, nodeType);
  var inner = findWrappingInside2(innerRange, nodeType);
  if (around && inner) {
    var aroundNodes = around.map(function(type) {
      return { type };
    });
    var innerNodes = inner.map(function(type) {
      return { type, attrs };
    });
    return aroundNodes.concat({ type: nodeType }).concat(innerNodes);
  }
  return null;
}
function wrapInList(tr, _a, wrappers, joinBefore, list2) {
  var start = _a.start, end = _a.end, startIndex = _a.startIndex, endIndex = _a.endIndex, parent = _a.parent;
  var content = Fragment.empty;
  for (var i = wrappers.length - 1; i >= 0; i -= 1) {
    content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  }
  tr.step(new ReplaceAroundStep(start - (joinBefore ? 2 : 0), end, start, end, new Slice(content, 0, 0), wrappers.length, true));
  var foundListIndex = 0;
  for (var i = 0; i < wrappers.length; i += 1) {
    if (wrappers[i].type === list2) {
      foundListIndex = i + 1;
      break;
    }
  }
  var splitDepth = wrappers.length - foundListIndex;
  var splitPos = start + wrappers.length - (joinBefore ? 2 : 0);
  for (var i = startIndex, len = endIndex; i < len; i += 1) {
    var first = i === startIndex;
    if (!first && canSplit(tr.doc, splitPos, splitDepth)) {
      tr.split(splitPos, splitDepth);
      splitPos += splitDepth * 2;
    }
    splitPos += parent.child(i).nodeSize;
  }
  return tr;
}
function changeToList(tr, range2, list2, attrs) {
  var $from = range2.$from, $to = range2.$to, depth = range2.depth;
  var outerRange = range2;
  var joinBefore = false;
  if (depth >= 2 && $from.node(depth - 1).type.compatibleContent(list2) && range2.startIndex === 0 && $from.index(depth - 1)) {
    var start = tr.doc.resolve(range2.start - 2);
    outerRange = new NodeRange(start, start, depth);
    if (range2.endIndex < range2.parent.childCount) {
      range2 = new NodeRange($from, tr.doc.resolve($to.end(depth)), depth);
    }
    joinBefore = true;
  }
  var wrappers = findWrappers(outerRange, range2, list2, attrs);
  if (wrappers) {
    return wrapInList(tr, range2, wrappers, joinBefore, list2);
  }
  return tr;
}
function getBeforeLineListItem(doc3, offset) {
  var endListItemPos = doc3.resolve(offset);
  while (endListItemPos.node().type.name !== "paragraph") {
    offset -= 2;
    endListItemPos = doc3.resolve(offset);
  }
  return findListItem(endListItemPos);
}
function toggleTaskListItems(tr, _a) {
  var $from = _a.$from, $to = _a.$to;
  var startListItem = findListItem($from);
  var endListItem = findListItem($to);
  if (startListItem && endListItem) {
    while (endListItem) {
      var offset = endListItem.offset, node = endListItem.node;
      var attrs = { task: !node.attrs.task, checked: false };
      tr.setNodeMarkup(offset, null, attrs);
      if (offset === startListItem.offset) {
        break;
      }
      endListItem = getBeforeLineListItem(tr.doc, offset);
    }
  }
  return tr;
}
function changeListType(tr, _a, list2) {
  var $from = _a.$from, $to = _a.$to;
  var startListItem = findListItem($from);
  var endListItem = findListItem($to);
  if (startListItem && endListItem) {
    while (endListItem) {
      var offset = endListItem.offset, node = endListItem.node, depth = endListItem.depth;
      if (node.attrs.task) {
        tr.setNodeMarkup(offset, null, { task: false, checked: false });
      }
      var resolvedPos = tr.doc.resolve(offset);
      if (resolvedPos.parent.type !== list2) {
        var parentOffset = resolvedPos.before(depth - 1);
        tr.setNodeMarkup(parentOffset, list2);
      }
      if (offset === startListItem.offset) {
        break;
      }
      endListItem = getBeforeLineListItem(tr.doc, offset);
    }
  }
  return tr;
}
function changeList(list2) {
  return function(_a, dispatch) {
    var selection = _a.selection, tr = _a.tr;
    var $from = selection.$from, $to = selection.$to;
    var range2 = $from.blockRange($to);
    if (range2) {
      var newTr = isInListNode($from) ? changeListType(tr, range2, list2) : changeToList(tr, range2, list2);
      dispatch(newTr);
      return true;
    }
    return false;
  };
}
function toggleTask() {
  return function(_a, dispatch) {
    var selection = _a.selection, tr = _a.tr, schema = _a.schema;
    var $from = selection.$from, $to = selection.$to;
    var range2 = $from.blockRange($to);
    if (range2) {
      var newTr = isInListNode($from) ? toggleTaskListItems(tr, range2) : changeToList(tr, range2, schema.nodes.bulletList, { task: true });
      dispatch(newTr);
      return true;
    }
    return false;
  };
}
function sinkListItem(listItem2) {
  return function(_a, dispatch) {
    var tr = _a.tr, selection = _a.selection;
    var $from = selection.$from, $to = selection.$to;
    var range2 = $from.blockRange($to, function(_a2) {
      var childCount = _a2.childCount, firstChild = _a2.firstChild;
      return !!childCount && firstChild.type === listItem2;
    });
    if (range2 && range2.startIndex > 0) {
      var parent_1 = range2.parent;
      var nodeBefore = parent_1.child(range2.startIndex - 1);
      if (nodeBefore.type !== listItem2) {
        return false;
      }
      var nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type === parent_1.type;
      var inner = nestedBefore ? Fragment.from(listItem2.create()) : null;
      var slice2 = new Slice(Fragment.from(listItem2.create(null, Fragment.from(parent_1.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
      var before = range2.start;
      var after = range2.end;
      tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true));
      dispatch(tr);
      return true;
    }
    return false;
  };
}
function liftToOuterList(tr, range2, listItem2) {
  var $from = range2.$from, $to = range2.$to, end = range2.end, depth = range2.depth, parent = range2.parent;
  var endOfList = $to.end(depth);
  if (end < endOfList) {
    tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(listItem2.create(null, parent.copy())), 1, 0), 1, true));
    range2 = new NodeRange(tr.doc.resolve($from.pos), tr.doc.resolve(endOfList), depth);
  }
  tr.lift(range2, liftTarget(range2));
  return tr;
}
function liftOutOfList(tr, range2) {
  var list2 = range2.parent;
  var pos = range2.end;
  for (var i = range2.endIndex - 1, len = range2.startIndex; i > len; i -= 1) {
    pos -= list2.child(i).nodeSize;
    tr.delete(pos - 1, pos + 1);
  }
  var startPos = tr.doc.resolve(range2.start);
  var listItem2 = startPos.nodeAfter;
  var atStart = range2.startIndex === 0;
  var atEnd = range2.endIndex === list2.childCount;
  var parent = startPos.node(-1);
  var indexBefore = startPos.index(-1);
  var canReplaceParent = parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, listItem2 === null || listItem2 === void 0 ? void 0 : listItem2.content.append(atEnd ? Fragment.empty : Fragment.from(list2)));
  if (listItem2 && canReplaceParent) {
    var start = startPos.pos;
    var end = start + listItem2.nodeSize;
    tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list2.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  }
  return tr;
}
function liftListItem(listItem2) {
  return function(_a, dispatch) {
    var tr = _a.tr, selection = _a.selection;
    var $from = selection.$from, $to = selection.$to;
    var range2 = $from.blockRange($to, function(_a2) {
      var childCount = _a2.childCount, firstChild = _a2.firstChild;
      return !!childCount && firstChild.type === listItem2;
    });
    if (range2) {
      var topListItem = $from.node(range2.depth - 1).type === listItem2;
      var newTr = topListItem ? liftToOuterList(tr, range2, listItem2) : liftOutOfList(tr, range2);
      dispatch(newTr);
      return true;
    }
    return false;
  };
}
function splitListItem(listItem2) {
  return function(_a, dispatch) {
    var tr = _a.tr, selection = _a.selection;
    var $from = selection.$from, $to = selection.$to;
    if ($from.depth < 2 || !$from.sameParent($to)) {
      return false;
    }
    var grandParent = $from.node(-1);
    if (grandParent.type !== listItem2) {
      return false;
    }
    if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
      if ($from.depth === 2 || $from.node(-3).type !== listItem2 || $from.index(-2) !== $from.node(-2).childCount - 1) {
        return false;
      }
      var keepItem = $from.index(-1) > 0;
      var wrapper = Fragment.empty;
      for (var depth = $from.depth - (keepItem ? 1 : 2); depth >= $from.depth - 3; depth -= 1) {
        wrapper = Fragment.from($from.node(depth).copy(wrapper));
      }
      wrapper = wrapper.append(Fragment.from(listItem2.createAndFill()));
      tr.replace(keepItem ? $from.before() : $from.before(-1), $from.after(-3), new Slice(wrapper, keepItem ? 3 : 2, 2));
      tr.setSelection(Selection.near(tr.doc.resolve($from.pos + (keepItem ? 3 : 2))));
      dispatch(tr);
      return true;
    }
    var nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
    var types = nextType && [null, { type: nextType }];
    tr.delete($from.pos, $to.pos);
    if (canSplit(tr.doc, $from.pos, 2, types)) {
      tr.split($from.pos, 2, types);
      dispatch(tr);
      return true;
    }
    return false;
  };
}
function indent() {
  return function() {
    return function(state, dispatch) {
      var selection = state.selection, schema = state.schema;
      var $from = selection.$from, $to = selection.$to;
      var range2 = $from.blockRange($to);
      if (range2 && isInListNode($from)) {
        return sinkListItem(schema.nodes.listItem)(state, dispatch);
      }
      return false;
    };
  };
}
function outdent() {
  return function() {
    return function(state, dispatch) {
      var selection = state.selection, schema = state.schema;
      var $from = selection.$from, $to = selection.$to;
      var range2 = $from.blockRange($to);
      if (range2 && isInListNode($from)) {
        return liftListItem(schema.nodes.listItem)(state, dispatch);
      }
      return false;
    };
  };
}
function getWwCommands() {
  return {
    indent: indent(),
    outdent: outdent()
  };
}
var cache = /* @__PURE__ */ new Map();
var TableOffsetMap = (
  /** @class */
  (function() {
    function TableOffsetMap2(table2, tableRows, tableStartPos, rowInfo) {
      this.table = table2;
      this.tableRows = tableRows;
      this.tableStartPos = tableStartPos;
      this.rowInfo = rowInfo;
    }
    TableOffsetMap2.create = function(cellPos) {
      var table2 = findNodeBy(cellPos, function(_a) {
        var type = _a.type;
        return type.name === "table";
      });
      if (table2) {
        var node = table2.node, depth = table2.depth, offset = table2.offset;
        var cached = cache.get(node);
        if ((cached === null || cached === void 0 ? void 0 : cached.tableStartPos) === offset + 1) {
          return cached;
        }
        var rows_1 = [];
        var tablePos = cellPos.start(depth);
        var thead = node.child(0);
        var tbody = node.child(1);
        var theadCellInfo = createOffsetMap(thead, tablePos);
        var tbodyCellInfo = createOffsetMap(tbody, tablePos + thead.nodeSize);
        thead.forEach(function(row) {
          return rows_1.push(row);
        });
        tbody.forEach(function(row) {
          return rows_1.push(row);
        });
        var map3 = new TableOffsetMap2(node, rows_1, tablePos, theadCellInfo.concat(tbodyCellInfo));
        cache.set(node, map3);
        return map3;
      }
      return null;
    };
    Object.defineProperty(TableOffsetMap2.prototype, "totalRowCount", {
      get: function() {
        return this.rowInfo.length;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableOffsetMap2.prototype, "totalColumnCount", {
      get: function() {
        return this.rowInfo[0].length;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableOffsetMap2.prototype, "tableStartOffset", {
      get: function() {
        return this.tableStartPos;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableOffsetMap2.prototype, "tableEndOffset", {
      get: function() {
        return this.tableStartPos + this.table.nodeSize - 1;
      },
      enumerable: false,
      configurable: true
    });
    TableOffsetMap2.prototype.getCellInfo = function(rowIdx, colIdx) {
      return this.rowInfo[rowIdx][colIdx];
    };
    TableOffsetMap2.prototype.posAt = function(rowIdx, colIdx) {
      for (var i = 0, rowStart = this.tableStartPos; ; i += 1) {
        var rowEnd = rowStart + this.tableRows[i].nodeSize;
        if (i === rowIdx) {
          var index2 = colIdx;
          while (index2 < this.totalColumnCount && this.rowInfo[i][index2].offset < rowStart) {
            index2 += 1;
          }
          return index2 === this.totalColumnCount ? rowEnd : this.rowInfo[i][index2].offset;
        }
        rowStart = rowEnd;
      }
    };
    TableOffsetMap2.prototype.getNodeAndPos = function(rowIdx, colIdx) {
      var cellInfo = this.rowInfo[rowIdx][colIdx];
      return {
        node: this.table.nodeAt(cellInfo.offset - this.tableStartOffset),
        pos: cellInfo.offset
      };
    };
    TableOffsetMap2.prototype.extendedRowspan = function(rowIdx, colIdx) {
      return false;
    };
    TableOffsetMap2.prototype.extendedColspan = function(rowIdx, colIdx) {
      return false;
    };
    TableOffsetMap2.prototype.getRowspanCount = function(rowIdx, colIdx) {
      return 0;
    };
    TableOffsetMap2.prototype.getColspanCount = function(rowIdx, colIdx) {
      return 0;
    };
    TableOffsetMap2.prototype.decreaseColspanCount = function(rowIdx, colIdx) {
      return 0;
    };
    TableOffsetMap2.prototype.decreaseRowspanCount = function(rowIdx, colIdx) {
      return 0;
    };
    TableOffsetMap2.prototype.getColspanStartInfo = function(rowIdx, colIdx) {
      return null;
    };
    TableOffsetMap2.prototype.getRowspanStartInfo = function(rowIdx, colIdx) {
      return null;
    };
    TableOffsetMap2.prototype.getCellStartOffset = function(rowIdx, colIdx) {
      var offset = this.rowInfo[rowIdx][colIdx].offset;
      return this.extendedRowspan(rowIdx, colIdx) ? this.posAt(rowIdx, colIdx) : offset;
    };
    TableOffsetMap2.prototype.getCellEndOffset = function(rowIdx, colIdx) {
      var _a = this.rowInfo[rowIdx][colIdx], offset = _a.offset, nodeSize2 = _a.nodeSize;
      return this.extendedRowspan(rowIdx, colIdx) ? this.posAt(rowIdx, colIdx) : offset + nodeSize2;
    };
    TableOffsetMap2.prototype.getCellIndex = function(cellPos) {
      for (var rowIdx = 0; rowIdx < this.totalRowCount; rowIdx += 1) {
        var rowInfo = this.rowInfo[rowIdx];
        for (var colIdx = 0; colIdx < this.totalColumnCount; colIdx += 1) {
          if (rowInfo[colIdx].offset + 1 > cellPos.pos) {
            return [rowIdx, colIdx];
          }
        }
      }
      return [0, 0];
    };
    TableOffsetMap2.prototype.getRectOffsets = function(startCellPos, endCellPos) {
      var _a, _b, _c;
      if (endCellPos === void 0) {
        endCellPos = startCellPos;
      }
      if (startCellPos.pos > endCellPos.pos) {
        _a = [endCellPos, startCellPos], startCellPos = _a[0], endCellPos = _a[1];
      }
      var _d = this.getCellIndex(startCellPos), startRowIdx = _d[0], startColIdx = _d[1];
      var _e = this.getCellIndex(endCellPos), endRowIdx = _e[0], endColIdx = _e[1];
      _b = getSortedNumPair(startRowIdx, endRowIdx), startRowIdx = _b[0], endRowIdx = _b[1];
      _c = getSortedNumPair(startColIdx, endColIdx), startColIdx = _c[0], endColIdx = _c[1];
      return this.getSpannedOffsets({ startRowIdx, startColIdx, endRowIdx, endColIdx });
    };
    TableOffsetMap2.prototype.getSpannedOffsets = function(selectionInfo) {
      return selectionInfo;
    };
    return TableOffsetMap2;
  })()
);
var createOffsetMap = function(headOrBody, startOffset) {
  var cellInfoMatrix = [];
  headOrBody.forEach(function(row, rowOffset) {
    var rowInfo = { rowspanMap: {}, colspanMap: {}, length: 0 };
    row.forEach(function(_a, cellOffset) {
      var nodeSize2 = _a.nodeSize;
      var colIdx = 0;
      while (rowInfo[colIdx]) {
        colIdx += 1;
      }
      rowInfo[colIdx] = {
        // 2 is the sum of the front and back positions of the tag
        offset: startOffset + rowOffset + cellOffset + 2,
        nodeSize: nodeSize2
      };
      rowInfo.length += 1;
    });
    cellInfoMatrix.push(rowInfo);
  });
  return cellInfoMatrix;
};
function mixinTableOffsetMapPrototype(offsetMapMixin, createOffsetMapMixin) {
  assign(TableOffsetMap.prototype, offsetMapMixin);
  createOffsetMap = createOffsetMapMixin;
  return TableOffsetMap;
}
function getSelectionRanges(doc3, map3, _a) {
  var startRowIdx = _a.startRowIdx, startColIdx = _a.startColIdx, endRowIdx = _a.endRowIdx, endColIdx = _a.endColIdx;
  var ranges = [];
  for (var rowIdx = startRowIdx; rowIdx <= endRowIdx; rowIdx += 1) {
    for (var colIdx = startColIdx; colIdx <= endColIdx; colIdx += 1) {
      var _b = map3.getCellInfo(rowIdx, colIdx), offset = _b.offset, nodeSize2 = _b.nodeSize;
      ranges.push(new SelectionRange(doc3.resolve(offset + 1), doc3.resolve(offset + nodeSize2 - 1)));
    }
  }
  return ranges;
}
function createTableFragment(tableHead2, tableBody2) {
  var fragment = [];
  if (tableHead2.childCount) {
    fragment.push(tableHead2);
  }
  if (tableBody2.childCount) {
    fragment.push(tableBody2);
  }
  return Fragment.from(fragment);
}
var CellSelection = (
  /** @class */
  (function(_super) {
    __extends$1(CellSelection2, _super);
    function CellSelection2(startCellPos, endCellPos) {
      if (endCellPos === void 0) {
        endCellPos = startCellPos;
      }
      var _this = this;
      var doc3 = startCellPos.node(0);
      var map3 = TableOffsetMap.create(startCellPos);
      var selectionInfo = map3.getRectOffsets(startCellPos, endCellPos);
      var ranges = getSelectionRanges(doc3, map3, selectionInfo);
      _this = _super.call(this, ranges[0].$from, ranges[0].$to, ranges) || this;
      _this.startCell = startCellPos;
      _this.endCell = endCellPos;
      _this.offsetMap = map3;
      _this.isCellSelection = true;
      _this.visible = false;
      return _this;
    }
    CellSelection2.prototype.map = function(doc3, mapping) {
      var startPos = this.startCell.pos;
      var endPos = this.endCell.pos;
      var startCell = doc3.resolve(mapping.map(startPos));
      var endCell = doc3.resolve(mapping.map(endPos));
      var map3 = TableOffsetMap.create(startCell);
      if (this.offsetMap.totalColumnCount > map3.totalColumnCount || this.offsetMap.totalRowCount > map3.totalRowCount) {
        var depthMap = { tableBody: 1, tableRow: 2, tableCell: 3, paragraph: 4 };
        var depthFromTable = depthMap[endCell.parent.type.name];
        var tableEndPos = endCell.end(endCell.depth - depthFromTable);
        var from2 = Math.min(tableEndPos - 4, endCell.pos);
        return TextSelection.create(doc3, from2);
      }
      return new CellSelection2(startCell, endCell);
    };
    CellSelection2.prototype.eq = function(cell) {
      return cell instanceof CellSelection2 && cell.startCell.pos === this.startCell.pos && cell.endCell.pos === this.endCell.pos;
    };
    CellSelection2.prototype.content = function() {
      var table2 = this.startCell.node(-2);
      var tableOffset = this.startCell.start(-2);
      var row = table2.child(1).firstChild;
      var tableHead2 = table2.child(0).type.create();
      var tableBody2 = table2.child(1).type.create();
      var map3 = TableOffsetMap.create(this.startCell);
      var selectionInfo = map3.getRectOffsets(this.startCell, this.endCell);
      var startRowIdx = selectionInfo.startRowIdx, startColIdx = selectionInfo.startColIdx, endRowIdx = selectionInfo.endRowIdx, endColIdx = selectionInfo.endColIdx;
      var isTableHeadCell = false;
      for (var rowIdx = startRowIdx; rowIdx <= endRowIdx; rowIdx += 1) {
        var cells = [];
        for (var colIdx = startColIdx; colIdx <= endColIdx; colIdx += 1) {
          var offset = map3.getCellInfo(rowIdx, colIdx).offset;
          var cell = table2.nodeAt(offset - tableOffset);
          if (cell) {
            isTableHeadCell = cell.type.name === "tableHeadCell";
            if (map3.extendedRowspan(rowIdx, colIdx) || map3.extendedColspan(rowIdx, colIdx)) {
              cells.push(cell.type.create({ extended: true }));
            } else {
              cells.push(cell.copy(cell.content));
            }
          }
        }
        var copiedRow = row.copy(Fragment.from(cells));
        var targetNode = isTableHeadCell ? tableHead2 : tableBody2;
        targetNode.content = targetNode.content.append(Fragment.from(copiedRow));
      }
      return new Slice(createTableFragment(tableHead2, tableBody2), 1, 1);
    };
    CellSelection2.prototype.toJSON = function() {
      return JSON.stringify(this);
    };
    return CellSelection2;
  })(Selection)
);
function createTableHeadRow(columnCount, schema, data) {
  var _a = schema.nodes, tableRow2 = _a.tableRow, tableHeadCell = _a.tableHeadCell, paragraph2 = _a.paragraph;
  var cells = [];
  for (var index2 = 0; index2 < columnCount; index2 += 1) {
    var text2 = data && data[index2];
    var para2 = paragraph2.create(null, text2 ? schema.text(text2) : []);
    cells.push(tableHeadCell.create(null, para2));
  }
  return [tableRow2.create(null, cells)];
}
function createTableBodyRows(rowCount, columnCount, schema, data) {
  var _a = schema.nodes, tableRow2 = _a.tableRow, tableBodyCell = _a.tableBodyCell, paragraph2 = _a.paragraph;
  var tableRows = [];
  for (var rowIdx = 0; rowIdx < rowCount; rowIdx += 1) {
    var cells = [];
    for (var colIdx = 0; colIdx < columnCount; colIdx += 1) {
      var text2 = data && data[rowIdx * columnCount + colIdx];
      var para2 = paragraph2.create(null, text2 ? schema.text(text2) : []);
      cells.push(tableBodyCell.create(null, para2));
    }
    tableRows.push(tableRow2.create(null, cells));
  }
  return tableRows;
}
function createDummyCells(columnCount, rowIdx, schema, attrs) {
  if (attrs === void 0) {
    attrs = null;
  }
  var _a = schema.nodes, tableHeadCell = _a.tableHeadCell, tableBodyCell = _a.tableBodyCell, paragraph2 = _a.paragraph;
  var cell = rowIdx === 0 ? tableHeadCell : tableBodyCell;
  var cells = [];
  for (var index2 = 0; index2 < columnCount; index2 += 1) {
    cells.push(cell.create(attrs, paragraph2.create()));
  }
  return cells;
}
function findCellElement(node, root) {
  while (node && node !== root) {
    if (node.nodeName === "TD" || node.nodeName === "TH") {
      return node;
    }
    node = node.parentNode;
  }
  return null;
}
function findCell(pos) {
  return findNodeBy(pos, function(_a) {
    var type = _a.type;
    return type.name === "tableHeadCell" || type.name === "tableBodyCell";
  });
}
function getResolvedSelection(selection) {
  if (selection instanceof TextSelection) {
    var $anchor = selection.$anchor;
    var foundCell = findCell($anchor);
    if (foundCell) {
      var anchor = $anchor.node(0).resolve($anchor.before(foundCell.depth));
      return { anchor, head: anchor };
    }
  }
  var _a = selection, startCell = _a.startCell, endCell = _a.endCell;
  return { anchor: startCell, head: endCell };
}
function getTableContentFromSlice(slice2) {
  var _a;
  if (slice2.size) {
    var content = slice2.content, openStart = slice2.openStart, openEnd = slice2.openEnd;
    if (content.childCount !== 1) {
      return null;
    }
    while (content.childCount === 1 && (openStart > 0 && openEnd > 0 || ((_a = content.firstChild) === null || _a === void 0 ? void 0 : _a.type.name) === "table")) {
      openStart -= 1;
      openEnd -= 1;
      content = content.firstChild.content;
    }
    if (content.firstChild.type.name === "tableHead" || content.firstChild.type.name === "tableBody") {
      return content;
    }
  }
  return null;
}
function getRowAndColumnCount(_a) {
  var startRowIdx = _a.startRowIdx, startColIdx = _a.startColIdx, endRowIdx = _a.endRowIdx, endColIdx = _a.endColIdx;
  var rowCount = endRowIdx - startRowIdx + 1;
  var columnCount = endColIdx - startColIdx + 1;
  return { rowCount, columnCount };
}
function setAttrs(cell, attrs) {
  return __assign$1(__assign$1({}, cell.attrs), attrs);
}
var pluginKey = new PluginKey("cellSelection");
var MOUSE_RIGHT_BUTTON = 2;
var TableSelection = (
  /** @class */
  (function() {
    function TableSelection2(view) {
      this.view = view;
      this.handlers = {
        mousedown: this.handleMousedown.bind(this),
        mousemove: this.handleMousemove.bind(this),
        mouseup: this.handleMouseup.bind(this)
      };
      this.startCellPos = null;
      this.init();
    }
    TableSelection2.prototype.init = function() {
      this.view.dom.addEventListener("mousedown", this.handlers.mousedown);
    };
    TableSelection2.prototype.handleMousedown = function(ev) {
      var foundCell = findCellElement(ev.target, this.view.dom);
      if (ev.button === MOUSE_RIGHT_BUTTON) {
        ev.preventDefault();
        return;
      }
      if (foundCell) {
        var startCellPos = this.getCellPos(ev);
        if (startCellPos) {
          this.startCellPos = startCellPos;
        }
        this.bindEvent();
      }
    };
    TableSelection2.prototype.handleMousemove = function(ev) {
      var prevEndCellOffset = pluginKey.getState(this.view.state);
      var endCellPos = this.getCellPos(ev);
      var startCellPos = this.startCellPos;
      var prevEndCellPos;
      if (prevEndCellOffset) {
        prevEndCellPos = this.view.state.doc.resolve(prevEndCellOffset);
      } else if (startCellPos !== endCellPos) {
        prevEndCellPos = startCellPos;
      }
      if (prevEndCellPos && startCellPos && endCellPos) {
        this.setCellSelection(startCellPos, endCellPos);
      }
    };
    TableSelection2.prototype.handleMouseup = function() {
      this.startCellPos = null;
      this.unbindEvent();
      if (pluginKey.getState(this.view.state) !== null) {
        this.view.dispatch(this.view.state.tr.setMeta(pluginKey, -1));
      }
    };
    TableSelection2.prototype.bindEvent = function() {
      var dom = this.view.dom;
      dom.addEventListener("mousemove", this.handlers.mousemove);
      dom.addEventListener("mouseup", this.handlers.mouseup);
    };
    TableSelection2.prototype.unbindEvent = function() {
      var dom = this.view.dom;
      dom.removeEventListener("mousemove", this.handlers.mousemove);
      dom.removeEventListener("mouseup", this.handlers.mouseup);
    };
    TableSelection2.prototype.getCellPos = function(_a) {
      var clientX = _a.clientX, clientY = _a.clientY;
      var mousePos = this.view.posAtCoords({ left: clientX, top: clientY });
      if (mousePos) {
        var doc3 = this.view.state.doc;
        var currentPos = doc3.resolve(mousePos.pos);
        var foundCell = findCell(currentPos);
        if (foundCell) {
          var cellOffset = currentPos.before(foundCell.depth);
          return doc3.resolve(cellOffset);
        }
      }
      return null;
    };
    TableSelection2.prototype.setCellSelection = function(startCellPos, endCellPos) {
      var _a = this.view.state, selection = _a.selection, tr = _a.tr;
      var starting = pluginKey.getState(this.view.state) === null;
      var cellSelection = new CellSelection(startCellPos, endCellPos);
      if (starting || !selection.eq(cellSelection)) {
        var newTr = tr.setSelection(cellSelection);
        if (starting) {
          newTr.setMeta(pluginKey, endCellPos.pos);
        }
        this.view.dispatch(newTr);
      }
    };
    TableSelection2.prototype.destroy = function() {
      this.view.dom.removeEventListener("mousedown", this.handlers.mousedown);
    };
    return TableSelection2;
  })()
);
var SELECTED_CELL_CLASS_NAME = cls("cell-selected");
function drawCellSelection(_a) {
  var selection = _a.selection, doc3 = _a.doc;
  if (selection instanceof CellSelection) {
    var cells_1 = [];
    var ranges = selection.ranges;
    ranges.forEach(function(_a2) {
      var $from = _a2.$from, $to = _a2.$to;
      cells_1.push(Decoration.node($from.pos - 1, $to.pos + 1, { class: SELECTED_CELL_CLASS_NAME }));
    });
    return DecorationSet.create(doc3, cells_1);
  }
  return null;
}
function tableSelection() {
  return new Plugin({
    key: pluginKey,
    state: {
      init: function() {
        return null;
      },
      apply: function(tr, value) {
        var cellOffset = tr.getMeta(pluginKey);
        if (cellOffset) {
          return cellOffset === -1 ? null : cellOffset;
        }
        if (isNull_1(value) || !tr.docChanged) {
          return value;
        }
        var _a = tr.mapping.mapResult(value), deleted = _a.deleted, pos = _a.pos;
        return deleted ? null : pos;
      }
    },
    props: {
      decorations: drawCellSelection,
      createSelectionBetween: function(_a) {
        var state = _a.state;
        if (!isNull_1(pluginKey.getState(state))) {
          return state.selection;
        }
        return null;
      }
    },
    view: function(editorView) {
      return new TableSelection(editorView);
    }
  });
}
var Map$1 = (
  /** @class */
  (function() {
    function Map2() {
      this.keys = [];
      this.values = [];
    }
    Map2.prototype.getKeyIndex = function(key) {
      return inArray_1(key, this.keys);
    };
    Map2.prototype.get = function(key) {
      return this.values[this.getKeyIndex(key)];
    };
    Map2.prototype.set = function(key, value) {
      var keyIndex = this.getKeyIndex(key);
      if (keyIndex > -1) {
        this.values[keyIndex] = value;
      } else {
        this.keys.push(key);
        this.values.push(value);
      }
      return this;
    };
    Map2.prototype.has = function(key) {
      return this.getKeyIndex(key) > -1;
    };
    Map2.prototype.delete = function(key) {
      var keyIndex = this.getKeyIndex(key);
      if (keyIndex > -1) {
        this.keys.splice(keyIndex, 1);
        this.values.splice(keyIndex, 1);
        return true;
      }
      return false;
    };
    Map2.prototype.forEach = function(callback, thisArg) {
      var _this = this;
      if (thisArg === void 0) {
        thisArg = this;
      }
      this.values.forEach(function(value, index2) {
        if (value && _this.keys[index2]) {
          callback.call(thisArg, value, _this.keys[index2], _this);
        }
      });
    };
    Map2.prototype.clear = function() {
      this.keys = [];
      this.values = [];
    };
    return Map2;
  })()
);
var DEFAULT_CODE = "en-US";
var I18n = (
  /** @class */
  (function() {
    function I18n2() {
      this.code = DEFAULT_CODE;
      this.langs = new Map$1();
    }
    I18n2.prototype.setCode = function(code2) {
      this.code = code2 || DEFAULT_CODE;
    };
    I18n2.prototype.setLanguage = function(codes, data) {
      var _this = this;
      codes = [].concat(codes);
      codes.forEach(function(code2) {
        if (!_this.langs.has(code2)) {
          _this.langs.set(code2, data);
        } else {
          var langData = _this.langs.get(code2);
          _this.langs.set(code2, extend_1(langData, data));
        }
      });
    };
    I18n2.prototype.get = function(key, code2) {
      if (!code2) {
        code2 = this.code;
      }
      var langSet = this.langs.get(code2);
      if (!langSet) {
        langSet = this.langs.get(DEFAULT_CODE);
      }
      var text2 = langSet[key];
      if (!text2) {
        throw new Error('There is no text key "' + key + '" in ' + code2);
      }
      return text2;
    };
    return I18n2;
  })()
);
var i18n = new I18n();
var contextMenuGroups = [
  [
    {
      action: "Add row to up",
      command: "addRowToUp",
      disableInThead: true,
      className: "add-row-up"
    },
    {
      action: "Add row to down",
      command: "addRowToDown",
      disableInThead: true,
      className: "add-row-down"
    },
    { action: "Remove row", command: "removeRow", disableInThead: true, className: "remove-row" }
  ],
  [
    { action: "Add column to left", command: "addColumnToLeft", className: "add-column-left" },
    { action: "Add column to right", command: "addColumnToRight", className: "add-column-right" },
    { action: "Remove column", command: "removeColumn", className: "remove-column" }
  ],
  [
    {
      action: "Align column to left",
      command: "alignColumn",
      payload: { align: "left" },
      className: "align-column-left"
    },
    {
      action: "Align column to center",
      command: "alignColumn",
      payload: { align: "center" },
      className: "align-column-center"
    },
    {
      action: "Align column to right",
      command: "alignColumn",
      payload: { align: "right" },
      className: "align-column-right"
    }
  ],
  [{ action: "Remove table", command: "removeTable", className: "remove-table" }]
];
function getContextMenuGroups(eventEmitter, inTableHead) {
  return contextMenuGroups.map(function(contextMenuGroup) {
    return contextMenuGroup.map(function(_a) {
      var action = _a.action, command = _a.command, payload = _a.payload, disableInThead = _a.disableInThead, className = _a.className;
      return {
        label: i18n.get(action),
        onClick: function() {
          eventEmitter.emit("command", command, payload);
        },
        disabled: inTableHead && !!disableInThead,
        className
      };
    });
  }).concat();
}
function tableContextMenu(eventEmitter) {
  return new Plugin({
    props: {
      handleDOMEvents: {
        contextmenu: function(view, ev) {
          var tableCell2 = findCellElement(ev.target, view.dom);
          if (tableCell2) {
            ev.preventDefault();
            var _a = ev, clientX = _a.clientX, clientY = _a.clientY;
            var _b = view.dom.parentNode.getBoundingClientRect(), left = _b.left, top_1 = _b.top;
            var inTableHead = tableCell2.nodeName === "TH";
            eventEmitter.emit("contextmenu", {
              pos: { left: clientX - left + 10 + "px", top: clientY - top_1 + 30 + "px" },
              menuGroups: getContextMenuGroups(eventEmitter, inTableHead),
              tableCell: tableCell2
            });
            return true;
          }
          return false;
        }
      }
    }
  });
}
function task() {
  return new Plugin({
    props: {
      handleDOMEvents: {
        mousedown: function(view, ev) {
          var _a = ev, clientX = _a.clientX, clientY = _a.clientY;
          var mousePos = view.posAtCoords({ left: clientX, top: clientY });
          if (mousePos) {
            var _b = view.state, doc3 = _b.doc, tr = _b.tr;
            var currentPos = doc3.resolve(mousePos.pos);
            var listItem2 = findListItem(currentPos);
            var target2 = ev.target;
            var style = getComputedStyle(target2, ":before");
            var _c = ev, offsetX = _c.offsetX, offsetY = _c.offsetY;
            if (!listItem2 || !isPositionInBox(style, offsetX, offsetY)) {
              return false;
            }
            ev.preventDefault();
            var offset = currentPos.before(listItem2.depth);
            var attrs = listItem2.node.attrs;
            tr.setNodeMarkup(offset, null, __assign$1(__assign$1({}, attrs), { checked: !attrs.checked }));
            view.dispatch(tr);
            return true;
          }
          return false;
        }
      }
    }
  });
}
var EXCEPT_TYPES = ["image", "link", "customBlock", "frontMatter"];
var MARK_TYPES = ["strong", "strike", "emph", "code"];
var LIST_TYPES = ["bulletList", "orderedList", "taskList"];
function getToolbarStateType(node, parentNode2) {
  var type = node.type.name;
  if (type === "listItem") {
    return node.attrs.task ? "taskList" : parentNode2.type.name;
  }
  if (type.indexOf("table") !== -1) {
    return "table";
  }
  return type;
}
function setListNodeToolbarState(type, nodeTypeState) {
  nodeTypeState[type] = { active: true };
  LIST_TYPES.filter(function(listName) {
    return listName !== type;
  }).forEach(function(listType) {
    if (nodeTypeState[listType]) {
      delete nodeTypeState[listType];
    }
  });
}
function setMarkTypeStates(from2, to, schema, toolbarState) {
  MARK_TYPES.forEach(function(type) {
    var mark = schema.marks[type];
    var marksAtPos = from2.marksAcross(to) || [];
    var foundMark = !!mark.isInSet(marksAtPos);
    if (foundMark) {
      toolbarState[type] = { active: true };
    }
  });
}
function getToolbarState(selection, doc3, schema) {
  var $from = selection.$from, $to = selection.$to, from2 = selection.from, to = selection.to;
  var toolbarState = {
    indent: { active: false, disabled: true },
    outdent: { active: false, disabled: true }
  };
  doc3.nodesBetween(from2, to, function(node, _, parentNode2) {
    var type = getToolbarStateType(node, parentNode2);
    if (includes(EXCEPT_TYPES, type)) {
      return;
    }
    if (includes(LIST_TYPES, type)) {
      setListNodeToolbarState(type, toolbarState);
      toolbarState.indent.disabled = false;
      toolbarState.outdent.disabled = false;
    } else if (type === "paragraph" || type === "text") {
      setMarkTypeStates($from, $to, schema, toolbarState);
    } else {
      toolbarState[type] = { active: true };
    }
  });
  return toolbarState;
}
function toolbarStateHighlight(eventEmitter) {
  return new Plugin({
    view: function() {
      return {
        update: function(view) {
          var _a = view.state, selection = _a.selection, doc3 = _a.doc, schema = _a.schema;
          eventEmitter.emit("changeToolbarState", {
            toolbarState: getToolbarState(selection, doc3, schema)
          });
        }
      };
    }
  });
}
var CustomBlockView = (
  /** @class */
  (function() {
    function CustomBlockView2(node, view, getPos, toDOMAdaptor) {
      var _this = this;
      this.openEditor = function() {
        if (_this.innerEditorView) {
          throw new Error("The editor is already opened.");
        }
        _this.dom.draggable = false;
        _this.wrapper.style.display = "none";
        _this.innerViewContainer.style.display = "block";
        _this.innerEditorView = new EditorView(_this.innerViewContainer, {
          state: EditorState.create({
            doc: _this.node,
            plugins: [
              keymap({
                "Mod-z": function() {
                  return undo(_this.innerEditorView.state, _this.innerEditorView.dispatch);
                },
                "Shift-Mod-z": function() {
                  return redo(_this.innerEditorView.state, _this.innerEditorView.dispatch);
                },
                Tab: function(state, dispatch) {
                  dispatch(state.tr.insertText("	"));
                  return true;
                },
                Enter: newlineInCode,
                Escape: function() {
                  _this.cancelEditing();
                  return true;
                },
                "Ctrl-Enter": function() {
                  _this.saveAndFinishEditing();
                  return true;
                }
              }),
              history()
            ]
          }),
          dispatchTransaction: function(tr) {
            return _this.dispatchInner(tr);
          },
          handleDOMEvents: {
            mousedown: function() {
              if (_this.editorView.hasFocus()) {
                _this.innerEditorView.focus();
              }
              return true;
            },
            blur: function() {
              _this.saveAndFinishEditing();
              return true;
            }
          }
        });
        _this.innerEditorView.focus();
      };
      this.node = node;
      this.editorView = view;
      this.getPos = getPos;
      this.toDOMAdaptor = toDOMAdaptor;
      this.innerEditorView = null;
      this.canceled = false;
      this.dom = document.createElement("div");
      this.dom.className = cls("custom-block");
      this.wrapper = document.createElement("div");
      this.wrapper.className = cls("custom-block-view");
      this.createInnerViewContainer();
      this.renderCustomBlock();
      this.dom.appendChild(this.innerViewContainer);
      this.dom.appendChild(this.wrapper);
    }
    CustomBlockView2.prototype.renderToolArea = function() {
      var _this = this;
      var tool = document.createElement("div");
      var span = document.createElement("span");
      var button = document.createElement("button");
      tool.className = "tool";
      span.textContent = this.node.attrs.info;
      span.className = "info";
      button.type = "button";
      button.addEventListener("click", function() {
        return _this.openEditor();
      });
      tool.appendChild(span);
      tool.appendChild(button);
      this.wrapper.appendChild(tool);
    };
    CustomBlockView2.prototype.renderCustomBlock = function() {
      var toDOMNode = this.toDOMAdaptor.getToDOMNode(this.node.attrs.info);
      if (toDOMNode) {
        var node = toDOMNode(this.node);
        while (this.wrapper.hasChildNodes()) {
          this.wrapper.removeChild(this.wrapper.lastChild);
        }
        if (node) {
          this.wrapper.appendChild(node);
        }
        this.renderToolArea();
      }
    };
    CustomBlockView2.prototype.createInnerViewContainer = function() {
      this.innerViewContainer = document.createElement("div");
      this.innerViewContainer.className = cls("custom-block-editor");
      this.innerViewContainer.style.display = "none";
    };
    CustomBlockView2.prototype.closeEditor = function() {
      if (this.innerEditorView) {
        this.innerEditorView.destroy();
        this.innerEditorView = null;
        this.innerViewContainer.style.display = "none";
      }
      this.wrapper.style.display = "block";
    };
    CustomBlockView2.prototype.saveAndFinishEditing = function() {
      var to = this.editorView.state.selection.to;
      var outerState = this.editorView.state;
      this.editorView.dispatch(outerState.tr.setSelection(createTextSelection(outerState.tr, to)));
      this.editorView.focus();
      this.renderCustomBlock();
      this.closeEditor();
    };
    CustomBlockView2.prototype.cancelEditing = function() {
      var undoableCount = undoDepth(this.innerEditorView.state);
      this.canceled = true;
      while (undoableCount--) {
        undo(this.innerEditorView.state, this.innerEditorView.dispatch);
        undo(this.editorView.state, this.editorView.dispatch);
      }
      this.canceled = false;
      var to = this.editorView.state.selection.to;
      var outerState = this.editorView.state;
      this.editorView.dispatch(outerState.tr.setSelection(TextSelection.create(outerState.doc, to)));
      this.editorView.focus();
      this.closeEditor();
    };
    CustomBlockView2.prototype.dispatchInner = function(tr) {
      var _a = this.innerEditorView.state.applyTransaction(tr), state = _a.state, transactions = _a.transactions;
      this.innerEditorView.updateState(state);
      if (!this.canceled && isFunction_1(this.getPos)) {
        var outerTr = this.editorView.state.tr;
        var offsetMap = StepMap.offset(this.getPos() + 1);
        for (var i = 0; i < transactions.length; i += 1) {
          var steps = transactions[i].steps;
          for (var j = 0; j < steps.length; j += 1) {
            outerTr.step(steps[j].map(offsetMap));
          }
        }
        if (outerTr.docChanged) {
          this.editorView.dispatch(outerTr);
        }
      }
    };
    CustomBlockView2.prototype.update = function(node) {
      if (!node.sameMarkup(this.node)) {
        return false;
      }
      this.node = node;
      if (!this.innerEditorView) {
        this.renderCustomBlock();
      }
      return true;
    };
    CustomBlockView2.prototype.stopEvent = function(event) {
      return !!this.innerEditorView && !!event.target && this.innerEditorView.dom.contains(event.target);
    };
    CustomBlockView2.prototype.ignoreMutation = function() {
      return true;
    };
    CustomBlockView2.prototype.destroy = function() {
      this.dom.removeEventListener("dblclick", this.openEditor);
      this.closeEditor();
    };
    return CustomBlockView2;
  })()
);
var IMAGE_LINK_CLASS_NAME = "image-link";
var ImageView = (
  /** @class */
  (function() {
    function ImageView2(node, view, getPos, eventEmitter) {
      var _this = this;
      var _a;
      this.handleMousedown = function(ev) {
        ev.preventDefault();
        var target2 = ev.target, offsetX = ev.offsetX, offsetY = ev.offsetY;
        if (_this.imageLink && isFunction_1(_this.getPos) && hasClass_1(target2, IMAGE_LINK_CLASS_NAME)) {
          var style = getComputedStyle(target2, ":before");
          ev.stopPropagation();
          if (isPositionInBox(style, offsetX, offsetY)) {
            var tr = _this.view.state.tr;
            var pos = _this.getPos();
            tr.setSelection(createTextSelection(tr, pos, pos + 1));
            _this.view.dispatch(tr);
            _this.eventEmitter.emit("openPopup", "link", _this.imageLink.attrs);
          }
        }
      };
      this.node = node;
      this.view = view;
      this.getPos = getPos;
      this.eventEmitter = eventEmitter;
      this.imageLink = (_a = node.marks.filter(function(_a2) {
        var type = _a2.type;
        return type.name === "link";
      })[0]) !== null && _a !== void 0 ? _a : null;
      this.dom = this.createElement();
      this.bindEvent();
    }
    ImageView2.prototype.createElement = function() {
      var image2 = this.createImageElement(this.node);
      if (this.imageLink) {
        var wrapper = document.createElement("span");
        wrapper.className = IMAGE_LINK_CLASS_NAME;
        wrapper.appendChild(image2);
        return wrapper;
      }
      return image2;
    };
    ImageView2.prototype.createImageElement = function(node) {
      var image2 = document.createElement("img");
      var _a = node.attrs, imageUrl = _a.imageUrl, altText = _a.altText;
      var attrs = getCustomAttrs(node.attrs);
      image2.src = imageUrl;
      if (altText) {
        image2.alt = altText;
      }
      setAttributes(attrs, image2);
      return image2;
    };
    ImageView2.prototype.bindEvent = function() {
      if (this.imageLink) {
        this.dom.addEventListener("mousedown", this.handleMousedown);
      }
    };
    ImageView2.prototype.stopEvent = function() {
      return true;
    };
    ImageView2.prototype.destroy = function() {
      if (this.imageLink) {
        this.dom.removeEventListener("mousedown", this.handleMousedown);
      }
    };
    return ImageView2;
  })()
);
var WRAPPER_CLASS_NAME = "toastui-editor-ww-code-block";
var CODE_BLOCK_LANG_CLASS_NAME = "toastui-editor-ww-code-block-language";
var CodeBlockView = (
  /** @class */
  (function() {
    function CodeBlockView2(node, view, getPos, eventEmitter) {
      var _this = this;
      this.contentDOM = null;
      this.input = null;
      this.timer = null;
      this.handleMousedown = function(ev) {
        var target2 = ev.target;
        var style = getComputedStyle(target2, ":after");
        if (style.backgroundImage !== "none" && isFunction_1(_this.getPos)) {
          var _a = _this.view.coordsAtPos(_this.getPos()), top_1 = _a.top, right = _a.right;
          _this.createLanguageEditor({ top: top_1, right });
        }
      };
      this.handleKeydown = function(ev) {
        if (ev.key === "Enter" && _this.input) {
          ev.preventDefault();
          _this.changeLanguage();
        }
      };
      this.node = node;
      this.view = view;
      this.getPos = getPos;
      this.eventEmitter = eventEmitter;
      this.createElement();
      this.bindDOMEvent();
      this.bindEvent();
    }
    CodeBlockView2.prototype.createElement = function() {
      var language = this.node.attrs.language;
      var wrapper = document.createElement("div");
      wrapper.setAttribute("data-language", language || "text");
      wrapper.className = WRAPPER_CLASS_NAME;
      var pre2 = this.createCodeBlockElement();
      var code2 = pre2.firstChild;
      wrapper.appendChild(pre2);
      this.dom = wrapper;
      this.contentDOM = code2;
    };
    CodeBlockView2.prototype.createCodeBlockElement = function() {
      var pre2 = document.createElement("pre");
      var code2 = document.createElement("code");
      var language = this.node.attrs.language;
      var attrs = getCustomAttrs(this.node.attrs);
      if (language) {
        code2.setAttribute("data-language", language);
      }
      setAttributes(attrs, pre2);
      pre2.appendChild(code2);
      return pre2;
    };
    CodeBlockView2.prototype.createLanguageEditor = function(_a) {
      var _this = this;
      var top2 = _a.top, right = _a.right;
      var wrapper = document.createElement("span");
      wrapper.className = CODE_BLOCK_LANG_CLASS_NAME;
      var input = document.createElement("input");
      input.type = "text";
      input.value = this.node.attrs.language;
      wrapper.appendChild(input);
      this.view.dom.parentElement.appendChild(wrapper);
      var wrpperWidth = wrapper.clientWidth;
      css_1(wrapper, {
        top: top2 + 10 + "px",
        left: right - wrpperWidth - 10 + "px",
        width: wrpperWidth + "px"
      });
      this.input = input;
      this.input.addEventListener("blur", function() {
        return _this.changeLanguage();
      });
      this.input.addEventListener("keydown", this.handleKeydown);
      this.clearTimer();
      this.timer = setTimeout(function() {
        _this.input.focus();
      });
    };
    CodeBlockView2.prototype.bindDOMEvent = function() {
      if (this.dom) {
        this.dom.addEventListener("click", this.handleMousedown);
      }
    };
    CodeBlockView2.prototype.bindEvent = function() {
      var _this = this;
      this.eventEmitter.listen("scroll", function() {
        if (_this.input) {
          _this.reset();
        }
      });
    };
    CodeBlockView2.prototype.changeLanguage = function() {
      if (this.input && isFunction_1(this.getPos)) {
        var value = this.input.value;
        this.reset();
        var pos = this.getPos();
        var tr = this.view.state.tr;
        tr.setNodeMarkup(pos, null, { language: value });
        this.view.dispatch(tr);
      }
    };
    CodeBlockView2.prototype.reset = function() {
      var _a;
      if ((_a = this.input) === null || _a === void 0 ? void 0 : _a.parentElement) {
        var parent_1 = this.input.parentElement;
        this.input = null;
        removeNode$1(parent_1);
      }
    };
    CodeBlockView2.prototype.clearTimer = function() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    };
    CodeBlockView2.prototype.stopEvent = function() {
      return true;
    };
    CodeBlockView2.prototype.update = function(node) {
      if (!node.sameMarkup(this.node)) {
        return false;
      }
      this.node = node;
      return true;
    };
    CodeBlockView2.prototype.destroy = function() {
      this.reset();
      this.clearTimer();
      if (this.dom) {
        this.dom.removeEventListener("click", this.handleMousedown);
      }
    };
    return CodeBlockView2;
  })()
);
var reMSOListClassName = /MsoListParagraph/;
var reMSOStylePrefix = /style=(.|\n)*mso-/;
var reMSOListStyle = /mso-list:(.*)/;
var reMSOTagName = /O:P/;
var reMSOListBullet = /^(n|u|l)/;
var MSO_CLASS_NAME_LIST_PARA = "p.MsoListParagraph";
function isFromMso(html2) {
  return reMSOStylePrefix.test(html2);
}
function getListItemContents(para2) {
  var removedNodes = [];
  var walker = document.createTreeWalker(para2, 1, null, false);
  while (walker.nextNode()) {
    var node = walker.currentNode;
    if (isElemNode(node)) {
      var _a = node, outerHTML = _a.outerHTML, textContent = _a.textContent;
      var msoSpan = reMSOStylePrefix.test(outerHTML);
      var bulletSpan = reMSOListStyle.test(outerHTML);
      if (msoSpan && !bulletSpan && textContent) {
        removedNodes.push([node, true]);
      } else if (reMSOTagName.test(node.nodeName) || msoSpan && !textContent || bulletSpan) {
        removedNodes.push([node, false]);
      }
    }
  }
  removedNodes.forEach(function(_a2) {
    var node2 = _a2[0], isUnwrap = _a2[1];
    if (isUnwrap) {
      unwrapNode(node2);
    } else {
      removeNode$1(node2);
    }
  });
  return para2.innerHTML.trim();
}
function createListItemDataFromParagraph(para2, index2) {
  var styleAttr = para2.getAttribute("style");
  if (styleAttr) {
    var _a = styleAttr.match(reMSOListStyle), listItemInfo = _a[1];
    var _b = listItemInfo.trim().split(" "), levelStr = _b[1];
    var level = parseInt(levelStr.replace("level", ""), 10);
    var unordered = reMSOListBullet.test(para2.textContent || "");
    return {
      id: index2,
      level,
      prev: null,
      parent: null,
      children: [],
      unordered,
      contents: getListItemContents(para2)
    };
  }
  return null;
}
function addListItemDetailData(data, prevData) {
  if (prevData.level < data.level) {
    prevData.children.push(data);
    data.parent = prevData;
  } else {
    while (prevData) {
      if (prevData.level === data.level) {
        break;
      }
      prevData = prevData.parent;
    }
    if (prevData) {
      data.prev = prevData;
      data.parent = prevData.parent;
      if (data.parent) {
        data.parent.children.push(data);
      }
    }
  }
}
function createListData(paras) {
  var listData = [];
  paras.forEach(function(para2, index2) {
    var prevListItemData = listData[index2 - 1];
    var listItemData = createListItemDataFromParagraph(para2, index2);
    if (listItemData) {
      if (prevListItemData) {
        addListItemDetailData(listItemData, prevListItemData);
      }
      listData.push(listItemData);
    }
  });
  return listData;
}
function makeList(listData) {
  var listTagName = listData[0].unordered ? "ul" : "ol";
  var list2 = document.createElement(listTagName);
  listData.forEach(function(data) {
    var children = data.children, contents = data.contents;
    var listItem2 = document.createElement("li");
    listItem2.innerHTML = contents;
    list2.appendChild(listItem2);
    if (children.length) {
      list2.appendChild(makeList(children));
    }
  });
  return list2;
}
function makeListFromParagraphs(paras) {
  var listData = createListData(paras);
  var rootChildren = listData.filter(function(_a) {
    var parent = _a.parent;
    return !parent;
  });
  return makeList(rootChildren);
}
function isMsoListParagraphEnd(node) {
  while (node) {
    if (isElemNode(node)) {
      break;
    }
    node = node.nextSibling;
  }
  return node ? !reMSOListClassName.test(node.className) : true;
}
function convertMsoParagraphsToList(html2) {
  var container = document.createElement("div");
  container.innerHTML = html2;
  var paras = [];
  var foundParas = findNodes(container, MSO_CLASS_NAME_LIST_PARA);
  foundParas.forEach(function(para2) {
    var msoListParaEnd = isMsoListParagraphEnd(para2.nextSibling);
    paras.push(para2);
    if (msoListParaEnd) {
      var list2 = makeListFromParagraphs(paras);
      var nextSibling = para2.nextSibling;
      if (nextSibling) {
        insertBeforeNode(list2, nextSibling);
      } else {
        appendNodes(container, list2);
      }
      paras = [];
    }
    removeNode$1(para2);
  });
  var extraHTML = foundParas.length ? "<p></p>" : "";
  return "" + extraHTML + container.innerHTML;
}
var START_FRAGMENT_COMMENT = "<!--StartFragment-->";
var END_FRAGMENT_COMMENT = "<!--EndFragment-->";
function getContentBetweenFragmentComments(html2) {
  var startFragmentIndex = html2.indexOf(START_FRAGMENT_COMMENT);
  var endFragmentIndex = html2.lastIndexOf(END_FRAGMENT_COMMENT);
  if (startFragmentIndex > -1 && endFragmentIndex > -1) {
    html2 = html2.slice(startFragmentIndex + START_FRAGMENT_COMMENT.length, endFragmentIndex);
  }
  return html2.replace(/<br[^>]*>/g, ALTERNATIVE_TAG_FOR_BR);
}
function convertMsoTableToCompletedTable(html2) {
  if (/<\/td>((?!<\/tr>)[\s\S])*$/i.test(html2)) {
    html2 = "<tr>" + html2 + "</tr>";
  }
  if (/<\/tr>((?!<\/table>)[\s\S])*$/i.test(html2)) {
    html2 = "<table>" + html2 + "</table>";
  }
  return html2;
}
function changePastedHTML(html2) {
  html2 = getContentBetweenFragmentComments(html2);
  html2 = convertMsoTableToCompletedTable(html2);
  if (isFromMso(html2)) {
    html2 = convertMsoParagraphsToList(html2);
  }
  return html2;
}
function getMaxColumnCount(rows) {
  var row = rows.reduce(function(prevRow, currentRow) {
    return prevRow.childCount > currentRow.childCount ? prevRow : currentRow;
  });
  return row.childCount;
}
function createCells(orgRow, maxColumnCount, cell) {
  var cells = [];
  var cellCount = orgRow.childCount;
  for (var colIdx = 0; colIdx < cellCount; colIdx += 1) {
    if (!orgRow.child(colIdx).attrs.extended) {
      var copiedCell = colIdx < cellCount ? cell.create(orgRow.child(colIdx).attrs, orgRow.child(colIdx).content) : cell.createAndFill();
      cells.push(copiedCell);
    }
  }
  return cells;
}
function copyTableHeadRow(orgRow, maxColumnCount, schema) {
  var _a = schema.nodes, tableRow2 = _a.tableRow, tableHeadCell = _a.tableHeadCell;
  var cells = createCells(orgRow, maxColumnCount, tableHeadCell);
  return tableRow2.create(null, cells);
}
function copyTableBodyRow(orgRow, maxColumnCount, schema) {
  var _a = schema.nodes, tableRow2 = _a.tableRow, tableBodyCell = _a.tableBodyCell;
  var cells = createCells(orgRow, maxColumnCount, tableBodyCell);
  return tableRow2.create(null, cells);
}
function creatTableBodyDummyRow(columnCount, schema) {
  var _a = schema.nodes, tableRow2 = _a.tableRow, tableBodyCell = _a.tableBodyCell;
  var cells = [];
  for (var columnIndex = 0; columnIndex < columnCount; columnIndex += 1) {
    var dummyCell = tableBodyCell.createAndFill();
    cells.push(dummyCell);
  }
  return tableRow2.create({ dummyRowForPasting: true }, cells);
}
function createRowsFromPastingTable(tableContent) {
  var tableHeadRows = [];
  var tableBodyRows = [];
  if (tableContent.firstChild.type.name === "tableHead") {
    var tableHead2 = tableContent.firstChild;
    tableHead2.forEach(function(row) {
      return tableHeadRows.push(row);
    });
  }
  if (tableContent.lastChild.type.name === "tableBody") {
    var tableBody2 = tableContent.lastChild;
    tableBody2.forEach(function(row) {
      return tableBodyRows.push(row);
    });
  }
  return __spreadArray$1(__spreadArray$1([], tableHeadRows), tableBodyRows);
}
function createTableHead(tableHeadRow, maxColumnCount, schema) {
  var copiedRow = copyTableHeadRow(tableHeadRow, maxColumnCount, schema);
  return schema.nodes.tableHead.create(null, copiedRow);
}
function createTableBody(tableBodyRows, maxColumnCount, schema) {
  var copiedRows = tableBodyRows.map(function(tableBodyRow) {
    return copyTableBodyRow(tableBodyRow, maxColumnCount, schema);
  });
  if (!tableBodyRows.length) {
    var dummyTableRow = creatTableBodyDummyRow(maxColumnCount, schema);
    copiedRows.push(dummyTableRow);
  }
  return schema.nodes.tableBody.create(null, copiedRows);
}
function createTableFromPastingTable(rows, schema, startFromBody, isInTable) {
  var columnCount = getMaxColumnCount(rows);
  if (startFromBody && isInTable) {
    return schema.nodes.table.create(null, [createTableBody(rows, columnCount, schema)]);
  }
  var tableHeadRow = rows[0];
  var tableBodyRows = rows.slice(1);
  var nodes = [createTableHead(tableHeadRow, columnCount, schema)];
  if (tableBodyRows.length) {
    nodes.push(createTableBody(tableBodyRows, columnCount, schema));
  }
  return schema.nodes.table.create(null, nodes);
}
function changePastedSlice(slice2, schema, isInTable) {
  var nodes = [];
  var content = slice2.content, openStart = slice2.openStart, openEnd = slice2.openEnd;
  content.forEach(function(node) {
    if (node.type.name === "table") {
      var tableContent = getTableContentFromSlice(new Slice(Fragment.from(node), 0, 0));
      if (tableContent) {
        var rows = createRowsFromPastingTable(tableContent);
        var startFromBody = tableContent.firstChild.type.name === "tableBody";
        var table2 = createTableFromPastingTable(rows, schema, startFromBody, isInTable);
        nodes.push(table2);
      }
    } else {
      nodes.push(node);
    }
  });
  return new Slice(Fragment.from(nodes), openStart, openEnd);
}
var DUMMY_CELL_SIZE = 4;
var TR_NODES_SIZE = 2;
function getDummyCellSize(dummyCellCount) {
  return dummyCellCount * DUMMY_CELL_SIZE;
}
function createPastingCells(tableContent, curSelectionInfo, schema) {
  var pastingRows = [];
  var pastingTableRows = createRowsFromPastingTable(tableContent);
  var columnCount = pastingTableRows[0].childCount;
  var rowCount = pastingTableRows.length;
  var startToTableHead = curSelectionInfo.startRowIdx === 0;
  var slicedRows = pastingTableRows.slice(0, rowCount);
  if (startToTableHead) {
    var tableHeadRow = slicedRows.shift();
    if (tableHeadRow) {
      var content = copyTableHeadRow(tableHeadRow, columnCount, schema).content;
      pastingRows.push(content);
    }
  }
  slicedRows.forEach(function(tableBodyRow) {
    if (!tableBodyRow.attrs.dummyRowForPasting) {
      var content2 = copyTableBodyRow(tableBodyRow, columnCount, schema).content;
      pastingRows.push(content2);
    }
  });
  return pastingRows;
}
function getPastingRangeInfo(map3, _a, pastingCells) {
  var startRowIdx = _a.startRowIdx, startColIdx = _a.startColIdx;
  var pastingRowCount = pastingCells.length;
  var pastingColumnCount = 0;
  var _loop_1 = function(i2) {
    var columnCount = pastingCells[i2].childCount;
    pastingCells[i2].forEach(function(_a2) {
      var attrs = _a2.attrs;
      var colspan = attrs.colspan;
      if (colspan > 1) {
        columnCount += colspan - 1;
      }
    });
    pastingColumnCount = Math.max(pastingColumnCount, columnCount);
  };
  for (var i = 0; i < pastingRowCount; i += 1) {
    _loop_1(i);
  }
  var endRowIdx = startRowIdx + pastingRowCount - 1;
  var endColIdx = startColIdx + pastingColumnCount - 1;
  var addedRowCount = Math.max(endRowIdx + 1 - map3.totalRowCount, 0);
  var addedColumnCount = Math.max(endColIdx + 1 - map3.totalColumnCount, 0);
  return {
    startRowIdx,
    startColIdx,
    endRowIdx,
    endColIdx,
    addedRowCount,
    addedColumnCount
  };
}
function addReplacedOffsets(_a, cellsOffsets) {
  var startRowIdx = _a.startRowIdx, startColIdx = _a.startColIdx, endRowIdx = _a.endRowIdx, endColIdx = _a.endColIdx, addedRowCount = _a.addedRowCount, addedColumnCount = _a.addedColumnCount;
  for (var rowIdx = startRowIdx; rowIdx <= endRowIdx - addedRowCount; rowIdx += 1) {
    cellsOffsets.push({
      rowIdx,
      startColIdx,
      endColIdx: endColIdx - addedColumnCount
    });
  }
}
function expandColumns(tr, schema, map3, _a, cellsOffsets) {
  var startRowIdx = _a.startRowIdx, startColIdx = _a.startColIdx, endRowIdx = _a.endRowIdx, endColIdx = _a.endColIdx, addedRowCount = _a.addedRowCount, addedColumnCount = _a.addedColumnCount;
  var totalRowCount = map3.totalRowCount;
  var index2 = 0;
  for (var rowIdx = 0; rowIdx < totalRowCount; rowIdx += 1) {
    var _b = map3.getCellInfo(rowIdx, endColIdx - addedColumnCount), offset = _b.offset, nodeSize2 = _b.nodeSize;
    var insertOffset = tr.mapping.map(offset + nodeSize2);
    var cells = createDummyCells(addedColumnCount, rowIdx, schema);
    tr.insert(insertOffset, cells);
    if (rowIdx >= startRowIdx && rowIdx <= endRowIdx - addedRowCount) {
      var cellInfo = map3.getCellInfo(rowIdx, endColIdx - addedColumnCount);
      var startCellOffset = tr.mapping.map(cellInfo.offset);
      var endCellOffset = insertOffset + getDummyCellSize(addedColumnCount);
      cellsOffsets[index2] = {
        rowIdx,
        startColIdx,
        endColIdx,
        dummyOffsets: [startCellOffset, endCellOffset]
      };
      index2 += 1;
    }
  }
}
function expandRows(tr, schema, map3, _a, cellsOffsets) {
  var addedRowCount = _a.addedRowCount, addedColumnCount = _a.addedColumnCount, startColIdx = _a.startColIdx, endColIdx = _a.endColIdx;
  var mapStart = tr.mapping.maps.length;
  var tableEndPos = map3.tableEndOffset - 2;
  var rows = createTableBodyRows(addedRowCount, map3.totalColumnCount + addedColumnCount, schema);
  var startOffset = tableEndPos;
  tr.insert(tr.mapping.slice(mapStart).map(startOffset), rows);
  for (var rowIndex = 0; rowIndex < addedRowCount; rowIndex += 1) {
    var startCellOffset = startOffset + getDummyCellSize(startColIdx) + 1;
    var endCellOffset = startOffset + getDummyCellSize(endColIdx + 1) + 1;
    var nextCellOffset = startOffset + getDummyCellSize(map3.totalColumnCount + addedColumnCount) + TR_NODES_SIZE;
    cellsOffsets.push({
      rowIdx: rowIndex + map3.totalRowCount,
      startColIdx,
      endColIdx,
      dummyOffsets: [startCellOffset, endCellOffset]
    });
    startOffset = nextCellOffset;
  }
}
function replaceCells(tr, pastingRows, cellsOffsets, map3) {
  var mapStart = tr.mapping.maps.length;
  cellsOffsets.forEach(function(offsets, index2) {
    var rowIdx = offsets.rowIdx, startColIdx = offsets.startColIdx, endColIdx = offsets.endColIdx, dummyOffsets = offsets.dummyOffsets;
    var mapping = tr.mapping.slice(mapStart);
    var cells = new Slice(pastingRows[index2], 0, 0);
    var from2 = dummyOffsets ? dummyOffsets[0] : map3.getCellStartOffset(rowIdx, startColIdx);
    var to = dummyOffsets ? dummyOffsets[1] : map3.getCellEndOffset(rowIdx, endColIdx);
    tr.replace(mapping.map(from2), mapping.map(to), cells);
  });
}
function pasteToTable(view, slice2) {
  var _a = view.state, selection = _a.selection, schema = _a.schema, tr = _a.tr;
  var _b = getResolvedSelection(selection), anchor = _b.anchor, head = _b.head;
  if (anchor && head) {
    var tableContent = getTableContentFromSlice(slice2);
    if (!tableContent) {
      return false;
    }
    var map3 = TableOffsetMap.create(anchor);
    var curSelectionInfo = map3.getRectOffsets(anchor, head);
    var pastingCells = createPastingCells(tableContent, curSelectionInfo, schema);
    var pastingInfo = getPastingRangeInfo(map3, curSelectionInfo, pastingCells);
    var cellsOffsets = [];
    if (canMerge(map3, pastingInfo)) {
      addReplacedOffsets(pastingInfo, cellsOffsets);
      if (pastingInfo.addedColumnCount) {
        expandColumns(tr, schema, map3, pastingInfo, cellsOffsets);
      }
      if (pastingInfo.addedRowCount) {
        expandRows(tr, schema, map3, pastingInfo, cellsOffsets);
      }
      replaceCells(tr, pastingCells, cellsOffsets, map3);
      view.dispatch(tr);
      setSelection(view, cellsOffsets, map3.getCellInfo(0, 0).offset);
    }
    return true;
  }
  return false;
}
function setSelection(view, cellsOffsets, pos) {
  var _a = view.state, tr = _a.tr, doc3 = _a.doc;
  var map3 = TableOffsetMap.create(doc3.resolve(pos));
  var _b = cellsOffsets[0], startRowIdx = _b.rowIdx, startColIdx = _b.startColIdx;
  var _c = last$1(cellsOffsets), endRowIdx = _c.rowIdx, endColIdx = _c.endColIdx;
  var startOffset = map3.getCellInfo(startRowIdx, startColIdx).offset;
  var endOffset = map3.getCellInfo(endRowIdx, endColIdx).offset;
  view.dispatch(tr.setSelection(new CellSelection(doc3.resolve(startOffset), doc3.resolve(endOffset))));
}
function canMerge(map3, pastingInfo) {
  var ranges = map3.getSpannedOffsets(pastingInfo);
  var _a = getRowAndColumnCount(ranges), rowCount = _a.rowCount, columnCount = _a.columnCount;
  var _b = getRowAndColumnCount(pastingInfo), pastingRowCount = _b.rowCount, pastingColumnCount = _b.columnCount;
  return rowCount === pastingRowCount && columnCount === pastingColumnCount;
}
var Doc = (
  /** @class */
  (function(_super) {
    __extends$1(Doc2, _super);
    function Doc2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Doc2.prototype, "name", {
      get: function() {
        return "doc";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Doc2.prototype, "schema", {
      get: function() {
        return {
          content: "block+"
        };
      },
      enumerable: false,
      configurable: true
    });
    return Doc2;
  })(Node$2)
);
var Paragraph = (
  /** @class */
  (function(_super) {
    __extends$1(Paragraph2, _super);
    function Paragraph2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Paragraph2.prototype, "name", {
      get: function() {
        return "paragraph";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Paragraph2.prototype, "schema", {
      get: function() {
        return {
          content: "inline*",
          group: "block",
          attrs: __assign$1({}, getDefaultCustomAttrs()),
          parseDOM: [{ tag: "p" }],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["p", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return Paragraph2;
  })(Node$2)
);
var reSoftTabLen = /\s{1,4}$/;
var Text = (
  /** @class */
  (function(_super) {
    __extends$1(Text2, _super);
    function Text2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Text2.prototype, "name", {
      get: function() {
        return "text";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Text2.prototype, "schema", {
      get: function() {
        return {
          group: "inline"
        };
      },
      enumerable: false,
      configurable: true
    });
    Text2.prototype.addSpaces = function() {
      return function(_a, dispatch) {
        var selection = _a.selection, tr = _a.tr;
        var $from = selection.$from, $to = selection.$to;
        var range2 = $from.blockRange($to);
        if (range2 && !isInListNode($from) && !isInTableNode($from)) {
          dispatch(tr.insertText("    ", $from.pos, $to.pos));
          return true;
        }
        return false;
      };
    };
    Text2.prototype.removeSpaces = function() {
      return function(_a, dispatch) {
        var selection = _a.selection, tr = _a.tr;
        var $from = selection.$from, $to = selection.$to, from2 = selection.from;
        var range2 = $from.blockRange($to);
        if (range2 && !isInListNode($from) && !isInTableNode($from)) {
          var nodeBefore = $from.nodeBefore;
          if (nodeBefore && nodeBefore.isText) {
            var text2 = nodeBefore.text;
            var removedSpaceText = text2.replace(reSoftTabLen, "");
            var spaces = text2.length - removedSpaceText.length;
            dispatch(tr.delete(from2 - spaces, from2));
            return true;
          }
        }
        return false;
      };
    };
    Text2.prototype.keymaps = function() {
      return {
        Tab: this.addSpaces(),
        "Shift-Tab": this.removeSpaces()
      };
    };
    return Text2;
  })(Node$2)
);
var Heading = (
  /** @class */
  (function(_super) {
    __extends$1(Heading2, _super);
    function Heading2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Heading2.prototype, "name", {
      get: function() {
        return "heading";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Heading2.prototype, "levels", {
      get: function() {
        return [1, 2, 3, 4, 5, 6];
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Heading2.prototype, "schema", {
      get: function() {
        var parseDOM = this.levels.map(function(level) {
          return {
            tag: "h" + level,
            getAttrs: function(dom) {
              var rawHTML = dom.getAttribute("data-raw-html");
              return __assign$1({ level }, rawHTML && { rawHTML });
            }
          };
        });
        return {
          attrs: __assign$1({ level: { default: 1 }, headingType: { default: "atx" }, rawHTML: { default: null } }, getDefaultCustomAttrs()),
          content: "inline*",
          group: "block",
          defining: true,
          parseDOM,
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["h" + attrs.level, getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Heading2.prototype.commands = function() {
      return function(payload) {
        return function(state, dispatch) {
          var nodeType = state.schema.nodes[payload.level ? "heading" : "paragraph"];
          return setBlockType2(nodeType, payload)(state, dispatch);
        };
      };
    };
    return Heading2;
  })(Node$2)
);
var CodeBlock = (
  /** @class */
  (function(_super) {
    __extends$1(CodeBlock2, _super);
    function CodeBlock2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(CodeBlock2.prototype, "name", {
      get: function() {
        return "codeBlock";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(CodeBlock2.prototype, "schema", {
      get: function() {
        return {
          content: "text*",
          group: "block",
          attrs: __assign$1({ language: { default: null }, rawHTML: { default: null } }, getDefaultCustomAttrs()),
          code: true,
          defining: true,
          marks: "",
          parseDOM: [
            {
              tag: "pre",
              preserveWhitespace: "full",
              getAttrs: function(dom) {
                var rawHTML = dom.getAttribute("data-raw-html");
                var child = dom.firstElementChild;
                return __assign$1({ language: (child === null || child === void 0 ? void 0 : child.getAttribute("data-language")) || null }, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [
              attrs.rawHTML || "pre",
              ["code", __assign$1({ "data-language": attrs.language }, getCustomAttrs(attrs)), 0]
            ];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    CodeBlock2.prototype.commands = function() {
      return function() {
        return function(state, dispatch) {
          return setBlockType2(state.schema.nodes.codeBlock)(state, dispatch);
        };
      };
    };
    CodeBlock2.prototype.moveCursor = function(direction) {
      var _this = this;
      return function(state, dispatch) {
        var tr = state.tr, doc3 = state.doc, schema = state.schema;
        var $from = state.selection.$from;
        var view = _this.context.view;
        if (view.endOfTextblock(direction) && $from.node().type.name === "codeBlock") {
          var lines = $from.parent.textContent.split("\n");
          var offset = direction === "up" ? $from.start() : $from.end();
          var range2 = direction === "up" ? [offset, lines[0].length + offset] : [offset - last$1(lines).length, offset];
          var pos = doc3.resolve(direction === "up" ? $from.before() : $from.after());
          var node = direction === "up" ? pos.nodeBefore : pos.nodeAfter;
          if (between$1($from.pos, range2[0], range2[1]) && !node) {
            var newTr = addParagraph(tr, pos, schema);
            if (newTr) {
              dispatch(newTr);
              return true;
            }
          }
        }
        return false;
      };
    };
    CodeBlock2.prototype.keymaps = function() {
      var codeCommand = this.commands()();
      return {
        "Shift-Mod-p": codeCommand,
        "Shift-Mod-P": codeCommand,
        ArrowUp: this.moveCursor("up"),
        ArrowDown: this.moveCursor("down")
      };
    };
    return CodeBlock2;
  })(Node$2)
);
var BulletList = (
  /** @class */
  (function(_super) {
    __extends$1(BulletList2, _super);
    function BulletList2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BulletList2.prototype, "name", {
      get: function() {
        return "bulletList";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BulletList2.prototype, "schema", {
      get: function() {
        return {
          content: "listItem+",
          group: "block",
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [createDOMInfoParsedRawHTML("ul")],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["ul", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    BulletList2.prototype.changeList = function() {
      return function(state, dispatch) {
        return changeList(state.schema.nodes.bulletList)(state, dispatch);
      };
    };
    BulletList2.prototype.commands = function() {
      return {
        bulletList: this.changeList,
        taskList: toggleTask
      };
    };
    BulletList2.prototype.keymaps = function() {
      var bulletListCommand = this.changeList();
      var _a = getWwCommands(), indent2 = _a.indent, outdent2 = _a.outdent;
      return {
        "Mod-u": bulletListCommand,
        "Mod-U": bulletListCommand,
        Tab: indent2(),
        "Shift-Tab": outdent2()
      };
    };
    return BulletList2;
  })(Node$2)
);
var OrderedList = (
  /** @class */
  (function(_super) {
    __extends$1(OrderedList2, _super);
    function OrderedList2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(OrderedList2.prototype, "name", {
      get: function() {
        return "orderedList";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(OrderedList2.prototype, "schema", {
      get: function() {
        return {
          content: "listItem+",
          group: "block",
          attrs: __assign$1({ order: { default: 1 }, rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [
            {
              tag: "ol",
              getAttrs: function(dom) {
                var start = dom.getAttribute("start");
                var rawHTML = dom.getAttribute("data-raw-html");
                return __assign$1({ order: dom.hasAttribute("start") ? Number(start) : 1 }, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [
              attrs.rawHTML || "ol",
              __assign$1({ start: attrs.order === 1 ? null : attrs.order }, getCustomAttrs(attrs)),
              0
            ];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    OrderedList2.prototype.commands = function() {
      return function() {
        return function(state, dispatch) {
          return changeList(state.schema.nodes.orderedList)(state, dispatch);
        };
      };
    };
    OrderedList2.prototype.keymaps = function() {
      var orderedListCommand = this.commands()();
      var _a = getWwCommands(), indent2 = _a.indent, outdent2 = _a.outdent;
      return {
        "Mod-o": orderedListCommand,
        "Mod-O": orderedListCommand,
        Tab: indent2(),
        "Shift-Tab": outdent2()
      };
    };
    return OrderedList2;
  })(Node$2)
);
var ListItem = (
  /** @class */
  (function(_super) {
    __extends$1(ListItem2, _super);
    function ListItem2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ListItem2.prototype, "name", {
      get: function() {
        return "listItem";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(ListItem2.prototype, "schema", {
      get: function() {
        return {
          content: "paragraph block*",
          selectable: false,
          attrs: {
            task: { default: false },
            checked: { default: false },
            rawHTML: { default: null }
          },
          defining: true,
          parseDOM: [
            {
              tag: "li",
              getAttrs: function(dom) {
                var rawHTML = dom.getAttribute("data-raw-html");
                return __assign$1({ task: dom.hasAttribute("data-task"), checked: dom.hasAttribute("data-task-checked") }, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            var task2 = attrs.task, checked = attrs.checked;
            if (!task2) {
              return [attrs.rawHTML || "li", 0];
            }
            var classNames = ["task-list-item"];
            if (checked) {
              classNames.push("checked");
            }
            return [
              attrs.rawHTML || "li",
              __assign$1({ class: classNames.join(" "), "data-task": task2 }, checked && { "data-task-checked": checked }),
              0
            ];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    ListItem2.prototype.liftToPrevListItem = function() {
      return function(state, dispatch) {
        var selection = state.selection, tr = state.tr, schema = state.schema;
        var $from = selection.$from, empty3 = selection.empty;
        var listItem2 = schema.nodes.listItem;
        var parent = $from.parent;
        var listItemParent = $from.node(-1);
        if (empty3 && !parent.childCount && listItemParent.type === listItem2) {
          if ($from.index(-2) >= 1) {
            tr.delete($from.start(-1) - 1, $from.end(-1));
            dispatch(tr);
            return true;
          }
          var grandParentListItem = $from.node(-3);
          if (grandParentListItem.type === listItem2) {
            tr.delete($from.start(-2) - 1, $from.end(-1));
            dispatch(tr);
            return true;
          }
        }
        return false;
      };
    };
    ListItem2.prototype.keymaps = function() {
      var split2 = function(state, dispatch) {
        return splitListItem(state.schema.nodes.listItem)(state, dispatch);
      };
      return {
        Backspace: this.liftToPrevListItem(),
        Enter: split2
      };
    };
    return ListItem2;
  })(Node$2)
);
var BlockQuote = (
  /** @class */
  (function(_super) {
    __extends$1(BlockQuote2, _super);
    function BlockQuote2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BlockQuote2.prototype, "name", {
      get: function() {
        return "blockQuote";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BlockQuote2.prototype, "schema", {
      get: function() {
        return {
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          content: "block+",
          group: "block",
          parseDOM: [createDOMInfoParsedRawHTML("blockquote")],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["blockquote", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    BlockQuote2.prototype.commands = function() {
      return function() {
        return function(state, dispatch) {
          return wrapIn(state.schema.nodes.blockQuote)(state, dispatch);
        };
      };
    };
    BlockQuote2.prototype.keymaps = function() {
      var blockQutoeCommand = this.commands()();
      return {
        "Alt-q": blockQutoeCommand,
        "Alt-Q": blockQutoeCommand
      };
    };
    return BlockQuote2;
  })(Node$2)
);
var cellOffsetFnMap = {
  left: getLeftCellOffset,
  right: getRightCellOffset,
  up: getUpCellOffset,
  down: getDownCellOffset
};
function isInFirstListItem(pos, doc3, _a) {
  var paraDepth = _a[0], listDepth = _a[1];
  var listItemNode = doc3.resolve(pos.before(paraDepth - 1));
  return listDepth === paraDepth && !listItemNode.nodeBefore;
}
function isInLastListItem(pos) {
  var _a;
  var depth = pos.depth;
  var parentNode2;
  while (depth) {
    parentNode2 = pos.node(depth);
    if (parentNode2.type.name === "tableBodyCell") {
      break;
    }
    if (parentNode2.type.name === "listItem") {
      var grandParent = pos.node(depth - 1);
      var lastListItem = grandParent.lastChild === parentNode2;
      var hasChildren = ((_a = parentNode2.lastChild) === null || _a === void 0 ? void 0 : _a.type.name) !== "paragraph";
      if (!lastListItem) {
        return false;
      }
      return !hasChildren;
    }
    depth -= 1;
  }
  return false;
}
function canMoveToBeforeCell(direction, _a, from2, doc3, inList) {
  var paraDepth = _a[0], listDepth = _a[1], curDepth = _a[2];
  if (direction === "left" || direction === "up") {
    if (inList && !isInFirstListItem(from2, doc3, [paraDepth, listDepth])) {
      return false;
    }
    var endOffset = from2.before(curDepth);
    var nodeBefore = doc3.resolve(endOffset).nodeBefore;
    if (nodeBefore) {
      return false;
    }
  }
  return true;
}
function canMoveToAfterCell(direction, curDepth, from2, doc3, inList) {
  if (direction === "right" || direction === "down") {
    if (inList && !isInLastListItem(from2)) {
      return false;
    }
    var endOffset = from2.after(curDepth);
    var nodeAfter = doc3.resolve(endOffset).nodeAfter;
    if (nodeAfter) {
      return false;
    }
  }
  return true;
}
function canMoveBetweenCells(direction, _a, from2, doc3) {
  var cellDepth = _a[0], paraDepth = _a[1];
  var listDepth = cellDepth + 3;
  var inList = paraDepth >= listDepth;
  var curDepth = inList ? cellDepth + 1 : paraDepth;
  var moveBeforeCell = canMoveToBeforeCell(direction, [paraDepth, listDepth, curDepth], from2, doc3, inList);
  var moveAfterCell = canMoveToAfterCell(direction, curDepth, from2, doc3, inList);
  return moveBeforeCell && moveAfterCell;
}
function canBeOutOfTable(direction, map3, _a) {
  var rowIdx = _a[0], colIdx = _a[1];
  var rowspanInfo = map3.getRowspanStartInfo(rowIdx, colIdx);
  var inFirstRow = direction === "up" && rowIdx === 0;
  var inLastRow = direction === "down" && ((rowspanInfo === null || rowspanInfo === void 0 ? void 0 : rowspanInfo.count) > 1 ? rowIdx + rowspanInfo.count - 1 : rowIdx) === map3.totalRowCount - 1;
  return inFirstRow || inLastRow;
}
function addParagraphBeforeTable(tr, map3, schema) {
  var tableStartPos = tr.doc.resolve(map3.tableStartOffset - 1);
  if (!tableStartPos.nodeBefore) {
    return addParagraph(tr, tableStartPos, schema);
  }
  return tr.setSelection(Selection.near(tableStartPos, -1));
}
function addParagraphAfterTable(tr, map3, schema, forcedAddtion) {
  if (forcedAddtion === void 0) {
    forcedAddtion = false;
  }
  var tableEndPos = tr.doc.resolve(map3.tableEndOffset);
  if (forcedAddtion || !tableEndPos.nodeAfter) {
    return addParagraph(tr, tableEndPos, schema);
  }
  return tr.setSelection(Selection.near(tableEndPos, 1));
}
function getRightCellOffset(_a, map3) {
  var rowIdx = _a[0], colIdx = _a[1];
  var totalRowCount = map3.totalRowCount, totalColumnCount = map3.totalColumnCount;
  var lastCellInRow = colIdx === totalColumnCount - 1;
  var lastCellInTable = rowIdx === totalRowCount - 1 && lastCellInRow;
  if (!lastCellInTable) {
    var nextColIdx = colIdx + 1;
    var colspanInfo = map3.getColspanStartInfo(rowIdx, colIdx);
    if ((colspanInfo === null || colspanInfo === void 0 ? void 0 : colspanInfo.count) > 1) {
      nextColIdx += colspanInfo.count - 1;
    }
    if (lastCellInRow || nextColIdx === totalColumnCount) {
      rowIdx += 1;
      nextColIdx = 0;
    }
    var offset = map3.getCellInfo(rowIdx, nextColIdx).offset;
    return offset + 2;
  }
  return null;
}
function getLeftCellOffset(_a, map3) {
  var rowIdx = _a[0], colIdx = _a[1];
  var totalColumnCount = map3.totalColumnCount;
  var firstCellInRow = colIdx === 0;
  var firstCellInTable = rowIdx === 0 && firstCellInRow;
  if (!firstCellInTable) {
    colIdx -= 1;
    if (firstCellInRow) {
      rowIdx -= 1;
      colIdx = totalColumnCount - 1;
    }
    var _b = map3.getCellInfo(rowIdx, colIdx), offset = _b.offset, nodeSize2 = _b.nodeSize;
    return offset + nodeSize2 - 2;
  }
  return null;
}
function getUpCellOffset(_a, map3) {
  var rowIdx = _a[0], colIdx = _a[1];
  if (rowIdx > 0) {
    var _b = map3.getCellInfo(rowIdx - 1, colIdx), offset = _b.offset, nodeSize2 = _b.nodeSize;
    return offset + nodeSize2 - 2;
  }
  return null;
}
function getDownCellOffset(_a, map3) {
  var rowIdx = _a[0], colIdx = _a[1];
  var totalRowCount = map3.totalRowCount;
  if (rowIdx < totalRowCount - 1) {
    var nextRowIdx = rowIdx + 1;
    var rowspanInfo = map3.getRowspanStartInfo(rowIdx, colIdx);
    if ((rowspanInfo === null || rowspanInfo === void 0 ? void 0 : rowspanInfo.count) > 1) {
      nextRowIdx += rowspanInfo.count - 1;
    }
    var offset = map3.getCellInfo(nextRowIdx, colIdx).offset;
    return offset + 2;
  }
  return null;
}
function moveToCell(direction, tr, cellIndex, map3) {
  var cellOffsetFn = cellOffsetFnMap[direction];
  var offset = cellOffsetFn(cellIndex, map3);
  if (offset) {
    var dir = direction === "right" || direction === "down" ? 1 : -1;
    return tr.setSelection(Selection.near(tr.doc.resolve(offset), dir));
  }
  return null;
}
function canSelectTableNode(direction, map3, _a) {
  var rowIdx = _a[0], colIdx = _a[1];
  if (direction === "up" || direction === "down") {
    return false;
  }
  var tableStartOffset = map3.tableStartOffset, tableEndOffset = map3.tableEndOffset;
  var _b = map3.getCellInfo(rowIdx, colIdx), offset = _b.offset, nodeSize2 = _b.nodeSize;
  var pos = direction === "left" ? tableStartOffset : tableEndOffset;
  var curPos = direction === "left" ? offset - 2 : offset + nodeSize2 + 3;
  return pos === curPos;
}
function selectNode(tr, pos, depth) {
  var tablePos = tr.doc.resolve(pos.before(depth - 3));
  return tr.setSelection(new NodeSelection(tablePos));
}
function getTargetRowInfo(direction, map3, selectionInfo) {
  var targetRowIdx;
  var insertColIdx;
  var nodeSize2;
  if (direction === "up") {
    targetRowIdx = selectionInfo.startRowIdx;
    insertColIdx = 0;
    nodeSize2 = -1;
  } else {
    targetRowIdx = selectionInfo.endRowIdx;
    insertColIdx = map3.totalColumnCount - 1;
    nodeSize2 = map3.getCellInfo(targetRowIdx, insertColIdx).nodeSize + 1;
  }
  return { targetRowIdx, insertColIdx, nodeSize: nodeSize2 };
}
function getRowRanges(map3, rowIdx, totalColumnCount) {
  var startOffset = map3.getCellInfo(rowIdx, 0).offset;
  var _a = map3.getCellInfo(rowIdx, totalColumnCount - 1), offset = _a.offset, nodeSize2 = _a.nodeSize;
  return { from: startOffset, to: offset + nodeSize2 };
}
var Table = (
  /** @class */
  (function(_super) {
    __extends$1(Table2, _super);
    function Table2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Table2.prototype, "name", {
      get: function() {
        return "table";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Table2.prototype, "schema", {
      get: function() {
        return {
          content: "tableHead{1} tableBody{1}",
          group: "block",
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [createDOMInfoParsedRawHTML("table")],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["table", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Table2.prototype.addTable = function() {
      return function(payload) {
        if (payload === void 0) {
          payload = { rowCount: 2, columnCount: 1, data: [] };
        }
        return function(state, dispatch) {
          var rowCount = payload.rowCount, columnCount = payload.columnCount, data = payload.data;
          var schema = state.schema, selection = state.selection, tr = state.tr;
          var from2 = selection.from, to = selection.to, $from = selection.$from;
          var collapsed = from2 === to;
          if (collapsed && !isInTableNode($from)) {
            var _a = schema.nodes, tableHead2 = _a.tableHead, tableBody2 = _a.tableBody;
            var theadData = data === null || data === void 0 ? void 0 : data.slice(0, columnCount);
            var tbodyData = data === null || data === void 0 ? void 0 : data.slice(columnCount, data.length);
            var tableHeadRow = createTableHeadRow(columnCount, schema, theadData);
            var tableBodyRows = createTableBodyRows(rowCount - 1, columnCount, schema, tbodyData);
            var table2 = schema.nodes.table.create(null, [
              tableHead2.create(null, tableHeadRow),
              tableBody2.create(null, tableBodyRows)
            ]);
            dispatch(tr.replaceSelectionWith(table2));
            return true;
          }
          return false;
        };
      };
    };
    Table2.prototype.removeTable = function() {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, tr = state.tr;
          var map3 = TableOffsetMap.create(selection.$anchor);
          if (map3) {
            var tableStartOffset = map3.tableStartOffset, tableEndOffset = map3.tableEndOffset;
            var startOffset = tableStartOffset - 1;
            var cursorPos = createTextSelection(tr.delete(startOffset, tableEndOffset), startOffset);
            dispatch(tr.setSelection(cursorPos));
            return true;
          }
          return false;
        };
      };
    };
    Table2.prototype.addColumn = function(direction) {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, tr = state.tr, schema = state.schema;
          var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
          if (anchor && head) {
            var map3 = TableOffsetMap.create(anchor);
            var selectionInfo = map3.getRectOffsets(anchor, head);
            var targetColIdx = direction === "left" ? selectionInfo.startColIdx : selectionInfo.endColIdx + 1;
            var columnCount = getRowAndColumnCount(selectionInfo).columnCount;
            var totalRowCount = map3.totalRowCount;
            for (var rowIdx = 0; rowIdx < totalRowCount; rowIdx += 1) {
              var cells = createDummyCells(columnCount, rowIdx, schema);
              tr.insert(tr.mapping.map(map3.posAt(rowIdx, targetColIdx)), cells);
            }
            dispatch(tr);
            return true;
          }
          return false;
        };
      };
    };
    Table2.prototype.removeColumn = function() {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, tr = state.tr;
          var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
          if (anchor && head) {
            var map3 = TableOffsetMap.create(anchor);
            var selectionInfo = map3.getRectOffsets(anchor, head);
            var totalColumnCount = map3.totalColumnCount, totalRowCount = map3.totalRowCount;
            var columnCount = getRowAndColumnCount(selectionInfo).columnCount;
            var selectedAllColumn = columnCount === totalColumnCount;
            if (selectedAllColumn) {
              return false;
            }
            var startColIdx = selectionInfo.startColIdx, endColIdx = selectionInfo.endColIdx;
            var mapStart = tr.mapping.maps.length;
            for (var rowIdx = 0; rowIdx < totalRowCount; rowIdx += 1) {
              for (var colIdx = endColIdx; colIdx >= startColIdx; colIdx -= 1) {
                var _b = map3.getCellInfo(rowIdx, colIdx), offset = _b.offset, nodeSize2 = _b.nodeSize;
                var from2 = tr.mapping.slice(mapStart).map(offset);
                var to = from2 + nodeSize2;
                tr.delete(from2, to);
              }
            }
            dispatch(tr);
            return true;
          }
          return false;
        };
      };
    };
    Table2.prototype.addRow = function(direction) {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, schema = state.schema, tr = state.tr;
          var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
          if (anchor && head) {
            var map3 = TableOffsetMap.create(anchor);
            var totalColumnCount = map3.totalColumnCount;
            var selectionInfo = map3.getRectOffsets(anchor, head);
            var rowCount = getRowAndColumnCount(selectionInfo).rowCount;
            var _b = getTargetRowInfo(direction, map3, selectionInfo), targetRowIdx = _b.targetRowIdx, insertColIdx = _b.insertColIdx, nodeSize2 = _b.nodeSize;
            var selectedThead = targetRowIdx === 0;
            if (!selectedThead) {
              var rows = [];
              var from2 = tr.mapping.map(map3.posAt(targetRowIdx, insertColIdx)) + nodeSize2;
              var cells = [];
              for (var colIdx = 0; colIdx < totalColumnCount; colIdx += 1) {
                cells = cells.concat(createDummyCells(1, targetRowIdx, schema));
              }
              for (var i = 0; i < rowCount; i += 1) {
                rows.push(schema.nodes.tableRow.create(null, cells));
              }
              dispatch(tr.insert(from2, rows));
              return true;
            }
          }
          return false;
        };
      };
    };
    Table2.prototype.removeRow = function() {
      return function() {
        return function(state, dispatch) {
          var selection = state.selection, tr = state.tr;
          var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
          if (anchor && head) {
            var map3 = TableOffsetMap.create(anchor);
            var totalRowCount = map3.totalRowCount, totalColumnCount = map3.totalColumnCount;
            var selectionInfo = map3.getRectOffsets(anchor, head);
            var rowCount = getRowAndColumnCount(selectionInfo).rowCount;
            var startRowIdx = selectionInfo.startRowIdx, endRowIdx = selectionInfo.endRowIdx;
            var selectedThead = startRowIdx === 0;
            var selectedAllTbodyRow = rowCount === totalRowCount - 1;
            if (selectedAllTbodyRow || selectedThead) {
              return false;
            }
            for (var rowIdx = endRowIdx; rowIdx >= startRowIdx; rowIdx -= 1) {
              var _b = getRowRanges(map3, rowIdx, totalColumnCount), from2 = _b.from, to = _b.to;
              tr.delete(from2 - 1, to + 1);
            }
            dispatch(tr);
            return true;
          }
          return false;
        };
      };
    };
    Table2.prototype.alignColumn = function() {
      return function(payload) {
        if (payload === void 0) {
          payload = { align: "center" };
        }
        return function(state, dispatch) {
          var align = payload.align;
          var selection = state.selection, tr = state.tr;
          var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
          if (anchor && head) {
            var map3 = TableOffsetMap.create(anchor);
            var totalRowCount = map3.totalRowCount;
            var selectionInfo = map3.getRectOffsets(anchor, head);
            var startColIdx = selectionInfo.startColIdx, endColIdx = selectionInfo.endColIdx;
            for (var rowIdx = 0; rowIdx < totalRowCount; rowIdx += 1) {
              for (var colIdx = startColIdx; colIdx <= endColIdx; colIdx += 1) {
                if (!map3.extendedRowspan(rowIdx, colIdx) && !map3.extendedColspan(rowIdx, colIdx)) {
                  var _b = map3.getNodeAndPos(rowIdx, colIdx), node = _b.node, pos = _b.pos;
                  var attrs = setAttrs(node, { align });
                  tr.setNodeMarkup(pos, null, attrs);
                }
              }
            }
            dispatch(tr);
            return true;
          }
          return false;
        };
      };
    };
    Table2.prototype.moveToCell = function(direction) {
      return function(state, dispatch) {
        var selection = state.selection, tr = state.tr, schema = state.schema;
        var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
        if (anchor && head) {
          var map3 = TableOffsetMap.create(anchor);
          var cellIndex = map3.getCellIndex(anchor);
          var newTr = void 0;
          if (canBeOutOfTable(direction, map3, cellIndex)) {
            newTr = addParagraphAfterTable(tr, map3, schema);
          } else {
            newTr = moveToCell(direction, tr, cellIndex, map3);
          }
          if (newTr) {
            dispatch(newTr);
            return true;
          }
        }
        return false;
      };
    };
    Table2.prototype.moveInCell = function(direction) {
      var _this = this;
      return function(state, dispatch) {
        var selection = state.selection, tr = state.tr, doc3 = state.doc, schema = state.schema;
        var $from = selection.$from;
        var view = _this.context.view;
        if (!view.endOfTextblock(direction)) {
          return false;
        }
        var cell = findNodeBy($from, function(_a) {
          var type = _a.type;
          return type.name === "tableHeadCell" || type.name === "tableBodyCell";
        });
        if (cell) {
          var para2 = findNodeBy($from, function(_a) {
            var type = _a.type;
            return type.name === "paragraph";
          });
          var cellDepth = cell.depth;
          if (para2 && canMoveBetweenCells(direction, [cellDepth, para2.depth], $from, doc3)) {
            var anchor = getResolvedSelection(selection).anchor;
            var map3 = TableOffsetMap.create(anchor);
            var cellIndex = map3.getCellIndex(anchor);
            var newTr = void 0;
            if (canSelectTableNode(direction, map3, cellIndex)) {
              newTr = selectNode(tr, $from, cellDepth);
            } else if (canBeOutOfTable(direction, map3, cellIndex)) {
              if (direction === "up") {
                newTr = addParagraphBeforeTable(tr, map3, schema);
              } else if (direction === "down") {
                newTr = addParagraphAfterTable(tr, map3, schema);
              }
            } else {
              newTr = moveToCell(direction, tr, cellIndex, map3);
            }
            if (newTr) {
              dispatch(newTr);
              return true;
            }
          }
        }
        return false;
      };
    };
    Table2.prototype.deleteCells = function() {
      return function(state, dispatch) {
        var schema = state.schema, selection = state.selection, tr = state.tr;
        var _a = getResolvedSelection(selection), anchor = _a.anchor, head = _a.head;
        var textSelection = selection instanceof TextSelection;
        if (anchor && head && !textSelection) {
          var map3 = TableOffsetMap.create(anchor);
          var _b = map3.getRectOffsets(anchor, head), startRowIdx = _b.startRowIdx, startColIdx = _b.startColIdx, endRowIdx = _b.endRowIdx, endColIdx = _b.endColIdx;
          for (var rowIdx = startRowIdx; rowIdx <= endRowIdx; rowIdx += 1) {
            for (var colIdx = startColIdx; colIdx <= endColIdx; colIdx += 1) {
              if (!map3.extendedRowspan(rowIdx, colIdx) && !map3.extendedColspan(rowIdx, colIdx)) {
                var _c = map3.getNodeAndPos(rowIdx, colIdx), node = _c.node, pos = _c.pos;
                var cells = createDummyCells(1, rowIdx, schema, node.attrs);
                tr.replaceWith(tr.mapping.map(pos), tr.mapping.map(pos + node.nodeSize), cells);
              }
            }
          }
          dispatch(tr);
          return true;
        }
        return false;
      };
    };
    Table2.prototype.exitTable = function() {
      return function(state, dispatch) {
        var selection = state.selection, tr = state.tr, schema = state.schema;
        var $from = selection.$from;
        var cell = findNodeBy($from, function(_a) {
          var type = _a.type;
          return type.name === "tableHeadCell" || type.name === "tableBodyCell";
        });
        if (cell) {
          var para2 = findNodeBy($from, function(_a) {
            var type = _a.type;
            return type.name === "paragraph";
          });
          if (para2) {
            var anchor = getResolvedSelection(selection).anchor;
            var map3 = TableOffsetMap.create(anchor);
            dispatch(addParagraphAfterTable(tr, map3, schema, true));
            return true;
          }
        }
        return false;
      };
    };
    Table2.prototype.commands = function() {
      return {
        addTable: this.addTable(),
        removeTable: this.removeTable(),
        addColumnToLeft: this.addColumn(
          "left"
          /* LEFT */
        ),
        addColumnToRight: this.addColumn(
          "right"
          /* RIGHT */
        ),
        removeColumn: this.removeColumn(),
        addRowToUp: this.addRow(
          "up"
          /* UP */
        ),
        addRowToDown: this.addRow(
          "down"
          /* DOWN */
        ),
        removeRow: this.removeRow(),
        alignColumn: this.alignColumn()
      };
    };
    Table2.prototype.keymaps = function() {
      var deleteCellContent = this.deleteCells();
      return {
        Tab: this.moveToCell(
          "right"
          /* RIGHT */
        ),
        "Shift-Tab": this.moveToCell(
          "left"
          /* LEFT */
        ),
        ArrowUp: this.moveInCell(
          "up"
          /* UP */
        ),
        ArrowDown: this.moveInCell(
          "down"
          /* DOWN */
        ),
        ArrowLeft: this.moveInCell(
          "left"
          /* LEFT */
        ),
        ArrowRight: this.moveInCell(
          "right"
          /* RIGHT */
        ),
        Backspace: deleteCellContent,
        "Mod-Backspace": deleteCellContent,
        Delete: deleteCellContent,
        "Mod-Delete": deleteCellContent,
        "Mod-Enter": this.exitTable()
      };
    };
    return Table2;
  })(Node$2)
);
var TableHead = (
  /** @class */
  (function(_super) {
    __extends$1(TableHead2, _super);
    function TableHead2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TableHead2.prototype, "name", {
      get: function() {
        return "tableHead";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableHead2.prototype, "schema", {
      get: function() {
        return {
          content: "tableRow{1}",
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [createDOMInfoParsedRawHTML("thead")],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["thead", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TableHead2;
  })(Node$2)
);
var TableBody = (
  /** @class */
  (function(_super) {
    __extends$1(TableBody2, _super);
    function TableBody2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TableBody2.prototype, "name", {
      get: function() {
        return "tableBody";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableBody2.prototype, "schema", {
      get: function() {
        return {
          content: "tableRow+",
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [
            {
              tag: "tbody",
              getAttrs: function(dom) {
                var rows = dom.querySelectorAll("tr");
                var columns = rows[0].children.length;
                var rawHTML = dom.getAttribute("data-raw-html");
                if (!columns) {
                  return false;
                }
                return __assign$1({}, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["tbody", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TableBody2;
  })(Node$2)
);
var TableRow = (
  /** @class */
  (function(_super) {
    __extends$1(TableRow2, _super);
    function TableRow2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TableRow2.prototype, "name", {
      get: function() {
        return "tableRow";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableRow2.prototype, "schema", {
      get: function() {
        return {
          content: "(tableHeadCell | tableBodyCell)*",
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [
            {
              tag: "tr",
              getAttrs: function(dom) {
                var columns = dom.children.length;
                var rawHTML = dom.getAttribute("data-raw-html");
                if (!columns) {
                  return false;
                }
                return __assign$1({}, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["tr", getCustomAttrs(attrs), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TableRow2;
  })(Node$2)
);
var TableHeadCell = (
  /** @class */
  (function(_super) {
    __extends$1(TableHeadCell2, _super);
    function TableHeadCell2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TableHeadCell2.prototype, "name", {
      get: function() {
        return "tableHeadCell";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableHeadCell2.prototype, "schema", {
      get: function() {
        return {
          content: "paragraph+",
          attrs: __assign$1({ align: { default: null }, className: { default: null }, rawHTML: { default: null }, colspan: { default: null }, extended: { default: null } }, getDefaultCustomAttrs()),
          isolating: true,
          parseDOM: [createParsedCellDOM("th")],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            var cellAttrs = createCellAttrs(attrs);
            return ["th", __assign$1(__assign$1({}, cellAttrs), getCustomAttrs(attrs)), 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TableHeadCell2;
  })(Node$2)
);
var TableBodyCell = (
  /** @class */
  (function(_super) {
    __extends$1(TableBodyCell2, _super);
    function TableBodyCell2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(TableBodyCell2.prototype, "name", {
      get: function() {
        return "tableBodyCell";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TableBodyCell2.prototype, "schema", {
      get: function() {
        return {
          content: "(paragraph | bulletList | orderedList)+",
          attrs: {
            align: { default: null },
            className: { default: null },
            rawHTML: { default: null },
            colspan: { default: null },
            rowspan: { default: null },
            extended: { default: null }
          },
          isolating: true,
          parseDOM: [createParsedCellDOM("td")],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            var cellAttrs = createCellAttrs(attrs);
            return ["td", cellAttrs, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    return TableBodyCell2;
  })(Node$2)
);
var Image = (
  /** @class */
  (function(_super) {
    __extends$1(Image2, _super);
    function Image2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Image2.prototype, "name", {
      get: function() {
        return "image";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Image2.prototype, "schema", {
      get: function() {
        return {
          inline: true,
          attrs: __assign$1({ imageUrl: { default: "" }, altText: { default: null }, rawHTML: { default: null } }, getDefaultCustomAttrs()),
          group: "inline",
          selectable: false,
          parseDOM: [
            {
              tag: "img[src]",
              getAttrs: function(dom) {
                var sanitizedDOM = sanitizeHTML(dom, { RETURN_DOM_FRAGMENT: true }).firstChild;
                var imageUrl = sanitizedDOM.getAttribute("src") || "";
                var rawHTML = sanitizedDOM.getAttribute("data-raw-html");
                var altText = sanitizedDOM.getAttribute("alt");
                return __assign$1({
                  imageUrl,
                  altText
                }, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [
              attrs.rawHTML || "img",
              __assign$1(__assign$1({ src: escapeXml$1(attrs.imageUrl) }, attrs.altText && { alt: attrs.altText }), getCustomAttrs(attrs))
            ];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Image2.prototype.addImage = function() {
      return function(payload) {
        return function(_a, dispatch) {
          var schema = _a.schema, tr = _a.tr;
          var _b = payload, imageUrl = _b.imageUrl, altText = _b.altText;
          if (!imageUrl) {
            return false;
          }
          var node = schema.nodes.image.createAndFill(__assign$1({ imageUrl }, altText && { altText }));
          dispatch(tr.replaceSelectionWith(node).scrollIntoView());
          return true;
        };
      };
    };
    Image2.prototype.commands = function() {
      return {
        addImage: this.addImage()
      };
    };
    return Image2;
  })(Node$2)
);
var ROOT_BLOCK_DEPTH = 1;
var ThematicBreak = (
  /** @class */
  (function(_super) {
    __extends$1(ThematicBreak2, _super);
    function ThematicBreak2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ThematicBreak2.prototype, "name", {
      get: function() {
        return "thematicBreak";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(ThematicBreak2.prototype, "schema", {
      get: function() {
        return {
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          group: "block",
          parseDOM: [{ tag: "hr" }],
          selectable: false,
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["div", getCustomAttrs(attrs), [attrs.rawHTML || "hr"]];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    ThematicBreak2.prototype.hr = function() {
      var _this = this;
      return function() {
        return function(state, dispatch) {
          var _a;
          var _b = state.selection, $from = _b.$from, $to = _b.$to;
          if ($from === $to) {
            var doc3 = state.doc;
            var _c = state.schema.nodes, thematicBreak2 = _c.thematicBreak, paragraph2 = _c.paragraph;
            var nodes = [thematicBreak2.create()];
            var rootBlock = $from.node(ROOT_BLOCK_DEPTH);
            var lastBlock = doc3.child(doc3.childCount - 1) === rootBlock;
            var blockEnd = doc3.resolve($from.after(ROOT_BLOCK_DEPTH));
            var nextHr = ((_a = $from.nodeAfter) === null || _a === void 0 ? void 0 : _a.type.name) === _this.name;
            if (lastBlock || nextHr) {
              nodes.push(paragraph2.create());
            }
            dispatch(state.tr.insert(blockEnd.pos, nodes).scrollIntoView());
            return true;
          }
          return false;
        };
      };
    };
    ThematicBreak2.prototype.commands = function() {
      return { hr: this.hr() };
    };
    ThematicBreak2.prototype.keymaps = function() {
      var hrCommand = this.hr()();
      return {
        "Mod-l": hrCommand,
        "Mod-L": hrCommand
      };
    };
    return ThematicBreak2;
  })(Node$2)
);
var Strong = (
  /** @class */
  (function(_super) {
    __extends$1(Strong2, _super);
    function Strong2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Strong2.prototype, "name", {
      get: function() {
        return "strong";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Strong2.prototype, "schema", {
      get: function() {
        var parseDOM = ["b", "strong"].map(function(tag) {
          return {
            tag,
            getAttrs: function(dom) {
              var rawHTML = dom.getAttribute("data-raw-html");
              return __assign$1({}, rawHTML && { rawHTML });
            }
          };
        });
        return {
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM,
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [attrs.rawHTML || "strong", getCustomAttrs(attrs)];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Strong2.prototype.bold = function() {
      return function() {
        return function(state, dispatch) {
          return toggleMark(state.schema.marks.strong)(state, dispatch);
        };
      };
    };
    Strong2.prototype.commands = function() {
      return { bold: this.bold() };
    };
    Strong2.prototype.keymaps = function() {
      var boldCommand = this.bold()();
      return {
        "Mod-b": boldCommand,
        "Mod-B": boldCommand
      };
    };
    return Strong2;
  })(Mark2)
);
var Emph = (
  /** @class */
  (function(_super) {
    __extends$1(Emph2, _super);
    function Emph2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Emph2.prototype, "name", {
      get: function() {
        return "emph";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Emph2.prototype, "schema", {
      get: function() {
        var parseDOM = ["i", "em"].map(function(tag) {
          return {
            tag,
            getAttrs: function(dom) {
              var rawHTML = dom.getAttribute("data-raw-html");
              return __assign$1({}, rawHTML && { rawHTML });
            }
          };
        });
        return {
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM,
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [attrs.rawHTML || "em", getCustomAttrs(attrs)];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Emph2.prototype.italic = function() {
      return function() {
        return function(state, dispatch) {
          return toggleMark(state.schema.marks.emph)(state, dispatch);
        };
      };
    };
    Emph2.prototype.commands = function() {
      return { italic: this.italic() };
    };
    Emph2.prototype.keymaps = function() {
      var italicCommand = this.italic()();
      return {
        "Mod-i": italicCommand,
        "Mod-I": italicCommand
      };
    };
    return Emph2;
  })(Mark2)
);
var Strike = (
  /** @class */
  (function(_super) {
    __extends$1(Strike2, _super);
    function Strike2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Strike2.prototype, "name", {
      get: function() {
        return "strike";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Strike2.prototype, "schema", {
      get: function() {
        var parseDOM = ["s", "del"].map(function(tag) {
          return {
            tag,
            getAttrs: function(dom) {
              var rawHTML = dom.getAttribute("data-raw-html");
              return __assign$1({}, rawHTML && { rawHTML });
            }
          };
        });
        return {
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM,
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [attrs.rawHTML || "del", getCustomAttrs(attrs)];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Strike2.prototype.commands = function() {
      return function() {
        return function(state, dispatch) {
          return toggleMark(state.schema.marks.strike)(state, dispatch);
        };
      };
    };
    Strike2.prototype.keymaps = function() {
      var strikeCommand = this.commands()();
      return {
        "Mod-s": strikeCommand,
        "Mod-S": strikeCommand
      };
    };
    return Strike2;
  })(Mark2)
);
var Link = (
  /** @class */
  (function(_super) {
    __extends$1(Link2, _super);
    function Link2(linkAttributes) {
      var _this = _super.call(this) || this;
      _this.linkAttributes = linkAttributes;
      return _this;
    }
    Object.defineProperty(Link2.prototype, "name", {
      get: function() {
        return "link";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Link2.prototype, "schema", {
      get: function() {
        var _this = this;
        return {
          attrs: __assign$1({ linkUrl: { default: "" }, title: { default: null }, rawHTML: { default: null } }, getDefaultCustomAttrs()),
          inclusive: false,
          parseDOM: [
            {
              tag: "a[href]",
              getAttrs: function(dom) {
                var sanitizedDOM = sanitizeHTML(dom, { RETURN_DOM_FRAGMENT: true }).firstChild;
                var href = sanitizedDOM.getAttribute("href") || "";
                var title = sanitizedDOM.getAttribute("title") || "";
                var rawHTML = sanitizedDOM.getAttribute("data-raw-html");
                return __assign$1({ linkUrl: href, title }, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [
              attrs.rawHTML || "a",
              __assign$1(__assign$1({ href: escapeXml$1(attrs.linkUrl) }, _this.linkAttributes), getCustomAttrs(attrs))
            ];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Link2.prototype.addLink = function() {
      return function(payload) {
        return function(state, dispatch) {
          var _a = payload, linkUrl = _a.linkUrl, _b = _a.linkText, linkText = _b === void 0 ? "" : _b;
          var schema = state.schema, tr = state.tr, selection = state.selection;
          var empty3 = selection.empty, from2 = selection.from, to = selection.to;
          if (from2 && to && linkUrl) {
            var attrs = { linkUrl };
            var mark = schema.mark("link", attrs);
            if (empty3 && linkText) {
              var node = createTextNode$1(schema, linkText, mark);
              tr.replaceRangeWith(from2, to, node);
            } else {
              tr.addMark(from2, to, mark);
            }
            dispatch(tr.scrollIntoView());
            return true;
          }
          return false;
        };
      };
    };
    Link2.prototype.toggleLink = function() {
      return function(payload) {
        return function(state, dispatch) {
          return toggleMark(state.schema.marks.link, payload)(state, dispatch);
        };
      };
    };
    Link2.prototype.commands = function() {
      return {
        addLink: this.addLink(),
        toggleLink: this.toggleLink()
      };
    };
    return Link2;
  })(Mark2)
);
var Code = (
  /** @class */
  (function(_super) {
    __extends$1(Code2, _super);
    function Code2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Code2.prototype, "name", {
      get: function() {
        return "code";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Code2.prototype, "schema", {
      get: function() {
        return {
          attrs: __assign$1({ rawHTML: { default: null } }, getDefaultCustomAttrs()),
          parseDOM: [
            {
              tag: "code",
              getAttrs: function(dom) {
                var rawHTML = dom.getAttribute("data-raw-html");
                return __assign$1({}, rawHTML && { rawHTML });
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return [attrs.rawHTML || "code", getCustomAttrs(attrs)];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    Code2.prototype.commands = function() {
      return function() {
        return function(state, dispatch) {
          return toggleMark(state.schema.marks.code)(state, dispatch);
        };
      };
    };
    Code2.prototype.keymaps = function() {
      var codeCommand = this.commands()();
      return {
        "Shift-Mod-c": codeCommand,
        "Shift-Mod-C": codeCommand
      };
    };
    return Code2;
  })(Mark2)
);
var CustomBlock = (
  /** @class */
  (function(_super) {
    __extends$1(CustomBlock2, _super);
    function CustomBlock2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(CustomBlock2.prototype, "name", {
      get: function() {
        return "customBlock";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(CustomBlock2.prototype, "schema", {
      get: function() {
        return {
          content: "text*",
          group: "block",
          attrs: {
            info: { default: null }
          },
          atom: true,
          code: true,
          defining: true,
          parseDOM: [
            {
              tag: "div[data-custom-info]",
              getAttrs: function(dom) {
                var info = dom.getAttribute("data-custom-info");
                return { info };
              }
            }
          ],
          toDOM: function(_a) {
            var attrs = _a.attrs;
            return ["div", { "data-custom-info": attrs.info || null }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    CustomBlock2.prototype.commands = function() {
      return function(payload) {
        return function(state, dispatch) {
          return (payload === null || payload === void 0 ? void 0 : payload.info) ? setBlockType2(state.schema.nodes.customBlock, payload)(state, dispatch) : false;
        };
      };
    };
    return CustomBlock2;
  })(Node$2)
);
var FrontMatter = (
  /** @class */
  (function(_super) {
    __extends$1(FrontMatter2, _super);
    function FrontMatter2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(FrontMatter2.prototype, "name", {
      get: function() {
        return "frontMatter";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(FrontMatter2.prototype, "schema", {
      get: function() {
        return {
          content: "text*",
          group: "block",
          code: true,
          defining: true,
          parseDOM: [
            {
              preserveWhitespace: "full",
              tag: "div[data-front-matter]"
            }
          ],
          toDOM: function() {
            return ["div", { "data-front-matter": "true" }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    FrontMatter2.prototype.commands = function() {
      return function() {
        return function(state, dispatch, view) {
          var $from = state.selection.$from;
          if (view.endOfTextblock("down") && $from.node().type.name === "frontMatter") {
            return exitCode(state, dispatch);
          }
          return false;
        };
      };
    };
    FrontMatter2.prototype.keymaps = function() {
      return {
        Enter: this.commands()()
      };
    };
    return FrontMatter2;
  })(Node$2)
);
var HTMLComment = (
  /** @class */
  (function(_super) {
    __extends$1(HTMLComment2, _super);
    function HTMLComment2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(HTMLComment2.prototype, "name", {
      get: function() {
        return "htmlComment";
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(HTMLComment2.prototype, "schema", {
      get: function() {
        return {
          content: "text*",
          group: "block",
          code: true,
          defining: true,
          parseDOM: [{ preserveWhitespace: "full", tag: "div[data-html-comment]" }],
          toDOM: function() {
            return ["div", { "data-html-comment": "true" }, 0];
          }
        };
      },
      enumerable: false,
      configurable: true
    });
    HTMLComment2.prototype.commands = function() {
      return function() {
        return function(state, dispatch, view) {
          var $from = state.selection.$from;
          if (view.endOfTextblock("down") && $from.node().type.name === "htmlComment") {
            return exitCode(state, dispatch);
          }
          return false;
        };
      };
    };
    HTMLComment2.prototype.keymaps = function() {
      return {
        Enter: this.commands()()
      };
    };
    return HTMLComment2;
  })(Node$2)
);
function createSpecs(linkAttributes) {
  return new SpecManager([
    new Doc(),
    new Paragraph(),
    new Text(),
    new Heading(),
    new CodeBlock(),
    new BulletList(),
    new OrderedList(),
    new ListItem(),
    new BlockQuote(),
    new Table(),
    new TableHead(),
    new TableBody(),
    new TableRow(),
    new TableHeadCell(),
    new TableBodyCell(),
    new Image(),
    new ThematicBreak(),
    new Strong(),
    new Emph(),
    new Strike(),
    new Link(linkAttributes),
    new Code(),
    new CustomBlock(),
    new FrontMatter(),
    new Widget(),
    new HTMLComment()
  ]);
}
var CONTENTS_CLASS_NAME = cls("contents");
var WysiwygEditor = (
  /** @class */
  (function(_super) {
    __extends$1(WysiwygEditor2, _super);
    function WysiwygEditor2(eventEmitter, options) {
      var _this = _super.call(this, eventEmitter) || this;
      var toDOMAdaptor = options.toDOMAdaptor, _a = options.htmlSchemaMap, htmlSchemaMap = _a === void 0 ? {} : _a, _b = options.linkAttributes, linkAttributes = _b === void 0 ? {} : _b, _c = options.useCommandShortcut, useCommandShortcut = _c === void 0 ? true : _c, _d = options.wwPlugins, wwPlugins = _d === void 0 ? [] : _d, _e = options.wwNodeViews, wwNodeViews = _e === void 0 ? {} : _e;
      _this.editorType = "wysiwyg";
      _this.el.classList.add("ww-mode");
      _this.toDOMAdaptor = toDOMAdaptor;
      _this.linkAttributes = linkAttributes;
      _this.extraPlugins = wwPlugins;
      _this.pluginNodeViews = wwNodeViews;
      _this.specs = _this.createSpecs();
      _this.schema = _this.createSchema(htmlSchemaMap);
      _this.context = _this.createContext();
      _this.keymaps = _this.createKeymaps(useCommandShortcut);
      _this.view = _this.createView();
      _this.commands = _this.createCommands();
      _this.specs.setContext(__assign$1(__assign$1({}, _this.context), { view: _this.view }));
      _this.initEvent();
      return _this;
    }
    WysiwygEditor2.prototype.createSpecs = function() {
      return createSpecs(this.linkAttributes);
    };
    WysiwygEditor2.prototype.createContext = function() {
      return {
        schema: this.schema,
        eventEmitter: this.eventEmitter
      };
    };
    WysiwygEditor2.prototype.createSchema = function(htmlSchemaMap) {
      return new Schema({
        nodes: __assign$1(__assign$1({}, this.specs.nodes), htmlSchemaMap.nodes),
        marks: __assign$1(__assign$1({}, this.specs.marks), htmlSchemaMap.marks)
      });
    };
    WysiwygEditor2.prototype.createPlugins = function() {
      return __spreadArray$1([
        tableSelection(),
        tableContextMenu(this.eventEmitter),
        task(),
        toolbarStateHighlight(this.eventEmitter)
      ], this.createPluginProps()).concat(this.defaultPlugins);
    };
    WysiwygEditor2.prototype.createPluginNodeViews = function() {
      var _a = this, eventEmitter = _a.eventEmitter, pluginNodeViews = _a.pluginNodeViews;
      var pluginNodeViewMap = {};
      if (pluginNodeViews) {
        Object.keys(pluginNodeViews).forEach(function(key) {
          pluginNodeViewMap[key] = function(node, view, getPos) {
            return pluginNodeViews[key](node, view, getPos, eventEmitter);
          };
        });
      }
      return pluginNodeViewMap;
    };
    WysiwygEditor2.prototype.createView = function() {
      var _this = this;
      var _a = this, toDOMAdaptor = _a.toDOMAdaptor, eventEmitter = _a.eventEmitter;
      return new EditorView(this.el, {
        state: this.createState(),
        attributes: {
          class: CONTENTS_CLASS_NAME
        },
        nodeViews: __assign$1({
          customBlock: function(node, view, getPos) {
            return new CustomBlockView(node, view, getPos, toDOMAdaptor);
          },
          image: function(node, view, getPos) {
            return new ImageView(node, view, getPos, eventEmitter);
          },
          codeBlock: function(node, view, getPos) {
            return new CodeBlockView(node, view, getPos, eventEmitter);
          },
          widget: widgetNodeView
        }, this.createPluginNodeViews()),
        dispatchTransaction: function(tr) {
          var state = _this.view.state.applyTransaction(tr).state;
          _this.view.updateState(state);
          _this.emitChangeEvent(tr.scrollIntoView());
          _this.eventEmitter.emit("setFocusedNode", state.selection.$from.node(1));
        },
        transformPastedHTML: changePastedHTML,
        transformPasted: function(slice2) {
          return changePastedSlice(slice2, _this.schema, isInTableNode(_this.view.state.selection.$from));
        },
        handlePaste: function(view, _, slice2) {
          return pasteToTable(view, slice2);
        },
        handleKeyDown: function(_, ev) {
          _this.eventEmitter.emit("keydown", _this.editorType, ev);
          return false;
        },
        handleDOMEvents: {
          paste: function(_, ev) {
            var clipboardData = ev.clipboardData || window.clipboardData;
            var items = clipboardData === null || clipboardData === void 0 ? void 0 : clipboardData.items;
            if (items) {
              var containRtfItem = toArray_1(items).some(function(item2) {
                return item2.kind === "string" && item2.type === "text/rtf";
              });
              if (!containRtfItem) {
                var imageBlob = pasteImageOnly(items);
                if (imageBlob) {
                  ev.preventDefault();
                  emitImageBlobHook(_this.eventEmitter, imageBlob, ev.type);
                }
              }
            }
            return false;
          },
          keyup: function(_, ev) {
            _this.eventEmitter.emit("keyup", _this.editorType, ev);
            return false;
          },
          scroll: function() {
            _this.eventEmitter.emit("scroll", "editor");
            return true;
          }
        }
      });
    };
    WysiwygEditor2.prototype.createCommands = function() {
      return this.specs.commands(this.view, getWwCommands());
    };
    WysiwygEditor2.prototype.getHTML = function() {
      return removeProseMirrorHackNodes(this.view.dom.innerHTML);
    };
    WysiwygEditor2.prototype.getModel = function() {
      return this.view.state.doc;
    };
    WysiwygEditor2.prototype.getSelection = function() {
      var _a = this.view.state.selection, from2 = _a.from, to = _a.to;
      return [from2, to];
    };
    WysiwygEditor2.prototype.getSchema = function() {
      return this.view.state.schema;
    };
    WysiwygEditor2.prototype.replaceSelection = function(text2, start, end) {
      var _a = this.view.state, schema = _a.schema, tr = _a.tr;
      var lineTexts = text2.split("\n");
      var paras = lineTexts.map(function(lineText) {
        return createParagraph(schema, createNodesWithWidget(lineText, schema));
      });
      var slice2 = new Slice(Fragment.from(paras), 1, 1);
      var newTr = isNumber_1(start) && isNumber_1(end) ? tr.replaceRange(start, end, slice2) : tr.replaceSelection(slice2);
      this.view.dispatch(newTr);
      this.focus();
    };
    WysiwygEditor2.prototype.deleteSelection = function(start, end) {
      var tr = this.view.state.tr;
      var newTr = isNumber_1(start) && isNumber_1(end) ? tr.deleteRange(start, end) : tr.deleteSelection();
      this.view.dispatch(newTr.scrollIntoView());
    };
    WysiwygEditor2.prototype.getSelectedText = function(start, end) {
      var _a = this.view.state, doc3 = _a.doc, selection = _a.selection;
      var from2 = selection.from, to = selection.to;
      if (isNumber_1(start) && isNumber_1(end)) {
        from2 = start;
        to = end;
      }
      return doc3.textBetween(from2, to, "\n");
    };
    WysiwygEditor2.prototype.setModel = function(newDoc, cursorToEnd) {
      if (cursorToEnd === void 0) {
        cursorToEnd = false;
      }
      var _a = this.view.state, tr = _a.tr, doc3 = _a.doc;
      this.view.dispatch(tr.replaceWith(0, doc3.content.size, newDoc));
      if (cursorToEnd) {
        this.moveCursorToEnd(true);
      }
    };
    WysiwygEditor2.prototype.setSelection = function(start, end) {
      if (end === void 0) {
        end = start;
      }
      var tr = this.view.state.tr;
      var selection = createTextSelection(tr, start, end);
      this.view.dispatch(tr.setSelection(selection).scrollIntoView());
    };
    WysiwygEditor2.prototype.addWidget = function(node, style, pos) {
      var _a = this.view, dispatch = _a.dispatch, state = _a.state;
      dispatch(state.tr.setMeta("widget", { pos: pos !== null && pos !== void 0 ? pos : state.selection.to, node, style }));
    };
    WysiwygEditor2.prototype.replaceWithWidget = function(start, end, text2) {
      var _a = this.view.state, tr = _a.tr, schema = _a.schema;
      var nodes = createNodesWithWidget(text2, schema);
      this.view.dispatch(tr.replaceWith(start, end, nodes));
    };
    WysiwygEditor2.prototype.getRangeInfoOfNode = function(pos) {
      var _a = this.view.state, doc3 = _a.doc, selection = _a.selection;
      var $pos = pos ? doc3.resolve(pos) : selection.$from;
      var marks = $pos.marks();
      var node = $pos.node();
      var start = $pos.start();
      var end = $pos.end();
      var type = node.type.name;
      if (marks.length || type === "paragraph") {
        var mark_1 = marks[marks.length - 1];
        var maybeHasMark_1 = function(nodeMarks) {
          return nodeMarks.length ? includes(nodeMarks, mark_1) : true;
        };
        type = mark_1 ? mark_1.type.name : "text";
        node.forEach(function(child, offset) {
          var isText = child.isText, nodeSize2 = child.nodeSize, nodeMarks = child.marks;
          var startOffset = $pos.pos - start;
          if (isText && offset <= startOffset && offset + nodeSize2 >= startOffset && maybeHasMark_1(nodeMarks)) {
            start = start + offset;
            end = start + nodeSize2;
          }
        });
      }
      return { range: [start, end], type };
    };
    return WysiwygEditor2;
  })(EditorBase)
);
var isUndefined = isUndefined_1;
var isNull = isNull_1;
function isExisty$1(param) {
  return !isUndefined(param) && !isNull(param);
}
var isExisty_1 = isExisty$1;
var isExisty = isExisty_1;
function isTruthy$1(obj) {
  return isExisty(obj) && obj !== false;
}
var isTruthy_1 = isTruthy$1;
var isTruthy = isTruthy_1;
function isFalsy(obj) {
  return !isTruthy(obj);
}
var isFalsy_1 = isFalsy;
var eventTypeList = [
  "afterPreviewRender",
  "updatePreview",
  "changeMode",
  "needChangeMode",
  "command",
  "changePreviewStyle",
  "changePreviewTabPreview",
  "changePreviewTabWrite",
  "scroll",
  "contextmenu",
  "show",
  "hide",
  "changeLanguage",
  "changeToolbarState",
  "toggleScrollSync",
  "mixinTableOffsetMapPrototype",
  "setFocusedNode",
  "removePopupWidget",
  "query",
  // provide event for user
  "openPopup",
  "closePopup",
  "addImageBlobHook",
  "beforePreviewRender",
  "beforeConvertWysiwygToMarkdown",
  "load",
  "loadUI",
  "change",
  "caretChange",
  "destroy",
  "focus",
  "blur",
  "keydown",
  "keyup"
];
var EventEmitter = (
  /** @class */
  (function() {
    function EventEmitter2() {
      var _this = this;
      this.events = new Map$1();
      this.eventTypes = eventTypeList.reduce(function(types, type) {
        return __assign$1(__assign$1({}, types), { type });
      }, {});
      this.hold = false;
      eventTypeList.forEach(function(eventType) {
        _this.addEventType(eventType);
      });
    }
    EventEmitter2.prototype.listen = function(type, handler) {
      var typeInfo = this.getTypeInfo(type);
      var eventHandlers = this.events.get(typeInfo.type) || [];
      if (!this.hasEventType(typeInfo.type)) {
        throw new Error("There is no event type " + typeInfo.type);
      }
      if (typeInfo.namespace) {
        handler.namespace = typeInfo.namespace;
      }
      eventHandlers.push(handler);
      this.events.set(typeInfo.type, eventHandlers);
    };
    EventEmitter2.prototype.emit = function(type) {
      var args = [];
      for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
      }
      var typeInfo = this.getTypeInfo(type);
      var eventHandlers = this.events.get(typeInfo.type);
      var results = [];
      if (!this.hold && eventHandlers) {
        eventHandlers.forEach(function(handler) {
          var result = handler.apply(void 0, args);
          if (!isUndefined_1(result)) {
            results.push(result);
          }
        });
      }
      return results;
    };
    EventEmitter2.prototype.emitReduce = function(type, source) {
      var args = [];
      for (var _i = 2; _i < arguments.length; _i++) {
        args[_i - 2] = arguments[_i];
      }
      var eventHandlers = this.events.get(type);
      if (!this.hold && eventHandlers) {
        eventHandlers.forEach(function(handler) {
          var result = handler.apply(void 0, __spreadArray$1([source], args));
          if (!isFalsy_1(result)) {
            source = result;
          }
        });
      }
      return source;
    };
    EventEmitter2.prototype.getTypeInfo = function(type) {
      var splited = type.split(".");
      return {
        type: splited[0],
        namespace: splited[1]
      };
    };
    EventEmitter2.prototype.hasEventType = function(type) {
      return !isUndefined_1(this.eventTypes[this.getTypeInfo(type).type]);
    };
    EventEmitter2.prototype.addEventType = function(type) {
      if (this.hasEventType(type)) {
        throw new Error("There is already have event type " + type);
      }
      this.eventTypes[type] = type;
    };
    EventEmitter2.prototype.removeEventHandler = function(eventType, handler) {
      var _this = this;
      var _a = this.getTypeInfo(eventType), type = _a.type, namespace = _a.namespace;
      if (type && handler) {
        this.removeEventHandlerWithHandler(type, handler);
      } else if (type && !namespace) {
        this.events.delete(type);
      } else if (!type && namespace) {
        this.events.forEach(function(_, evtType) {
          _this.removeEventHandlerWithTypeInfo(evtType, namespace);
        });
      } else if (type && namespace) {
        this.removeEventHandlerWithTypeInfo(type, namespace);
      }
    };
    EventEmitter2.prototype.removeEventHandlerWithHandler = function(type, handler) {
      var eventHandlers = this.events.get(type);
      if (eventHandlers) {
        var handlerIndex = eventHandlers.indexOf(handler);
        if (eventHandlers.indexOf(handler) >= 0) {
          eventHandlers.splice(handlerIndex, 1);
        }
      }
    };
    EventEmitter2.prototype.removeEventHandlerWithTypeInfo = function(type, namespace) {
      var handlersToSurvive = [];
      var eventHandlers = this.events.get(type);
      if (!eventHandlers) {
        return;
      }
      eventHandlers.map(function(handler) {
        if (handler.namespace !== namespace) {
          handlersToSurvive.push(handler);
        }
        return null;
      });
      this.events.set(type, handlersToSurvive);
    };
    EventEmitter2.prototype.getEvents = function() {
      return this.events;
    };
    EventEmitter2.prototype.holdEventInvoke = function(fn) {
      this.hold = true;
      fn();
      this.hold = false;
    };
    return EventEmitter2;
  })()
);
var CommandManager = (
  /** @class */
  (function() {
    function CommandManager2(eventEmitter, mdCommands, wwCommands, getEditorType) {
      this.eventEmitter = eventEmitter;
      this.mdCommands = mdCommands;
      this.wwCommands = wwCommands;
      this.getEditorType = getEditorType;
      this.initEvent();
    }
    CommandManager2.prototype.initEvent = function() {
      var _this = this;
      this.eventEmitter.listen("command", function(command, payload) {
        _this.exec(command, payload);
      });
    };
    CommandManager2.prototype.addCommand = function(type, name, command) {
      if (type === "markdown") {
        this.mdCommands[name] = command;
      } else {
        this.wwCommands[name] = command;
      }
    };
    CommandManager2.prototype.deleteCommand = function(type, name) {
      if (type === "markdown") {
        delete this.mdCommands[name];
      } else {
        delete this.wwCommands[name];
      }
    };
    CommandManager2.prototype.exec = function(name, payload) {
      var type = this.getEditorType();
      if (type === "markdown") {
        this.mdCommands[name](payload);
      } else {
        this.wwCommands[name](payload);
      }
    };
    return CommandManager2;
  })()
);
function getTextWithoutTrailingNewline(text2) {
  return text2[text2.length - 1] === "\n" ? text2.slice(0, text2.length - 1) : text2;
}
function isCustomHTMLInlineNode(_a, node) {
  var schema = _a.schema;
  var html2 = node.literal;
  var matched = html2.match(reHTMLTag);
  if (matched) {
    var openTagName = matched[1], closeTagName = matched[3];
    var typeName = (openTagName || closeTagName).toLowerCase();
    return node.type === "htmlInline" && !!(schema.marks[typeName] || schema.nodes[typeName]);
  }
  return false;
}
function isInlineNode(_a) {
  var type = _a.type;
  return includes(["text", "strong", "emph", "strike", "image", "link", "code"], type);
}
function isSoftbreak(mdNode) {
  return (mdNode === null || mdNode === void 0 ? void 0 : mdNode.type) === "softbreak";
}
function isListNode(_a) {
  var type = _a.type, literal = _a.literal;
  var matched = type === "htmlInline" && literal.match(reHTMLTag);
  if (matched) {
    var openTagName = matched[1], closeTagName = matched[3];
    var tagName = openTagName || closeTagName;
    if (tagName) {
      return includes(["ul", "ol", "li"], tagName.toLowerCase());
    }
  }
  return false;
}
function getListItemAttrs(_a) {
  var literal = _a.literal;
  var task2 = /data-task/.test(literal);
  var checked = /data-task-checked/.test(literal);
  return { task: task2, checked };
}
function getMatchedAttributeValue(rawHTML) {
  var attrNames = [];
  for (var _i = 1; _i < arguments.length; _i++) {
    attrNames[_i - 1] = arguments[_i];
  }
  var wrapper = document.createElement("div");
  wrapper.innerHTML = sanitizeHTML(rawHTML);
  var el2 = wrapper.firstChild;
  return attrNames.map(function(attrName) {
    return el2.getAttribute(attrName) || "";
  });
}
function createConvertors(convertors2) {
  var convertorMap = {};
  Object.keys(convertors2).forEach(function(key) {
    var tagNames = key.split(", ");
    tagNames.forEach(function(tagName) {
      var name = tagName.toLowerCase();
      convertorMap[name] = convertors2[key];
    });
  });
  return convertorMap;
}
var convertors = {
  "b, strong": function(state, _, openTagName) {
    var strong = state.schema.marks.strong;
    if (openTagName) {
      state.openMark(strong.create({ rawHTML: openTagName }));
    } else {
      state.closeMark(strong);
    }
  },
  "i, em": function(state, _, openTagName) {
    var emph = state.schema.marks.emph;
    if (openTagName) {
      state.openMark(emph.create({ rawHTML: openTagName }));
    } else {
      state.closeMark(emph);
    }
  },
  "s, del": function(state, _, openTagName) {
    var strike = state.schema.marks.strike;
    if (openTagName) {
      state.openMark(strike.create({ rawHTML: openTagName }));
    } else {
      state.closeMark(strike);
    }
  },
  code: function(state, _, openTagName) {
    var code2 = state.schema.marks.code;
    if (openTagName) {
      state.openMark(code2.create({ rawHTML: openTagName }));
    } else {
      state.closeMark(code2);
    }
  },
  a: function(state, node, openTagName) {
    var tag = node.literal;
    var link2 = state.schema.marks.link;
    if (openTagName) {
      var linkUrl = getMatchedAttributeValue(tag, "href")[0];
      state.openMark(link2.create({
        linkUrl,
        rawHTML: openTagName
      }));
    } else {
      state.closeMark(link2);
    }
  },
  img: function(state, node, openTagName) {
    var tag = node.literal;
    if (openTagName) {
      var _a = getMatchedAttributeValue(tag, "src", "alt"), imageUrl = _a[0], altText = _a[1];
      var image2 = state.schema.nodes.image;
      state.addNode(image2, __assign$1({ rawHTML: openTagName, imageUrl }, altText && { altText }));
    }
  },
  hr: function(state, _, openTagName) {
    state.addNode(state.schema.nodes.thematicBreak, { rawHTML: openTagName });
  },
  br: function(state, node) {
    var paragraph2 = state.schema.nodes.paragraph;
    var parent = node.parent, prev = node.prev, next = node.next;
    if ((parent === null || parent === void 0 ? void 0 : parent.type) === "paragraph") {
      if (isSoftbreak(prev)) {
        state.openNode(paragraph2);
      }
      if (isSoftbreak(next)) {
        state.closeNode();
      } else if (next) {
        state.closeNode();
        state.openNode(paragraph2);
      }
    } else if ((parent === null || parent === void 0 ? void 0 : parent.type) === "tableCell") {
      if (prev && (isInlineNode(prev) || isCustomHTMLInlineNode(state, prev))) {
        state.closeNode();
      }
      if (next && (isInlineNode(next) || isCustomHTMLInlineNode(state, next))) {
        state.openNode(paragraph2);
      }
    }
  },
  pre: function(state, node, openTagName) {
    var _a, _b;
    var container = document.createElement("div");
    container.innerHTML = node.literal;
    var literal = (_b = (_a = container.firstChild) === null || _a === void 0 ? void 0 : _a.firstChild) === null || _b === void 0 ? void 0 : _b.textContent;
    state.openNode(state.schema.nodes.codeBlock, { rawHTML: openTagName });
    state.addText(getTextWithoutTrailingNewline(literal));
    state.closeNode();
  },
  "ul, ol": function(state, node, openTagName) {
    if (node.parent.type === "tableCell") {
      var _a = state.schema.nodes, bulletList = _a.bulletList, orderedList = _a.orderedList, paragraph2 = _a.paragraph;
      var list2 = openTagName === "ul" ? bulletList : orderedList;
      if (openTagName) {
        if (node.prev && !isListNode(node.prev)) {
          state.closeNode();
        }
        state.openNode(list2, { rawHTML: openTagName });
      } else {
        state.closeNode();
        if (node.next && !isListNode(node.next)) {
          state.openNode(paragraph2);
        }
      }
    }
  },
  li: function(state, node, openTagName) {
    var _a;
    if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.type) === "tableCell") {
      var _b = state.schema.nodes, listItem2 = _b.listItem, paragraph2 = _b.paragraph;
      if (openTagName) {
        var attrs = getListItemAttrs(node);
        if (node.prev && !isListNode(node.prev)) {
          state.closeNode();
        }
        state.openNode(listItem2, __assign$1({ rawHTML: openTagName }, attrs));
        if (node.next && !isListNode(node.next)) {
          state.openNode(paragraph2);
        }
      } else {
        if (node.prev && !isListNode(node.prev)) {
          state.closeNode();
        }
        state.closeNode();
      }
    }
  }
};
var htmlToWwConvertors = createConvertors(convertors);
function isBRTag(node) {
  return node.type === "htmlInline" && reBR.test(node.literal);
}
function addRawHTMLAttributeToDOM(parent) {
  toArray_1(parent.childNodes).forEach(function(child) {
    if (isElemNode(child)) {
      var openTagName = child.nodeName.toLowerCase();
      child.setAttribute("data-raw-html", openTagName);
      if (child.childNodes) {
        addRawHTMLAttributeToDOM(child);
      }
    }
  });
}
var toWwConvertors = {
  text: function(state, node) {
    state.addText(node.literal || "");
  },
  paragraph: function(state, node, _a, customAttrs) {
    var _b;
    var entering = _a.entering;
    if (entering) {
      var paragraph2 = state.schema.nodes.paragraph;
      if (((_b = node.prev) === null || _b === void 0 ? void 0 : _b.type) === "paragraph") {
        state.openNode(paragraph2, customAttrs);
        state.closeNode();
      }
      state.openNode(paragraph2, customAttrs);
    } else {
      state.closeNode();
    }
  },
  heading: function(state, node, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      var _b = node, level = _b.level, headingType = _b.headingType;
      state.openNode(state.schema.nodes.heading, __assign$1({ level, headingType }, customAttrs));
    } else {
      state.closeNode();
    }
  },
  codeBlock: function(state, node, customAttrs) {
    var codeBlock2 = state.schema.nodes.codeBlock;
    var _a = node, info = _a.info, literal = _a.literal;
    state.openNode(codeBlock2, __assign$1({ language: info }, customAttrs));
    state.addText(getTextWithoutTrailingNewline(literal || ""));
    state.closeNode();
  },
  list: function(state, node, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      var _b = state.schema.nodes, bulletList = _b.bulletList, orderedList = _b.orderedList;
      var _c = node.listData, type = _c.type, start = _c.start;
      if (type === "bullet") {
        state.openNode(bulletList, customAttrs);
      } else {
        state.openNode(orderedList, __assign$1({ order: start }, customAttrs));
      }
    } else {
      state.closeNode();
    }
  },
  item: function(state, node, _a, customAttrs) {
    var entering = _a.entering;
    var listItem2 = state.schema.nodes.listItem;
    var _b = node.listData, task2 = _b.task, checked = _b.checked;
    if (entering) {
      var attrs = __assign$1(__assign$1(__assign$1({}, task2 && { task: task2 }), checked && { checked }), customAttrs);
      state.openNode(listItem2, attrs);
    } else {
      state.closeNode();
    }
  },
  blockQuote: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      state.openNode(state.schema.nodes.blockQuote, customAttrs);
    } else {
      state.closeNode();
    }
  },
  image: function(state, node, _a, customAttrs) {
    var entering = _a.entering, skipChildren = _a.skipChildren;
    var image2 = state.schema.nodes.image;
    var _b = node, destination = _b.destination, firstChild = _b.firstChild;
    if (entering && skipChildren) {
      skipChildren();
    }
    state.addNode(image2, __assign$1(__assign$1({ imageUrl: destination }, firstChild && { altText: firstChild.literal }), customAttrs));
  },
  thematicBreak: function(state, node, _, customAttrs) {
    state.addNode(state.schema.nodes.thematicBreak, customAttrs);
  },
  strong: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    var strong = state.schema.marks.strong;
    if (entering) {
      state.openMark(strong.create(customAttrs));
    } else {
      state.closeMark(strong);
    }
  },
  emph: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    var emph = state.schema.marks.emph;
    if (entering) {
      state.openMark(emph.create(customAttrs));
    } else {
      state.closeMark(emph);
    }
  },
  link: function(state, node, _a, customAttrs) {
    var entering = _a.entering;
    var link2 = state.schema.marks.link;
    var _b = node, destination = _b.destination, title = _b.title;
    if (entering) {
      var attrs = __assign$1({ linkUrl: destination, title }, customAttrs);
      state.openMark(link2.create(attrs));
    } else {
      state.closeMark(link2);
    }
  },
  softbreak: function(state, node) {
    if (node.parent.type === "paragraph") {
      var prev = node.prev, next = node.next;
      if (prev && !isBRTag(prev)) {
        state.closeNode();
      }
      if (next && !isBRTag(next)) {
        state.openNode(state.schema.nodes.paragraph);
      }
    }
  },
  // GFM specifications node
  table: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      state.openNode(state.schema.nodes.table, customAttrs);
    } else {
      state.closeNode();
    }
  },
  tableHead: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      state.openNode(state.schema.nodes.tableHead, customAttrs);
    } else {
      state.closeNode();
    }
  },
  tableBody: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      state.openNode(state.schema.nodes.tableBody, customAttrs);
    } else {
      state.closeNode();
    }
  },
  tableRow: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    if (entering) {
      state.openNode(state.schema.nodes.tableRow, customAttrs);
    } else {
      state.closeNode();
    }
  },
  tableCell: function(state, node, _a) {
    var entering = _a.entering;
    if (!node.ignored) {
      var hasParaNode = function(childNode) {
        return childNode && (isInlineNode(childNode) || isCustomHTMLInlineNode(state, childNode));
      };
      if (entering) {
        var _b = state.schema.nodes, tableHeadCell = _b.tableHeadCell, tableBodyCell = _b.tableBodyCell, paragraph2 = _b.paragraph;
        var tablePart = node.parent.parent;
        var cell = tablePart.type === "tableHead" ? tableHeadCell : tableBodyCell;
        var table2 = tablePart.parent;
        var align = (table2.columns[node.startIdx] || {}).align;
        var attrs = __assign$1({}, node.attrs);
        if (align) {
          attrs.align = align;
        }
        state.openNode(cell, attrs);
        if (hasParaNode(node.firstChild)) {
          state.openNode(paragraph2);
        }
      } else {
        if (hasParaNode(node.lastChild)) {
          state.closeNode();
        }
        state.closeNode();
      }
    }
  },
  strike: function(state, _, _a, customAttrs) {
    var entering = _a.entering;
    var strike = state.schema.marks.strike;
    if (entering) {
      state.openMark(strike.create(customAttrs));
    } else {
      state.closeMark(strike);
    }
  },
  code: function(state, node, _, customAttrs) {
    var code2 = state.schema.marks.code;
    state.openMark(code2.create(customAttrs));
    state.addText(getTextWithoutTrailingNewline(node.literal || ""));
    state.closeMark(code2);
  },
  customBlock: function(state, node) {
    var _a = state.schema.nodes, customBlock2 = _a.customBlock, paragraph2 = _a.paragraph;
    var _b = node, info = _b.info, literal = _b.literal;
    state.openNode(customBlock2, { info });
    state.addText(getTextWithoutTrailingNewline(literal || ""));
    state.closeNode();
    if (!node.next) {
      state.openNode(paragraph2);
      state.closeNode();
    }
  },
  frontMatter: function(state, node) {
    state.openNode(state.schema.nodes.frontMatter);
    state.addText(node.literal);
    state.closeNode();
  },
  htmlInline: function(state, node) {
    var html2 = node.literal;
    var matched = html2.match(reHTMLTag);
    var openTagName = matched[1], closeTagName = matched[3];
    var typeName = (openTagName || closeTagName).toLowerCase();
    var markType = state.schema.marks[typeName];
    var sanitizedHTML = sanitizeHTML(html2);
    if (markType === null || markType === void 0 ? void 0 : markType.spec.attrs.htmlInline) {
      if (openTagName) {
        var htmlAttrs = getHTMLAttrsByHTMLString(sanitizedHTML);
        state.openMark(markType.create({ htmlAttrs }));
      } else {
        state.closeMark(markType);
      }
    } else {
      var htmlToWwConvertor = htmlToWwConvertors[typeName];
      if (htmlToWwConvertor) {
        htmlToWwConvertor(state, node, openTagName);
      }
    }
  },
  htmlBlock: function(state, node) {
    var html2 = node.literal;
    var container = document.createElement("div");
    var isHTMLComment = reHTMLComment.test(html2);
    if (isHTMLComment) {
      state.openNode(state.schema.nodes.htmlComment);
      state.addText(node.literal);
      state.closeNode();
    } else {
      var matched = html2.match(reHTMLTag);
      var openTagName = matched[1], closeTagName = matched[3];
      var typeName = (openTagName || closeTagName).toLowerCase();
      var nodeType = state.schema.nodes[typeName];
      var sanitizedHTML = sanitizeHTML(html2);
      if (nodeType === null || nodeType === void 0 ? void 0 : nodeType.spec.attrs.htmlBlock) {
        var htmlAttrs = getHTMLAttrsByHTMLString(sanitizedHTML);
        var childrenHTML = getChildrenHTML(node, typeName);
        state.addNode(nodeType, { htmlAttrs, childrenHTML });
      } else {
        container.innerHTML = sanitizedHTML;
        addRawHTMLAttributeToDOM(container);
        state.convertByDOMParser(container);
      }
    }
  },
  customInline: function(state, node, _a) {
    var entering = _a.entering, skipChildren = _a.skipChildren;
    var _b = node, info = _b.info, firstChild = _b.firstChild;
    var schema = state.schema;
    if (info.indexOf("widget") !== -1 && entering) {
      var content = getWidgetContent(node);
      skipChildren();
      state.addNode(schema.nodes.widget, { info }, [
        schema.text(createWidgetContent(info, content))
      ]);
    } else {
      var text2 = "$$";
      if (entering) {
        text2 += firstChild ? info + " " : info;
      }
      state.addText(text2);
    }
  }
};
function createWwConvertors(customConvertors) {
  var customConvertorTypes = Object.keys(customConvertors);
  var convertors2 = __assign$1({}, toWwConvertors);
  var renderer = new Renderer({
    gfm: true,
    nodeId: true,
    convertors: customConvertors
  });
  var orgConvertors = renderer.getConvertors();
  customConvertorTypes.forEach(function(type) {
    var wwConvertor = toWwConvertors[type];
    if (wwConvertor && !includes(["htmlBlock", "htmlInline"], type)) {
      convertors2[type] = function(state, node, context) {
        context.origin = function() {
          return orgConvertors[type](node, context, orgConvertors);
        };
        var tokens = customConvertors[type](node, context);
        var attrs;
        if (tokens) {
          var _a = Array.isArray(tokens) ? tokens[0] : tokens, htmlAttrs = _a.attributes, classNames = _a.classNames;
          attrs = { htmlAttrs, classNames };
        }
        wwConvertor(state, node, context, attrs);
      };
    }
  });
  return convertors2;
}
function mergeMarkText(a, b) {
  if (a.isText && b.isText && Mark.sameSet(a.marks, b.marks)) {
    return a.withText(a.text + b.text);
  }
  return false;
}
var ToWwConvertorState = (
  /** @class */
  (function() {
    function ToWwConvertorState2(schema, convertors2) {
      this.schema = schema;
      this.convertors = convertors2;
      this.stack = [{ type: this.schema.topNodeType, attrs: null, content: [] }];
      this.marks = Mark.none;
    }
    ToWwConvertorState2.prototype.top = function() {
      return last$1(this.stack);
    };
    ToWwConvertorState2.prototype.push = function(node) {
      if (this.stack.length) {
        this.top().content.push(node);
      }
    };
    ToWwConvertorState2.prototype.addText = function(text2) {
      if (text2) {
        var nodes = this.top().content;
        var lastNode = last$1(nodes);
        var node = this.schema.text(text2, this.marks);
        var merged = lastNode && mergeMarkText(lastNode, node);
        if (merged) {
          nodes[nodes.length - 1] = merged;
        } else {
          nodes.push(node);
        }
      }
    };
    ToWwConvertorState2.prototype.openMark = function(mark) {
      this.marks = mark.addToSet(this.marks);
    };
    ToWwConvertorState2.prototype.closeMark = function(mark) {
      this.marks = mark.removeFromSet(this.marks);
    };
    ToWwConvertorState2.prototype.addNode = function(type, attrs, content) {
      var node = type.createAndFill(attrs, content, this.marks);
      if (node) {
        this.push(node);
        return node;
      }
      return null;
    };
    ToWwConvertorState2.prototype.openNode = function(type, attrs) {
      this.stack.push({ type, attrs, content: [] });
    };
    ToWwConvertorState2.prototype.closeNode = function() {
      if (this.marks.length) {
        this.marks = Mark.none;
      }
      var _a = this.stack.pop(), type = _a.type, attrs = _a.attrs, content = _a.content;
      return this.addNode(type, attrs, content);
    };
    ToWwConvertorState2.prototype.convertByDOMParser = function(root) {
      var _this = this;
      var doc3 = DOMParser.fromSchema(this.schema).parse(root);
      doc3.content.forEach(function(node) {
        return _this.push(node);
      });
    };
    ToWwConvertorState2.prototype.closeUnmatchedHTMLInline = function(node, entering) {
      var _a;
      if (!entering && node.type !== "htmlInline") {
        var length_1 = this.stack.length - 1;
        for (var i = length_1; i >= 0; i -= 1) {
          var nodeInfo = this.stack[i];
          if ((_a = nodeInfo.attrs) === null || _a === void 0 ? void 0 : _a.rawHTML) {
            if (nodeInfo.content.length) {
              this.closeNode();
            } else {
              this.stack.pop();
            }
          } else {
            break;
          }
        }
      }
    };
    ToWwConvertorState2.prototype.convert = function(mdNode, infoForPosSync) {
      var walker = mdNode.walker();
      var event = walker.next();
      var _loop_1 = function() {
        var node = event.node, entering = event.entering;
        var convertor = this_1.convertors[node.type];
        var skipped = false;
        if (convertor) {
          var context = {
            entering,
            leaf: !isContainer$2(node),
            getChildrenText: getChildrenText$1,
            options: { gfm: true, nodeId: false, tagFilter: false, softbreak: "\n" },
            skipChildren: function() {
              skipped = true;
            }
          };
          this_1.closeUnmatchedHTMLInline(node, entering);
          convertor(this_1, node, context);
          if ((infoForPosSync === null || infoForPosSync === void 0 ? void 0 : infoForPosSync.node) === node) {
            var pos = this_1.stack.reduce(function(nodeSize2, stackItem) {
              return nodeSize2 + stackItem.content.reduce(function(contentSize, pmNode) {
                return contentSize + pmNode.nodeSize;
              }, 0);
            }, 0) + 1;
            infoForPosSync.setMappedPos(pos);
          }
        }
        if (skipped) {
          walker.resumeAt(node, false);
          walker.next();
        }
        event = walker.next();
      };
      var this_1 = this;
      while (event) {
        _loop_1();
      }
    };
    ToWwConvertorState2.prototype.convertNode = function(mdNode, infoForPosSync) {
      this.convert(mdNode, infoForPosSync);
      if (this.stack.length) {
        return this.closeNode();
      }
      return null;
    };
    return ToWwConvertorState2;
  })()
);
function convertToRawHTMLHavingInlines(state, node, _a) {
  var openTag = _a[0], closeTag = _a[1];
  state.write(openTag);
  state.convertInline(node);
  state.write(closeTag);
}
function convertToRawHTMLHavingBlocks(state, _a, _b) {
  var node = _a.node, parent = _a.parent;
  var openTag = _b[0], closeTag = _b[1];
  state.stopNewline = true;
  state.write(openTag);
  state.convertNode(node);
  state.write(closeTag);
  if ((parent === null || parent === void 0 ? void 0 : parent.type.name) === "doc") {
    state.closeBlock(node);
    state.stopNewline = false;
  }
}
function createTableHeadDelim(textContent, columnAlign) {
  var textLen = textContent.length;
  var leftDelim = "";
  var rightDelim = "";
  if (columnAlign === "left") {
    leftDelim = ":";
    textLen -= 1;
  } else if (columnAlign === "right") {
    rightDelim = ":";
    textLen -= 1;
  } else if (columnAlign === "center") {
    leftDelim = ":";
    rightDelim = ":";
    textLen -= 2;
  }
  return "" + leftDelim + repeat$1("-", Math.max(textLen, 3)) + rightDelim;
}
var nodeTypeWriters = {
  text: function(state, _a) {
    var _b;
    var node = _a.node;
    var text2 = (_b = node.text) !== null && _b !== void 0 ? _b : "";
    if ((node.marks || []).some(function(mark) {
      return mark.type.name === "link";
    })) {
      state.text(escapeTextForLink(text2), false);
    } else {
      state.text(text2);
    }
  },
  paragraph: function(state, _a) {
    var node = _a.node, parent = _a.parent, _b = _a.index, index2 = _b === void 0 ? 0 : _b;
    if (state.stopNewline) {
      state.convertInline(node);
    } else {
      var firstChildNode = index2 === 0;
      var prevNode = !firstChildNode && parent.child(index2 - 1);
      var prevEmptyNode = prevNode && prevNode.childCount === 0;
      var nextNode = index2 < parent.childCount - 1 && parent.child(index2 + 1);
      var nextParaNode = nextNode && nextNode.type.name === "paragraph";
      var emptyNode = node.childCount === 0;
      if (emptyNode && prevEmptyNode) {
        state.write("<br>\n");
      } else if (emptyNode && !prevEmptyNode && !firstChildNode) {
        if ((parent === null || parent === void 0 ? void 0 : parent.type.name) === "listItem") {
          var prevDelim = state.getDelim();
          state.setDelim("");
          state.write("<br>");
          state.setDelim(prevDelim);
        }
        state.write("\n");
      } else {
        state.convertInline(node);
        if (nextParaNode) {
          state.write("\n");
        } else {
          state.closeBlock(node);
        }
      }
    }
  },
  heading: function(state, _a, _b) {
    var node = _a.node;
    var delim = _b.delim;
    var headingType = node.attrs.headingType;
    if (headingType === "atx") {
      state.write(delim + " ");
      state.convertInline(node);
      state.closeBlock(node);
    } else {
      state.convertInline(node);
      state.ensureNewLine();
      state.write(delim);
      state.closeBlock(node);
    }
  },
  codeBlock: function(state, _a, _b) {
    var node = _a.node;
    var delim = _b.delim, text2 = _b.text;
    var _c = delim, openDelim = _c[0], closeDelim = _c[1];
    state.write(openDelim);
    state.ensureNewLine();
    state.text(text2, false);
    state.ensureNewLine();
    state.write(closeDelim);
    state.closeBlock(node);
  },
  blockQuote: function(state, _a, _b) {
    var node = _a.node, parent = _a.parent;
    var delim = _b.delim;
    if ((parent === null || parent === void 0 ? void 0 : parent.type.name) === node.type.name) {
      state.flushClose(1);
    }
    state.wrapBlock(delim, null, node, function() {
      return state.convertNode(node);
    });
  },
  bulletList: function(state, _a, _b) {
    var node = _a.node;
    var delim = _b.delim;
    state.convertList(node, repeat$1(" ", 4), function() {
      return delim + " ";
    });
  },
  orderedList: function(state, _a) {
    var node = _a.node;
    var start = node.attrs.order || 1;
    state.convertList(node, repeat$1(" ", 4), function(index2) {
      var orderedNum = String(start + index2);
      return orderedNum + ". ";
    });
  },
  listItem: function(state, _a) {
    var node = _a.node;
    var _b = node.attrs, task2 = _b.task, checked = _b.checked;
    if (task2) {
      state.write("[" + (checked ? "x" : " ") + "] ");
    }
    state.convertNode(node);
  },
  image: function(state, _, _a) {
    var attrs = _a.attrs;
    state.write("![" + (attrs === null || attrs === void 0 ? void 0 : attrs.altText) + "](" + (attrs === null || attrs === void 0 ? void 0 : attrs.imageUrl) + ")");
  },
  thematicBreak: function(state, _a, _b) {
    var node = _a.node;
    var delim = _b.delim;
    state.write(delim);
    state.closeBlock(node);
  },
  table: function(state, _a) {
    var node = _a.node;
    state.convertNode(node);
    state.closeBlock(node);
  },
  tableHead: function(state, _a, _b) {
    var node = _a.node;
    var delim = _b.delim;
    var row = node.firstChild;
    state.convertNode(node);
    var result = delim !== null && delim !== void 0 ? delim : "";
    if (!delim && row) {
      row.forEach(function(_a2) {
        var textContent = _a2.textContent, attrs = _a2.attrs;
        var headDelim = createTableHeadDelim(textContent, attrs.align);
        result += "| " + headDelim + " ";
      });
    }
    state.write(result + "|");
    state.ensureNewLine();
  },
  tableBody: function(state, _a) {
    var node = _a.node;
    state.convertNode(node);
  },
  tableRow: function(state, _a) {
    var node = _a.node;
    state.convertNode(node);
    state.write("|");
    state.ensureNewLine();
  },
  tableHeadCell: function(state, _a, _b) {
    var node = _a.node;
    var _c = _b.delim, delim = _c === void 0 ? "| " : _c;
    state.write(delim);
    state.convertTableCell(node);
    state.write(" ");
  },
  tableBodyCell: function(state, _a, _b) {
    var node = _a.node;
    var _c = _b.delim, delim = _c === void 0 ? "| " : _c;
    state.write(delim);
    state.convertTableCell(node);
    state.write(" ");
  },
  customBlock: function(state, _a, _b) {
    var node = _a.node;
    var delim = _b.delim, text2 = _b.text;
    var _c = delim, openDelim = _c[0], closeDelim = _c[1];
    state.write(openDelim);
    state.ensureNewLine();
    state.text(text2, false);
    state.ensureNewLine();
    state.write(closeDelim);
    state.closeBlock(node);
  },
  frontMatter: function(state, _a, _b) {
    var node = _a.node;
    var text2 = _b.text;
    state.text(text2, false);
    state.closeBlock(node);
  },
  widget: function(state, _, _a) {
    var text2 = _a.text;
    state.write(text2);
  },
  html: function(state, _a, _b) {
    var node = _a.node;
    var text2 = _b.text;
    state.write(text2);
    if (node.attrs.htmlBlock) {
      state.closeBlock(node);
    }
  },
  htmlComment: function(state, _a, _b) {
    var node = _a.node;
    var text2 = _b.text;
    state.write(text2);
    state.closeBlock(node);
  }
};
function write(type, _a) {
  var state = _a.state, nodeInfo = _a.nodeInfo, params = _a.params;
  var rawHTML = params.rawHTML;
  if (rawHTML) {
    if (inArray_1(type, ["heading", "codeBlock"]) > -1) {
      convertToRawHTMLHavingInlines(state, nodeInfo.node, rawHTML);
    } else if (inArray_1(type, ["image", "thematicBreak"]) > -1) {
      state.write(rawHTML);
    } else {
      convertToRawHTMLHavingBlocks(state, nodeInfo, rawHTML);
    }
  } else {
    nodeTypeWriters[type](state, nodeInfo, params);
  }
}
function addBackticks(node, side) {
  var text2 = node.text;
  var ticks = /`+/g;
  var len = 0;
  if (node.isText && text2) {
    var matched = ticks.exec(text2);
    while (matched) {
      len = Math.max(len, matched[0].length);
      matched = ticks.exec(text2);
    }
  }
  var result = len > 0 && side > 0 ? " `" : "`";
  for (var i = 0; i < len; i += 1) {
    result += "`";
  }
  if (len > 0 && side < 0) {
    result += " ";
  }
  return result;
}
function getPairRawHTML(rawHTML) {
  return rawHTML ? ["<" + rawHTML + ">", "</" + rawHTML + ">"] : null;
}
function getOpenRawHTML(rawHTML) {
  return rawHTML ? "<" + rawHTML + ">" : null;
}
function getCloseRawHTML(rawHTML) {
  return rawHTML ? "</" + rawHTML + ">" : null;
}
var toMdConvertors = {
  heading: function(_a) {
    var node = _a.node;
    var attrs = node.attrs;
    var level = attrs.level;
    var delim = repeat$1("#", level);
    if (attrs.headingType === "setext") {
      delim = level === 1 ? "===" : "---";
    }
    return {
      delim,
      rawHTML: getPairRawHTML(attrs.rawHTML)
    };
  },
  codeBlock: function(_a) {
    var node = _a.node;
    var _b = node, attrs = _b.attrs, textContent = _b.textContent;
    return {
      delim: ["```" + (attrs.language || ""), "```"],
      rawHTML: getPairRawHTML(attrs.rawHTML),
      text: textContent
    };
  },
  blockQuote: function(_a) {
    var node = _a.node;
    return {
      delim: "> ",
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  bulletList: function(_a, _b) {
    var node = _a.node;
    var inTable = _b.inTable;
    var rawHTML = node.attrs.rawHTML;
    if (inTable) {
      rawHTML = rawHTML || "ul";
    }
    return {
      delim: "*",
      rawHTML: getPairRawHTML(rawHTML)
    };
  },
  orderedList: function(_a, _b) {
    var node = _a.node;
    var inTable = _b.inTable;
    var rawHTML = node.attrs.rawHTML;
    if (inTable) {
      rawHTML = rawHTML || "ol";
    }
    return {
      rawHTML: getPairRawHTML(rawHTML)
    };
  },
  listItem: function(_a, _b) {
    var node = _a.node;
    var inTable = _b.inTable;
    var _c = node.attrs, task2 = _c.task, checked = _c.checked;
    var rawHTML = node.attrs.rawHTML;
    if (inTable) {
      rawHTML = rawHTML || "li";
    }
    var className = task2 ? ' class="task-list-item' + (checked ? " checked" : "") + '"' : "";
    var dataset = task2 ? " data-task" + (checked ? " data-task-checked" : "") : "";
    return {
      rawHTML: rawHTML ? ["<" + rawHTML + className + dataset + ">", "</" + rawHTML + ">"] : null
    };
  },
  table: function(_a) {
    var node = _a.node;
    return {
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  tableHead: function(_a) {
    var node = _a.node;
    return {
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  tableBody: function(_a) {
    var node = _a.node;
    return {
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  tableRow: function(_a) {
    var node = _a.node;
    return {
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  tableHeadCell: function(_a) {
    var node = _a.node;
    return {
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  tableBodyCell: function(_a) {
    var node = _a.node;
    return {
      rawHTML: getPairRawHTML(node.attrs.rawHTML)
    };
  },
  image: function(_a) {
    var node = _a.node;
    var attrs = node.attrs;
    var rawHTML = attrs.rawHTML, altText = attrs.altText;
    var imageUrl = attrs.imageUrl.replace(/&amp;/g, "&");
    var altAttr = altText ? ' alt="' + escapeXml$1(altText) + '"' : "";
    return {
      rawHTML: rawHTML ? "<" + rawHTML + ' src="' + escapeXml$1(imageUrl) + '"' + altAttr + ">" : null,
      attrs: {
        altText: escapeTextForLink(altText || ""),
        imageUrl
      }
    };
  },
  thematicBreak: function(_a) {
    var node = _a.node;
    return {
      delim: "***",
      rawHTML: getOpenRawHTML(node.attrs.rawHTML)
    };
  },
  customBlock: function(_a) {
    var node = _a.node;
    var _b = node, attrs = _b.attrs, textContent = _b.textContent;
    return {
      delim: ["$$" + attrs.info, "$$"],
      text: textContent
    };
  },
  frontMatter: function(_a) {
    var node = _a.node;
    return {
      text: node.textContent
    };
  },
  widget: function(_a) {
    var node = _a.node;
    return {
      text: node.textContent
    };
  },
  strong: function(_a, _b) {
    var node = _a.node;
    var entering = _b.entering;
    var rawHTML = node.attrs.rawHTML;
    return {
      delim: "**",
      rawHTML: entering ? getOpenRawHTML(rawHTML) : getCloseRawHTML(rawHTML)
    };
  },
  emph: function(_a, _b) {
    var node = _a.node;
    var entering = _b.entering;
    var rawHTML = node.attrs.rawHTML;
    return {
      delim: "*",
      rawHTML: entering ? getOpenRawHTML(rawHTML) : getCloseRawHTML(rawHTML)
    };
  },
  strike: function(_a, _b) {
    var node = _a.node;
    var entering = _b.entering;
    var rawHTML = node.attrs.rawHTML;
    return {
      delim: "~~",
      rawHTML: entering ? getOpenRawHTML(rawHTML) : getCloseRawHTML(rawHTML)
    };
  },
  link: function(_a, _b) {
    var node = _a.node;
    var entering = _b.entering;
    var attrs = node.attrs;
    var title = attrs.title, rawHTML = attrs.rawHTML;
    var linkUrl = attrs.linkUrl.replace(/&amp;/g, "&");
    var titleAttr = title ? ' title="' + escapeXml$1(title) + '"' : "";
    if (entering) {
      return {
        delim: "[",
        rawHTML: rawHTML ? "<" + rawHTML + ' href="' + escapeXml$1(linkUrl) + '"' + titleAttr + ">" : null
      };
    }
    return {
      delim: "](" + linkUrl + (title ? " " + quote(escapeTextForLink(title)) : "") + ")",
      rawHTML: getCloseRawHTML(rawHTML)
    };
  },
  code: function(_a, _b) {
    var node = _a.node, parent = _a.parent, _c = _a.index, index2 = _c === void 0 ? 0 : _c;
    var entering = _b.entering;
    var delim = entering ? addBackticks(parent.child(index2), -1) : addBackticks(parent.child(index2 - 1), 1);
    var rawHTML = entering ? getOpenRawHTML(node.attrs.rawHTML) : getCloseRawHTML(node.attrs.rawHTML);
    return {
      delim,
      rawHTML
    };
  },
  htmlComment: function(_a) {
    var node = _a.node;
    return {
      text: node.textContent
    };
  },
  // html inline node, html block node
  html: function(_a, _b) {
    var node = _a.node;
    var entering = _b.entering;
    var tagName = node.type.name;
    var attrs = node.attrs.htmlAttrs;
    var openTag = "<" + tagName;
    var closeTag = "</" + tagName + ">";
    Object.keys(attrs).forEach(function(attrName) {
      openTag += " " + attrName + '="' + attrs[attrName].replace(/"/g, "'") + '"';
    });
    openTag += ">";
    if (node.attrs.htmlInline) {
      return {
        rawHTML: entering ? openTag : closeTag
      };
    }
    return {
      text: "" + openTag + node.attrs.childrenHTML + closeTag
    };
  }
};
var markTypeOptions = {
  strong: {
    mixable: true,
    removedEnclosingWhitespace: true
  },
  emph: {
    mixable: true,
    removedEnclosingWhitespace: true
  },
  strike: {
    mixable: true,
    removedEnclosingWhitespace: true
  },
  code: {
    escape: false
  },
  link: null,
  html: null
};
function createNodeTypeConvertors(convertors2) {
  var nodeTypeConvertors = {};
  var nodeTypes = Object.keys(nodeTypeWriters);
  nodeTypes.forEach(function(type) {
    nodeTypeConvertors[type] = function(state, nodeInfo) {
      var writer = nodeTypeWriters[type];
      if (writer) {
        var convertor = convertors2[type];
        var params = convertor ? convertor(nodeInfo, {
          inTable: state.inTable
        }) : {};
        write(type, { state, nodeInfo, params });
      }
    };
  });
  return nodeTypeConvertors;
}
function createMarkTypeConvertors(convertors2) {
  var markTypeConvertors = {};
  var markTypes = Object.keys(markTypeOptions);
  markTypes.forEach(function(type) {
    markTypeConvertors[type] = function(nodeInfo, entering) {
      var markOption = markTypeOptions[type];
      var convertor = convertors2[type];
      var runConvertor = convertor && nodeInfo && !isUndefined_1(entering);
      var params = runConvertor ? convertor(nodeInfo, { entering }) : {};
      return __assign$1(__assign$1({}, params), markOption);
    };
  });
  return markTypeConvertors;
}
function createMdConvertors(customConvertors) {
  var customConvertorTypes = Object.keys(customConvertors);
  customConvertorTypes.forEach(function(type) {
    var baseConvertor = toMdConvertors[type];
    var customConvertor = customConvertors[type];
    if (baseConvertor) {
      toMdConvertors[type] = function(nodeInfo, context) {
        context.origin = function() {
          return baseConvertor(nodeInfo, context);
        };
        return customConvertor(nodeInfo, context);
      };
    } else {
      toMdConvertors[type] = customConvertor;
    }
    delete customConvertors[type];
  });
  var nodeTypeConvertors = createNodeTypeConvertors(toMdConvertors);
  var markTypeConvertors = createMarkTypeConvertors(toMdConvertors);
  return {
    nodeTypeConvertors,
    markTypeConvertors
  };
}
var ToMdConvertorState = (
  /** @class */
  (function() {
    function ToMdConvertorState2(_a) {
      var nodeTypeConvertors = _a.nodeTypeConvertors, markTypeConvertors = _a.markTypeConvertors;
      this.nodeTypeConvertors = nodeTypeConvertors;
      this.markTypeConvertors = markTypeConvertors;
      this.delim = "";
      this.result = "";
      this.closed = false;
      this.tightList = false;
      this.stopNewline = false;
      this.inTable = false;
    }
    ToMdConvertorState2.prototype.getMarkConvertor = function(mark) {
      var type = mark.attrs.htmlInline ? "html" : mark.type.name;
      return this.markTypeConvertors[type];
    };
    ToMdConvertorState2.prototype.isInBlank = function() {
      return /(^|\n)$/.test(this.result);
    };
    ToMdConvertorState2.prototype.markText = function(mark, entering, parent, index2) {
      var convertor = this.getMarkConvertor(mark);
      if (convertor) {
        var _a = convertor({ node: mark, parent, index: index2 }, entering), delim = _a.delim, rawHTML = _a.rawHTML;
        return rawHTML || delim;
      }
      return "";
    };
    ToMdConvertorState2.prototype.setDelim = function(delim) {
      this.delim = delim;
    };
    ToMdConvertorState2.prototype.getDelim = function() {
      return this.delim;
    };
    ToMdConvertorState2.prototype.flushClose = function(size) {
      if (!this.stopNewline && this.closed) {
        if (!this.isInBlank()) {
          this.result += "\n";
        }
        if (!size) {
          size = 2;
        }
        if (size > 1) {
          var delimMin = this.delim;
          var trim = /\s+$/.exec(delimMin);
          if (trim) {
            delimMin = delimMin.slice(0, delimMin.length - trim[0].length);
          }
          for (var i = 1; i < size; i += 1) {
            this.result += delimMin + "\n";
          }
        }
        this.closed = false;
      }
    };
    ToMdConvertorState2.prototype.wrapBlock = function(delim, firstDelim, node, fn) {
      var old = this.getDelim();
      this.write(firstDelim || delim);
      this.setDelim(this.getDelim() + delim);
      fn();
      this.setDelim(old);
      this.closeBlock(node);
    };
    ToMdConvertorState2.prototype.ensureNewLine = function() {
      if (!this.isInBlank()) {
        this.result += "\n";
      }
    };
    ToMdConvertorState2.prototype.write = function(content) {
      if (content === void 0) {
        content = "";
      }
      this.flushClose();
      if (this.delim && this.isInBlank()) {
        this.result += this.delim;
      }
      if (content) {
        this.result += content;
      }
    };
    ToMdConvertorState2.prototype.closeBlock = function(node) {
      this.closed = node;
    };
    ToMdConvertorState2.prototype.text = function(text2, escaped) {
      if (escaped === void 0) {
        escaped = true;
      }
      var lines = text2.split("\n");
      for (var i = 0; i < lines.length; i += 1) {
        this.write();
        this.result += escaped ? escape$1(lines[i]) : lines[i];
        if (i !== lines.length - 1) {
          this.result += "\n";
        }
      }
    };
    ToMdConvertorState2.prototype.convertBlock = function(node, parent, index2) {
      var type = node.type.name;
      var convertor = this.nodeTypeConvertors[type];
      var nodeInfo = { node, parent, index: index2 };
      if (node.attrs.htmlBlock) {
        this.nodeTypeConvertors.html(this, nodeInfo);
      } else if (convertor) {
        convertor(this, nodeInfo);
      }
    };
    ToMdConvertorState2.prototype.convertInline = function(parent) {
      var _this = this;
      var active = [];
      var trailing = "";
      var progress = function(node, _, index2) {
        var marks = node ? node.marks : [];
        var leading = trailing;
        trailing = "";
        var removedWhitespace = node && node.isText && marks.some(function(mark2) {
          var markConvertor2 = _this.getMarkConvertor(mark2);
          var info = markConvertor2 && markConvertor2();
          return info && info.removedEnclosingWhitespace;
        });
        if (removedWhitespace && node && node.text) {
          var _a = /^(\s*)(.*?)(\s*)$/m.exec(node.text), lead = _a[1], mark = _a[2], trail = _a[3];
          leading += lead;
          trailing = trail;
          if (lead || trail) {
            node = mark ? node.withText(mark) : null;
            if (!node) {
              marks = active;
            }
          }
        }
        var lastMark = marks.length && last$1(marks);
        var markConvertor = lastMark && _this.getMarkConvertor(lastMark);
        var markType = markConvertor && markConvertor();
        var noEscape = markType && markType.escape === false;
        var len = marks.length - (noEscape ? 1 : 0);
        for (var i = 0; i < len; i += 1) {
          var mark = marks[i];
          if (markType && !markType.mixable) {
            break;
          }
          for (var j = 0; j < active.length; j += 1) {
            var other = active[j];
            if (markType && !markType.mixable) {
              break;
            }
            if (mark.eq(other)) {
              if (i > j) {
                marks = marks.slice(0, j).concat(mark).concat(marks.slice(j, i)).concat(marks.slice(i + 1, len));
              } else if (j > i) {
                marks = marks.slice(0, i).concat(marks.slice(i + 1, j)).concat(mark).concat(marks.slice(j, len));
              }
              break;
            }
          }
        }
        var keep = 0;
        while (keep < Math.min(active.length, len) && marks[keep].eq(active[keep])) {
          keep += 1;
        }
        while (keep < active.length) {
          var activedMark = active.pop();
          if (activedMark) {
            _this.text(_this.markText(activedMark, false, parent, index2), false);
          }
        }
        if (leading) {
          _this.text(leading);
        }
        if (node) {
          while (active.length < len) {
            var mark = marks[active.length];
            active.push(mark);
            _this.text(_this.markText(mark, true, parent, index2), false);
          }
          if (noEscape && node.isText) {
            _this.text(_this.markText(lastMark, true, parent, index2) + node.text + _this.markText(lastMark, false, parent, index2 + 1), false);
          } else {
            _this.convertBlock(node, parent, index2);
          }
        }
      };
      parent.forEach(progress);
      progress(null, null, parent.childCount);
    };
    ToMdConvertorState2.prototype.convertList = function(node, delim, firstDelimFn) {
      var _this = this;
      var _a;
      if (this.closed && this.closed.type === node.type) {
        this.flushClose(3);
      } else if (this.tightList) {
        this.flushClose(1);
      }
      var tight = (_a = node.attrs.tight) !== null && _a !== void 0 ? _a : true;
      var prevTight = this.tightList;
      this.tightList = tight;
      node.forEach(function(child, _, index2) {
        if (index2 && tight) {
          _this.flushClose(1);
        }
        _this.wrapBlock(delim, firstDelimFn(index2), node, function() {
          return _this.convertBlock(child, node, index2);
        });
      });
      this.tightList = prevTight;
    };
    ToMdConvertorState2.prototype.convertTableCell = function(node) {
      var _this = this;
      this.stopNewline = true;
      this.inTable = true;
      node.forEach(function(child, _, index2) {
        if (includes(["bulletList", "orderedList"], child.type.name)) {
          _this.convertBlock(child, node, index2);
          _this.closed = false;
        } else {
          _this.convertInline(child);
          if (index2 < node.childCount - 1) {
            var nextChild = node.child(index2 + 1);
            if (nextChild.type.name === "paragraph") {
              _this.write("<br>");
            }
          }
        }
      });
      this.stopNewline = false;
      this.inTable = false;
    };
    ToMdConvertorState2.prototype.convertNode = function(parent, infoForPosSync) {
      var _this = this;
      parent.forEach(function(node, _, index2) {
        _this.convertBlock(node, parent, index2);
        if ((infoForPosSync === null || infoForPosSync === void 0 ? void 0 : infoForPosSync.node) === node) {
          var lineTexts = _this.result.split("\n");
          infoForPosSync.setMappedPos([lineTexts.length, last$1(lineTexts).length + 1]);
        }
      });
      return this.result;
    };
    return ToMdConvertorState2;
  })()
);
var Convertor = (
  /** @class */
  (function() {
    function Convertor2(schema, toMdConvertors2, toHTMLConvertors, eventEmitter) {
      var _this = this;
      this.setMappedPos = function(pos) {
        _this.mappedPosWhenConverting = pos;
      };
      this.schema = schema;
      this.eventEmitter = eventEmitter;
      this.focusedNode = null;
      this.mappedPosWhenConverting = null;
      this.toWwConvertors = createWwConvertors(toHTMLConvertors);
      this.toMdConvertors = createMdConvertors(toMdConvertors2 || {});
      this.eventEmitter.listen("setFocusedNode", function(node) {
        return _this.focusedNode = node;
      });
    }
    Convertor2.prototype.getMappedPos = function() {
      return this.mappedPosWhenConverting;
    };
    Convertor2.prototype.getInfoForPosSync = function() {
      return { node: this.focusedNode, setMappedPos: this.setMappedPos };
    };
    Convertor2.prototype.toWysiwygModel = function(mdNode) {
      var state = new ToWwConvertorState(this.schema, this.toWwConvertors);
      return state.convertNode(mdNode, this.getInfoForPosSync());
    };
    Convertor2.prototype.toMarkdownText = function(wwNode) {
      var state = new ToMdConvertorState(this.toMdConvertors);
      var markdownText = state.convertNode(wwNode, this.getInfoForPosSync());
      markdownText = this.eventEmitter.emitReduce("beforeConvertWysiwygToMarkdown", markdownText);
      return markdownText;
    };
    return Convertor2;
  })()
);
function execPlugin(pluginInfo) {
  var plugin = pluginInfo.plugin, eventEmitter = pluginInfo.eventEmitter, usageStatistics = pluginInfo.usageStatistics, instance = pluginInfo.instance;
  var pmState = { Plugin, PluginKey, Selection, TextSelection };
  var pmView = { Decoration, DecorationSet };
  var pmModel = { Fragment };
  var pmRules = { InputRule, inputRules, undoInputRule };
  var pmKeymap = { keymap };
  var context = {
    eventEmitter,
    usageStatistics,
    instance,
    pmState,
    pmView,
    pmModel,
    pmRules,
    pmKeymap,
    i18n
  };
  if (isArray_1(plugin)) {
    var pluginFn = plugin[0], _a = plugin[1], options = _a === void 0 ? {} : _a;
    return pluginFn(context, options);
  }
  return plugin(context);
}
function getPluginInfo(pluginsInfo) {
  var plugins = pluginsInfo.plugins, eventEmitter = pluginsInfo.eventEmitter, usageStatistics = pluginsInfo.usageStatistics, instance = pluginsInfo.instance;
  eventEmitter.listen("mixinTableOffsetMapPrototype", mixinTableOffsetMapPrototype);
  return (plugins !== null && plugins !== void 0 ? plugins : []).reduce(function(acc, plugin) {
    var pluginInfoResult = execPlugin({
      plugin,
      eventEmitter,
      usageStatistics,
      instance
    });
    if (!pluginInfoResult) {
      throw new Error("The return value of the executed plugin is empty.");
    }
    var markdownParsers = pluginInfoResult.markdownParsers, toHTMLRenderers = pluginInfoResult.toHTMLRenderers, toMarkdownRenderers = pluginInfoResult.toMarkdownRenderers, markdownPlugins = pluginInfoResult.markdownPlugins, wysiwygPlugins = pluginInfoResult.wysiwygPlugins, wysiwygNodeViews = pluginInfoResult.wysiwygNodeViews, markdownCommands = pluginInfoResult.markdownCommands, wysiwygCommands = pluginInfoResult.wysiwygCommands, toolbarItems = pluginInfoResult.toolbarItems;
    if (toHTMLRenderers) {
      acc.toHTMLRenderers = deepMergedCopy(acc.toHTMLRenderers, toHTMLRenderers);
    }
    if (toMarkdownRenderers) {
      acc.toMarkdownRenderers = deepMergedCopy(acc.toMarkdownRenderers, toMarkdownRenderers);
    }
    if (markdownPlugins) {
      acc.mdPlugins = acc.mdPlugins.concat(markdownPlugins);
    }
    if (wysiwygPlugins) {
      acc.wwPlugins = acc.wwPlugins.concat(wysiwygPlugins);
    }
    if (wysiwygNodeViews) {
      acc.wwNodeViews = __assign$1(__assign$1({}, acc.wwNodeViews), wysiwygNodeViews);
    }
    if (markdownCommands) {
      acc.mdCommands = __assign$1(__assign$1({}, acc.mdCommands), markdownCommands);
    }
    if (wysiwygCommands) {
      acc.wwCommands = __assign$1(__assign$1({}, acc.wwCommands), wysiwygCommands);
    }
    if (toolbarItems) {
      acc.toolbarItems = acc.toolbarItems.concat(toolbarItems);
    }
    if (markdownParsers) {
      acc.markdownParsers = __assign$1(__assign$1({}, acc.markdownParsers), markdownParsers);
    }
    return acc;
  }, {
    toHTMLRenderers: {},
    toMarkdownRenderers: {},
    mdPlugins: [],
    wwPlugins: [],
    wwNodeViews: {},
    mdCommands: {},
    wwCommands: {},
    toolbarItems: [],
    markdownParsers: {}
  });
}
var TASK_ATTR_NAME = "data-task";
var DISABLED_TASK_ATTR_NAME = "data-task-disabled";
var TASK_CHECKED_CLASS_NAME = "checked";
function registerHTMLTagToWhitelist(convertorMap) {
  ["htmlBlock", "htmlInline"].forEach(function(htmlType) {
    if (convertorMap[htmlType]) {
      Object.keys(convertorMap[htmlType]).forEach(function(type) {
        return registerTagWhitelistIfPossible(type);
      });
    }
  });
}
var ToastUIEditorViewer = (
  /** @class */
  (function() {
    function ToastUIEditorViewer2(options) {
      var _this = this;
      this.options = extend_1({
        linkAttributes: null,
        extendedAutolinks: false,
        customHTMLRenderer: null,
        referenceDefinition: false,
        customHTMLSanitizer: null,
        frontMatter: false,
        usageStatistics: true,
        theme: "light"
      }, options);
      this.eventEmitter = new EventEmitter();
      var linkAttributes = sanitizeLinkAttribute(this.options.linkAttributes);
      var _a = getPluginInfo({
        plugins: this.options.plugins,
        eventEmitter: this.eventEmitter,
        usageStatistics: this.options.usageStatistics,
        instance: this
      }) || {}, toHTMLRenderers = _a.toHTMLRenderers, markdownParsers = _a.markdownParsers;
      var _b = this.options, customHTMLRenderer = _b.customHTMLRenderer, extendedAutolinks = _b.extendedAutolinks, referenceDefinition = _b.referenceDefinition, frontMatter2 = _b.frontMatter, customHTMLSanitizer = _b.customHTMLSanitizer;
      var rendererOptions = {
        linkAttributes,
        customHTMLRenderer: __assign$1(__assign$1({}, toHTMLRenderers), customHTMLRenderer),
        extendedAutolinks,
        referenceDefinition,
        frontMatter: frontMatter2,
        sanitizer: customHTMLSanitizer || sanitizeHTML
      };
      registerHTMLTagToWhitelist(rendererOptions.customHTMLRenderer);
      if (this.options.events) {
        forEachOwnProperties_1(this.options.events, function(fn, key) {
          _this.on(key, fn);
        });
      }
      var _c = this.options, el2 = _c.el, initialValue = _c.initialValue, theme = _c.theme;
      var existingHTML = el2.innerHTML;
      if (theme !== "light") {
        el2.classList.add(cls(theme));
      }
      el2.innerHTML = "";
      this.toastMark = new ToastMark("", {
        disallowedHtmlBlockTags: ["br", "img"],
        extendedAutolinks,
        referenceDefinition,
        disallowDeepHeading: true,
        frontMatter: frontMatter2,
        customParser: markdownParsers
      });
      this.preview = new MarkdownPreview(this.eventEmitter, __assign$1(__assign$1({}, rendererOptions), { isViewer: true }));
      on_1(this.preview.previewContent, "mousedown", this.toggleTask.bind(this));
      if (initialValue) {
        this.setMarkdown(initialValue);
      } else if (existingHTML) {
        this.preview.setHTML(existingHTML);
      }
      el2.appendChild(this.preview.previewContent);
      this.eventEmitter.emit("load", this);
    }
    ToastUIEditorViewer2.prototype.toggleTask = function(ev) {
      var element = ev.target;
      var style = getComputedStyle(element, ":before");
      if (!element.hasAttribute(DISABLED_TASK_ATTR_NAME) && element.hasAttribute(TASK_ATTR_NAME) && isPositionInBox(style, ev.offsetX, ev.offsetY)) {
        toggleClass(element, TASK_CHECKED_CLASS_NAME);
        this.eventEmitter.emit("change", {
          source: "viewer",
          date: ev
        });
      }
    };
    ToastUIEditorViewer2.prototype.setMarkdown = function(markdown) {
      var lineTexts = this.toastMark.getLineTexts();
      var length = lineTexts.length;
      var lastLine = last$1(lineTexts);
      var endSourcepos = [length, lastLine.length + 1];
      var editResult = this.toastMark.editMarkdown([1, 1], endSourcepos, markdown || "");
      this.eventEmitter.emit("updatePreview", editResult);
    };
    ToastUIEditorViewer2.prototype.on = function(type, handler) {
      this.eventEmitter.listen(type, handler);
    };
    ToastUIEditorViewer2.prototype.off = function(type) {
      this.eventEmitter.removeEventHandler(type);
    };
    ToastUIEditorViewer2.prototype.addHook = function(type, handler) {
      this.eventEmitter.removeEventHandler(type);
      this.eventEmitter.listen(type, handler);
    };
    ToastUIEditorViewer2.prototype.destroy = function() {
      off_1(this.preview.el, "mousedown", this.toggleTask.bind(this));
      this.preview.destroy();
      this.eventEmitter.emit("destroy");
    };
    ToastUIEditorViewer2.prototype.isViewer = function() {
      return true;
    };
    ToastUIEditorViewer2.prototype.isMarkdownMode = function() {
      return false;
    };
    ToastUIEditorViewer2.prototype.isWysiwygMode = function() {
      return false;
    };
    return ToastUIEditorViewer2;
  })()
);
function isPmNode(node) {
  return node instanceof Node2;
}
function isContainer(type) {
  var containerTypes = [
    "document",
    "blockQuote",
    "bulletList",
    "orderedList",
    "listItem",
    "paragraph",
    "heading",
    "emph",
    "strong",
    "strike",
    "link",
    "image",
    "table",
    "tableHead",
    "tableBody",
    "tableRow",
    "tableHeadCell",
    "tableBodyCell"
  ];
  return includes(containerTypes, type);
}
function createMdLikeNode(node) {
  var attrs = node.attrs, type = node.type;
  var nodeType = type.name;
  var mdLikeNode = {
    type: nodeType,
    wysiwygNode: true,
    literal: !isContainer(nodeType) && isPmNode(node) ? node.textContent : null
  };
  var nodeTypeMap = {
    heading: { level: attrs.level },
    link: { destination: attrs.linkUrl, title: attrs.title },
    image: { destination: attrs.imageUrl },
    codeBlock: { info: attrs.language },
    bulletList: { type: "list", listData: { type: "bullet" } },
    orderedList: { type: "list", listData: { type: "ordered", start: attrs.order } },
    listItem: { type: "item", listData: { task: attrs.task, checked: attrs.checked } },
    tableHeadCell: { type: "tableCell", cellType: "head", align: attrs.align },
    tableBodyCell: { type: "tableCell", cellType: "body", align: attrs.align },
    customBlock: { info: attrs.info }
  };
  var nodeInfo = nodeTypeMap[nodeType];
  var attributes = __assign$1(__assign$1({}, mdLikeNode), nodeInfo);
  var _a = node.attrs, htmlAttrs = _a.htmlAttrs, childrenHTML = _a.childrenHTML;
  if (htmlAttrs) {
    return __assign$1(__assign$1({}, attributes), { attrs: htmlAttrs, childrenHTML });
  }
  return attributes;
}
var tokenToDOMNode = {
  openTag: function(token, stack) {
    var _a = token, tagName = _a.tagName, classNames = _a.classNames, attributes = _a.attributes;
    var el2 = document.createElement(tagName);
    var attrs = {};
    if (classNames) {
      el2.className = classNames.join(" ");
    }
    if (attributes) {
      attrs = __assign$1(__assign$1({}, attrs), attributes);
    }
    setAttributes(attrs, el2);
    stack.push(el2);
  },
  closeTag: function(_, stack) {
    if (stack.length > 1) {
      var el2 = stack.pop();
      last$1(stack).appendChild(el2);
    }
  },
  html: function(token, stack) {
    last$1(stack).insertAdjacentHTML("beforeend", token.content);
  },
  text: function(token, stack) {
    var textNode = document.createTextNode(token.content);
    last$1(stack).appendChild(textNode);
  }
};
var WwToDOMAdaptor = (
  /** @class */
  (function() {
    function WwToDOMAdaptor2(linkAttributes, customRenderer) {
      var convertors2 = getHTMLRenderConvertors(linkAttributes, customRenderer);
      var customHTMLConvertor = __assign$1(__assign$1({}, customRenderer.htmlBlock), customRenderer.htmlInline);
      this.customConvertorKeys = Object.keys(customRenderer).concat(Object.keys(customHTMLConvertor));
      this.renderer = new Renderer({
        gfm: true,
        convertors: __assign$1(__assign$1({}, convertors2), customHTMLConvertor)
      });
      this.convertors = this.renderer.getConvertors();
    }
    WwToDOMAdaptor2.prototype.generateTokens = function(node) {
      var mdLikeNode = createMdLikeNode(node);
      var context = {
        entering: true,
        leaf: isPmNode(node) ? node.isLeaf : false,
        options: this.renderer.getOptions(),
        getChildrenText: function() {
          return isPmNode(node) ? node.textContent : "";
        },
        skipChildren: function() {
          return false;
        }
      };
      var convertor = this.convertors[node.type.name];
      var converted = convertor(mdLikeNode, context, this.convertors);
      var tokens = isArray_1(converted) ? converted : [converted];
      if (isContainer(node.type.name) || node.attrs.htmlInline) {
        context.entering = false;
        tokens.push({ type: "text", content: isPmNode(node) ? node.textContent : "" });
        tokens = tokens.concat(convertor(mdLikeNode, context, this.convertors));
      }
      return tokens;
    };
    WwToDOMAdaptor2.prototype.toDOMNode = function(node) {
      var tokens = this.generateTokens(node);
      var stack = [];
      tokens.forEach(function(token) {
        return tokenToDOMNode[token.type](token, stack);
      });
      return stack[0];
    };
    WwToDOMAdaptor2.prototype.getToDOMNode = function(name) {
      if (includes(this.customConvertorKeys, name)) {
        return this.toDOMNode.bind(this);
      }
      return null;
    };
    return WwToDOMAdaptor2;
  })()
);
var ANIMATION_TIME = 100;
var SCROLL_BLOCKING_RESET_DELAY = 15;
var currentTimeoutId = null;
var releaseTimer = null;
function run2(deltaScrollTop, _a) {
  var syncScrollTop = _a.syncScrollTop, releaseEventBlock = _a.releaseEventBlock;
  if (releaseTimer) {
    clearTimeout(releaseTimer);
  }
  syncScrollTop(deltaScrollTop);
  releaseTimer = setTimeout(function() {
    releaseEventBlock();
  }, SCROLL_BLOCKING_RESET_DELAY);
}
function animate(curScrollTop, targetScrollTop, syncCallbacks) {
  var diff2 = targetScrollTop - curScrollTop;
  var startTime = Date.now();
  var step = function() {
    var stepTime = Date.now();
    var progress = (stepTime - startTime) / ANIMATION_TIME;
    var deltaValue;
    if (currentTimeoutId) {
      clearTimeout(currentTimeoutId);
    }
    if (progress < 1) {
      deltaValue = curScrollTop + diff2 * Math.cos((1 - progress) * Math.PI / 2);
      run2(Math.ceil(deltaValue), syncCallbacks);
      currentTimeoutId = setTimeout(step, 1);
    } else {
      run2(targetScrollTop, syncCallbacks);
      currentTimeoutId = null;
    }
  };
  step();
}
var EDITOR_BOTTOM_PADDING = 18;
var ScrollSync = (
  /** @class */
  (function() {
    function ScrollSync2(mdEditor, preview, eventEmitter) {
      this.latestEditorScrollTop = null;
      this.latestPreviewScrollTop = null;
      this.blockedScroll = null;
      this.active = true;
      this.timer = null;
      var previewRoot = preview.previewContent, previewEl = preview.el;
      this.previewRoot = previewRoot;
      this.previewEl = previewEl;
      this.mdEditor = mdEditor;
      this.editorView = mdEditor.view;
      this.toastMark = mdEditor.getToastMark();
      this.eventEmitter = eventEmitter;
      this.addScrollSyncEvent();
    }
    ScrollSync2.prototype.addScrollSyncEvent = function() {
      var _this = this;
      this.eventEmitter.listen("afterPreviewRender", function() {
        _this.clearTimer();
        _this.timer = setTimeout(function() {
          _this.syncPreviewScrollTop(true);
        }, 200);
      });
      this.eventEmitter.listen("scroll", function(type, data) {
        if (_this.active) {
          if (type === "editor" && _this.blockedScroll !== "editor") {
            _this.syncPreviewScrollTop();
          } else if (type === "preview" && _this.blockedScroll !== "preview") {
            _this.syncEditorScrollTop(data);
          }
        }
      });
      this.eventEmitter.listen("toggleScrollSync", function(active) {
        _this.active = active;
      });
    };
    ScrollSync2.prototype.getMdNodeAtPos = function(doc3, posInfo) {
      var indexInfo = doc3.content.findIndex(posInfo.pos);
      var line = indexInfo.index;
      return this.toastMark.findFirstNodeAtLine(line + 1);
    };
    ScrollSync2.prototype.getScrollTopByCaretPos = function() {
      var pos = this.mdEditor.getSelection();
      var firstMdNode = this.toastMark.findFirstNodeAtLine(pos[0][0]);
      var previewHeight = this.previewEl.clientHeight;
      var el2 = getParentNodeObj(this.previewRoot, firstMdNode).el;
      var totalOffsetTop = getTotalOffsetTop(el2, this.previewRoot) || el2.offsetTop;
      var nodeHeight = el2.clientHeight;
      var targetScrollTop = totalOffsetTop + nodeHeight - previewHeight * 0.5;
      this.latestEditorScrollTop = null;
      var diff2 = el2.getBoundingClientRect().top - this.previewEl.getBoundingClientRect().top;
      return diff2 < previewHeight ? null : targetScrollTop;
    };
    ScrollSync2.prototype.syncPreviewScrollTop = function(editing) {
      if (editing === void 0) {
        editing = false;
      }
      var _a = this, editorView = _a.editorView, previewEl = _a.previewEl, previewRoot = _a.previewRoot;
      var _b = editorView.dom.getBoundingClientRect(), left = _b.left, top2 = _b.top;
      var posInfo = editorView.posAtCoords({ left, top: top2 });
      var doc3 = editorView.state.doc;
      var firstMdNode = this.getMdNodeAtPos(doc3, posInfo);
      if (!firstMdNode || isHTMLNode(firstMdNode)) {
        return;
      }
      var curScrollTop = previewEl.scrollTop;
      var _c = editorView.dom, scrollTop = _c.scrollTop, scrollHeight = _c.scrollHeight, clientHeight = _c.clientHeight, children = _c.children;
      var isBottomPos = scrollHeight - scrollTop <= clientHeight + EDITOR_BOTTOM_PADDING;
      var targetScrollTop = isBottomPos ? previewEl.scrollHeight : 0;
      if (scrollTop && !isBottomPos) {
        if (editing) {
          var scrollTopByEditing = this.getScrollTopByCaretPos();
          if (!scrollTopByEditing) {
            return;
          }
          targetScrollTop = scrollTopByEditing;
        } else {
          var _d = getParentNodeObj(this.previewRoot, firstMdNode), el2 = _d.el, mdNode = _d.mdNode;
          var _e = getEditorRangeHeightInfo(doc3, mdNode, children), height = _e.height, rect2 = _e.rect;
          var totalOffsetTop = getTotalOffsetTop(el2, previewRoot) || el2.offsetTop;
          var nodeHeight = el2.clientHeight;
          var ratio2 = top2 > rect2.top ? Math.min((top2 - rect2.top) / height, 1) : 0;
          targetScrollTop = totalOffsetTop + nodeHeight * ratio2;
        }
        targetScrollTop = this.getResolvedScrollTop("editor", scrollTop, targetScrollTop, curScrollTop);
        this.latestEditorScrollTop = scrollTop;
      }
      if (targetScrollTop !== curScrollTop) {
        this.run("editor", targetScrollTop, curScrollTop);
      }
    };
    ScrollSync2.prototype.syncEditorScrollTop = function(targetNode) {
      var _a = this, toastMark = _a.toastMark, editorView = _a.editorView, previewRoot = _a.previewRoot, previewEl = _a.previewEl;
      var dom = editorView.dom, state = editorView.state;
      var scrollTop = previewEl.scrollTop, clientHeight = previewEl.clientHeight, scrollHeight = previewEl.scrollHeight;
      var isBottomPos = scrollHeight - scrollTop <= clientHeight;
      var curScrollTop = dom.scrollTop;
      var targetScrollTop = isBottomPos ? dom.scrollHeight : 0;
      if (scrollTop && targetNode && !isBottomPos) {
        targetNode = findAncestorHavingId(targetNode, previewRoot);
        if (!targetNode.getAttribute("data-nodeid")) {
          return;
        }
        var children = dom.children;
        var mdNodeId = Number(targetNode.getAttribute("data-nodeid"));
        var _b = getParentNodeObj(this.previewRoot, toastMark.findNodeById(mdNodeId)), mdNode = _b.mdNode, el2 = _b.el;
        var mdNodeStartLine = getMdStartLine(mdNode);
        targetScrollTop = children[mdNodeStartLine - 1].offsetTop;
        var height = getEditorRangeHeightInfo(state.doc, mdNode, children).height;
        var _c = getAndSaveOffsetInfo(el2, previewRoot, mdNodeId), nodeHeight = _c.nodeHeight, offsetTop = _c.offsetTop;
        targetScrollTop += getAdditionalPos(scrollTop, offsetTop, nodeHeight, height);
        targetScrollTop = this.getResolvedScrollTop("preview", scrollTop, targetScrollTop, curScrollTop);
        this.latestPreviewScrollTop = scrollTop;
      }
      if (targetScrollTop !== curScrollTop) {
        this.run("preview", targetScrollTop, curScrollTop);
      }
    };
    ScrollSync2.prototype.getResolvedScrollTop = function(from2, scrollTop, targetScrollTop, curScrollTop) {
      var latestScrollTop = from2 === "editor" ? this.latestEditorScrollTop : this.latestPreviewScrollTop;
      if (latestScrollTop === null) {
        return targetScrollTop;
      }
      return latestScrollTop < scrollTop ? Math.max(targetScrollTop, curScrollTop) : Math.min(targetScrollTop, curScrollTop);
    };
    ScrollSync2.prototype.run = function(from2, targetScrollTop, curScrollTop) {
      var _this = this;
      var scrollTarget;
      if (from2 === "editor") {
        scrollTarget = this.previewEl;
        this.blockedScroll = "preview";
      } else {
        scrollTarget = this.editorView.dom;
        this.blockedScroll = "editor";
      }
      var syncCallbacks = {
        syncScrollTop: function(scrollTop) {
          return scrollTarget.scrollTop = scrollTop;
        },
        releaseEventBlock: function() {
          return _this.blockedScroll = null;
        }
      };
      animate(curScrollTop, targetScrollTop, syncCallbacks);
    };
    ScrollSync2.prototype.clearTimer = function() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    };
    ScrollSync2.prototype.destroy = function() {
      this.clearTimer();
      this.eventEmitter.removeEventHandler("scroll");
      this.eventEmitter.removeEventHandler("afterPreviewRender");
    };
    return ScrollSync2;
  })()
);
var queryMap = {
  getPopupInitialValues: function(editor, payload) {
    var popupName = payload.popupName;
    return popupName === "link" ? { linkText: editor.getSelectedText() } : {};
  }
};
function buildQuery(editor) {
  editor.eventEmitter.listen("query", function(query, payload) {
    return queryMap[query](editor, payload);
  });
}
var ToastUIEditorCore = (
  /** @class */
  (function() {
    function ToastUIEditorCore2(options) {
      var _this = this;
      this.initialHTML = options.el.innerHTML;
      options.el.innerHTML = "";
      this.options = extend_1({
        previewStyle: "tab",
        previewHighlight: true,
        initialEditType: "markdown",
        height: "300px",
        minHeight: "200px",
        language: "en-US",
        useCommandShortcut: true,
        usageStatistics: true,
        toolbarItems: [
          ["heading", "bold", "italic", "strike"],
          ["hr", "quote"],
          ["ul", "ol", "task", "indent", "outdent"],
          ["table", "image", "link"],
          ["code", "codeblock"],
          ["scrollSync"]
        ],
        hideModeSwitch: false,
        linkAttributes: null,
        extendedAutolinks: false,
        customHTMLRenderer: null,
        customMarkdownRenderer: null,
        referenceDefinition: false,
        customHTMLSanitizer: null,
        frontMatter: false,
        widgetRules: [],
        theme: "light",
        autofocus: true
      }, options);
      var _a = this.options, customHTMLRenderer = _a.customHTMLRenderer, extendedAutolinks = _a.extendedAutolinks, referenceDefinition = _a.referenceDefinition, frontMatter2 = _a.frontMatter, customMarkdownRenderer = _a.customMarkdownRenderer, useCommandShortcut = _a.useCommandShortcut, initialEditType = _a.initialEditType, widgetRules2 = _a.widgetRules, customHTMLSanitizer = _a.customHTMLSanitizer;
      this.mode = initialEditType || "markdown";
      this.mdPreviewStyle = this.options.previewStyle;
      this.i18n = i18n;
      this.i18n.setCode(this.options.language);
      this.eventEmitter = new EventEmitter();
      setWidgetRules(widgetRules2);
      var linkAttributes = sanitizeLinkAttribute(this.options.linkAttributes);
      this.pluginInfo = getPluginInfo({
        plugins: this.options.plugins,
        eventEmitter: this.eventEmitter,
        usageStatistics: this.options.usageStatistics,
        instance: this
      });
      var _b = this.pluginInfo, toHTMLRenderers = _b.toHTMLRenderers, toMarkdownRenderers = _b.toMarkdownRenderers, mdPlugins = _b.mdPlugins, wwPlugins = _b.wwPlugins, wwNodeViews = _b.wwNodeViews, mdCommands = _b.mdCommands, wwCommands = _b.wwCommands, markdownParsers = _b.markdownParsers;
      var rendererOptions = {
        linkAttributes,
        customHTMLRenderer: deepMergedCopy(toHTMLRenderers, customHTMLRenderer),
        extendedAutolinks,
        referenceDefinition,
        frontMatter: frontMatter2,
        sanitizer: customHTMLSanitizer || sanitizeHTML
      };
      var wwToDOMAdaptor = new WwToDOMAdaptor(linkAttributes, rendererOptions.customHTMLRenderer);
      var htmlSchemaMap = createHTMLSchemaMap(rendererOptions.customHTMLRenderer, rendererOptions.sanitizer, wwToDOMAdaptor);
      this.toastMark = new ToastMark("", {
        disallowedHtmlBlockTags: ["br", "img"],
        extendedAutolinks,
        referenceDefinition,
        disallowDeepHeading: true,
        frontMatter: frontMatter2,
        customParser: markdownParsers
      });
      this.mdEditor = new MdEditor(this.eventEmitter, {
        toastMark: this.toastMark,
        useCommandShortcut,
        mdPlugins
      });
      this.preview = new MarkdownPreview(this.eventEmitter, __assign$1(__assign$1({}, rendererOptions), { isViewer: false, highlight: this.options.previewHighlight }));
      this.wwEditor = new WysiwygEditor(this.eventEmitter, {
        toDOMAdaptor: wwToDOMAdaptor,
        useCommandShortcut,
        htmlSchemaMap,
        linkAttributes,
        wwPlugins,
        wwNodeViews
      });
      this.convertor = new Convertor(this.wwEditor.getSchema(), __assign$1(__assign$1({}, toMarkdownRenderers), customMarkdownRenderer), getHTMLRenderConvertors(linkAttributes, rendererOptions.customHTMLRenderer), this.eventEmitter);
      this.setMinHeight(this.options.minHeight);
      this.setHeight(this.options.height);
      this.setMarkdown(this.options.initialValue, false);
      if (this.options.placeholder) {
        this.setPlaceholder(this.options.placeholder);
      }
      if (!this.options.initialValue) {
        this.setHTML(this.initialHTML, false);
      }
      this.commandManager = new CommandManager(this.eventEmitter, this.mdEditor.commands, this.wwEditor.commands, function() {
        return _this.mode;
      });
      if (this.options.usageStatistics) {
        sendHostName();
      }
      this.scrollSync = new ScrollSync(this.mdEditor, this.preview, this.eventEmitter);
      this.addInitEvent();
      this.addInitCommand(mdCommands, wwCommands);
      buildQuery(this);
      if (this.options.hooks) {
        forEachOwnProperties_1(this.options.hooks, function(fn, key) {
          return _this.addHook(key, fn);
        });
      }
      if (this.options.events) {
        forEachOwnProperties_1(this.options.events, function(fn, key) {
          return _this.on(key, fn);
        });
      }
      this.eventEmitter.emit("load", this);
      this.moveCursorToStart(this.options.autofocus);
    }
    ToastUIEditorCore2.prototype.addInitEvent = function() {
      var _this = this;
      this.on("needChangeMode", this.changeMode.bind(this));
      this.on("loadUI", function() {
        if (_this.height !== "auto") {
          var minHeight = Math.min(parseInt(_this.minHeight, 10), parseInt(_this.height, 10) - 75) + "px";
          _this.setMinHeight(minHeight);
        }
      });
      addDefaultImageBlobHook(this.eventEmitter);
    };
    ToastUIEditorCore2.prototype.addInitCommand = function(mdCommands, wwCommands) {
      var _this = this;
      var addPluginCommands = function(type, commandMap) {
        Object.keys(commandMap).forEach(function(name) {
          _this.addCommand(type, name, commandMap[name]);
        });
      };
      this.addCommand("markdown", "toggleScrollSync", function(payload) {
        _this.eventEmitter.emit("toggleScrollSync", payload.active);
        return true;
      });
      addPluginCommands("markdown", mdCommands);
      addPluginCommands("wysiwyg", wwCommands);
    };
    ToastUIEditorCore2.prototype.getCurrentModeEditor = function() {
      return this.isMarkdownMode() ? this.mdEditor : this.wwEditor;
    };
    ToastUIEditorCore2.factory = function(options) {
      return options.viewer ? new ToastUIEditorViewer(options) : new ToastUIEditorCore2(options);
    };
    ToastUIEditorCore2.setLanguage = function(code2, data) {
      i18n.setLanguage(code2, data);
    };
    ToastUIEditorCore2.prototype.changePreviewStyle = function(style) {
      if (this.mdPreviewStyle !== style) {
        this.mdPreviewStyle = style;
        this.eventEmitter.emit("changePreviewStyle", style);
      }
    };
    ToastUIEditorCore2.prototype.exec = function(name, payload) {
      this.commandManager.exec(name, payload);
    };
    ToastUIEditorCore2.prototype.addCommand = function(type, name, command) {
      var _this = this;
      var commandHoc = function(paylaod) {
        if (paylaod === void 0) {
          paylaod = {};
        }
        var view = (type === "markdown" ? _this.mdEditor : _this.wwEditor).view;
        command(paylaod, view.state, view.dispatch, view);
      };
      this.commandManager.addCommand(type, name, commandHoc);
    };
    ToastUIEditorCore2.prototype.on = function(type, handler) {
      this.eventEmitter.listen(type, handler);
    };
    ToastUIEditorCore2.prototype.off = function(type) {
      this.eventEmitter.removeEventHandler(type);
    };
    ToastUIEditorCore2.prototype.addHook = function(type, handler) {
      this.eventEmitter.removeEventHandler(type);
      this.eventEmitter.listen(type, handler);
    };
    ToastUIEditorCore2.prototype.removeHook = function(type) {
      this.eventEmitter.removeEventHandler(type);
    };
    ToastUIEditorCore2.prototype.focus = function() {
      this.getCurrentModeEditor().focus();
    };
    ToastUIEditorCore2.prototype.blur = function() {
      this.getCurrentModeEditor().blur();
    };
    ToastUIEditorCore2.prototype.moveCursorToEnd = function(focus) {
      if (focus === void 0) {
        focus = true;
      }
      this.getCurrentModeEditor().moveCursorToEnd(focus);
    };
    ToastUIEditorCore2.prototype.moveCursorToStart = function(focus) {
      if (focus === void 0) {
        focus = true;
      }
      this.getCurrentModeEditor().moveCursorToStart(focus);
    };
    ToastUIEditorCore2.prototype.setMarkdown = function(markdown, cursorToEnd) {
      if (markdown === void 0) {
        markdown = "";
      }
      if (cursorToEnd === void 0) {
        cursorToEnd = true;
      }
      this.mdEditor.setMarkdown(markdown, cursorToEnd);
      if (this.isWysiwygMode()) {
        var mdNode = this.toastMark.getRootNode();
        var wwNode = this.convertor.toWysiwygModel(mdNode);
        this.wwEditor.setModel(wwNode, cursorToEnd);
      }
    };
    ToastUIEditorCore2.prototype.setHTML = function(html2, cursorToEnd) {
      if (html2 === void 0) {
        html2 = "";
      }
      if (cursorToEnd === void 0) {
        cursorToEnd = true;
      }
      var container = document.createElement("div");
      container.innerHTML = replaceBRWithEmptyBlock(html2);
      var wwNode = DOMParser.fromSchema(this.wwEditor.schema).parse(container);
      if (this.isMarkdownMode()) {
        this.mdEditor.setMarkdown(this.convertor.toMarkdownText(wwNode), cursorToEnd);
      } else {
        this.wwEditor.setModel(wwNode, cursorToEnd);
      }
    };
    ToastUIEditorCore2.prototype.getMarkdown = function() {
      if (this.isMarkdownMode()) {
        return this.mdEditor.getMarkdown();
      }
      return this.convertor.toMarkdownText(this.wwEditor.getModel());
    };
    ToastUIEditorCore2.prototype.getHTML = function() {
      var _this = this;
      this.eventEmitter.holdEventInvoke(function() {
        if (_this.isMarkdownMode()) {
          var mdNode = _this.toastMark.getRootNode();
          var wwNode = _this.convertor.toWysiwygModel(mdNode);
          _this.wwEditor.setModel(wwNode);
        }
      });
      var html2 = removeProseMirrorHackNodes(this.wwEditor.view.dom.innerHTML);
      if (this.placeholder) {
        var rePlaceholder = new RegExp('<span class="placeholder[^>]+>' + this.placeholder + "</span>", "i");
        return html2.replace(rePlaceholder, "");
      }
      return html2;
    };
    ToastUIEditorCore2.prototype.insertText = function(text2) {
      this.getCurrentModeEditor().replaceSelection(text2);
    };
    ToastUIEditorCore2.prototype.setSelection = function(start, end) {
      this.getCurrentModeEditor().setSelection(start, end);
    };
    ToastUIEditorCore2.prototype.replaceSelection = function(text2, start, end) {
      this.getCurrentModeEditor().replaceSelection(text2, start, end);
    };
    ToastUIEditorCore2.prototype.deleteSelection = function(start, end) {
      this.getCurrentModeEditor().deleteSelection(start, end);
    };
    ToastUIEditorCore2.prototype.getSelectedText = function(start, end) {
      return this.getCurrentModeEditor().getSelectedText(start, end);
    };
    ToastUIEditorCore2.prototype.getRangeInfoOfNode = function(pos) {
      return this.getCurrentModeEditor().getRangeInfoOfNode(pos);
    };
    ToastUIEditorCore2.prototype.addWidget = function(node, style, pos) {
      this.getCurrentModeEditor().addWidget(node, style, pos);
    };
    ToastUIEditorCore2.prototype.replaceWithWidget = function(start, end, text2) {
      this.getCurrentModeEditor().replaceWithWidget(start, end, text2);
    };
    ToastUIEditorCore2.prototype.setHeight = function(height) {
      var el2 = this.options.el;
      if (isString_1(height)) {
        if (height === "auto") {
          addClass_1(el2, "auto-height");
        } else {
          removeClass_1(el2, "auto-height");
        }
        this.setMinHeight(this.getMinHeight());
      }
      css_1(el2, { height });
      this.height = height;
    };
    ToastUIEditorCore2.prototype.getHeight = function() {
      return this.height;
    };
    ToastUIEditorCore2.prototype.setMinHeight = function(minHeight) {
      if (minHeight !== this.minHeight) {
        var height = this.height || this.options.height;
        if (height !== "auto" && this.options.el.querySelector("." + cls("main"))) {
          minHeight = Math.min(parseInt(minHeight, 10), parseInt(height, 10) - 75) + "px";
        }
        var minHeightNum = parseInt(minHeight, 10);
        this.minHeight = minHeight;
        this.wwEditor.setMinHeight(minHeightNum);
        this.mdEditor.setMinHeight(minHeightNum);
        this.preview.setMinHeight(minHeightNum);
      }
    };
    ToastUIEditorCore2.prototype.getMinHeight = function() {
      return this.minHeight;
    };
    ToastUIEditorCore2.prototype.isMarkdownMode = function() {
      return this.mode === "markdown";
    };
    ToastUIEditorCore2.prototype.isWysiwygMode = function() {
      return this.mode === "wysiwyg";
    };
    ToastUIEditorCore2.prototype.isViewer = function() {
      return false;
    };
    ToastUIEditorCore2.prototype.getCurrentPreviewStyle = function() {
      return this.mdPreviewStyle;
    };
    ToastUIEditorCore2.prototype.changeMode = function(mode, withoutFocus) {
      if (this.mode === mode) {
        return;
      }
      this.mode = mode;
      if (this.isWysiwygMode()) {
        var mdNode = this.toastMark.getRootNode();
        var wwNode = this.convertor.toWysiwygModel(mdNode);
        this.wwEditor.setModel(wwNode);
      } else {
        var wwNode = this.wwEditor.getModel();
        this.mdEditor.setMarkdown(this.convertor.toMarkdownText(wwNode), !withoutFocus);
      }
      this.eventEmitter.emit("removePopupWidget");
      this.eventEmitter.emit("changeMode", mode);
      if (!withoutFocus) {
        var pos = this.convertor.getMappedPos();
        this.focus();
        if (this.isWysiwygMode() && isNumber_1(pos)) {
          this.wwEditor.setSelection(pos);
        } else if (Array.isArray(pos)) {
          this.mdEditor.setSelection(pos);
        }
      }
    };
    ToastUIEditorCore2.prototype.destroy = function() {
      var _this = this;
      this.wwEditor.destroy();
      this.mdEditor.destroy();
      this.preview.destroy();
      this.scrollSync.destroy();
      this.eventEmitter.emit("destroy");
      this.eventEmitter.getEvents().forEach(function(_, type) {
        return _this.off(type);
      });
    };
    ToastUIEditorCore2.prototype.hide = function() {
      this.eventEmitter.emit("hide");
    };
    ToastUIEditorCore2.prototype.show = function() {
      this.eventEmitter.emit("show");
    };
    ToastUIEditorCore2.prototype.setScrollTop = function(value) {
      this.getCurrentModeEditor().setScrollTop(value);
    };
    ToastUIEditorCore2.prototype.getScrollTop = function() {
      return this.getCurrentModeEditor().getScrollTop();
    };
    ToastUIEditorCore2.prototype.reset = function() {
      this.wwEditor.setModel([]);
      this.mdEditor.setMarkdown("");
    };
    ToastUIEditorCore2.prototype.getSelection = function() {
      return this.getCurrentModeEditor().getSelection();
    };
    ToastUIEditorCore2.prototype.setPlaceholder = function(placeholder2) {
      this.placeholder = placeholder2;
      this.mdEditor.setPlaceholder(placeholder2);
      this.wwEditor.setPlaceholder(placeholder2);
    };
    ToastUIEditorCore2.prototype.getEditorElements = function() {
      return {
        mdEditor: this.mdEditor.getElement(),
        mdPreview: this.preview.getElement(),
        wwEditor: this.wwEditor.getElement()
      };
    };
    ToastUIEditorCore2.prototype.convertPosToMatchEditorMode = function(start, end, mode) {
      var _a, _b;
      if (end === void 0) {
        end = start;
      }
      if (mode === void 0) {
        mode = this.mode;
      }
      var doc3 = this.mdEditor.view.state.doc;
      var isFromArray = Array.isArray(start);
      var isToArray = Array.isArray(end);
      var convertedFrom = start;
      var convertedTo = end;
      if (isFromArray !== isToArray) {
        throw new Error("Types of arguments must be same");
      }
      if (mode === "markdown" && !isFromArray && !isToArray) {
        _a = getEditorToMdPos(doc3, start, end), convertedFrom = _a[0], convertedTo = _a[1];
      } else if (mode === "wysiwyg" && isFromArray && isToArray) {
        _b = getMdToEditorPos(doc3, start, end), convertedFrom = _b[0], convertedTo = _b[1];
      }
      return [convertedFrom, convertedTo];
    };
    return ToastUIEditorCore2;
  })()
);
function html$1(n) {
  for (var l, e, s = arguments, t = 1, r = "", u = "", a = [0], c = function(n2) {
    t === 1 && (n2 || (r = r.replace(/^\s*\n\s*|\s*\n\s*$/g, ""))) ? a.push(n2 ? s[n2] : r) : t === 3 && (n2 || r) ? (a[1] = n2 ? s[n2] : r, t = 2) : t === 2 && r === "..." && n2 ? a[2] = assign(a[2] || {}, s[n2]) : t === 2 && r && !n2 ? (a[2] = a[2] || {})[r] = true : t >= 5 && (t === 5 ? ((a[2] = a[2] || {})[e] = n2 ? r ? r + s[n2] : s[n2] : r, t = 6) : (n2 || r) && (a[2][e] += n2 ? r + s[n2] : r)), r = "";
  }, h2 = 0; h2 < n.length; h2++) {
    h2 && (t === 1 && c(), c(h2));
    for (let i = 0; i < n[h2].length; i++)
      l = n[h2][i], t === 1 ? l === "<" ? (c(), a = [a, "", null], t = 3) : r += l : t === 4 ? r === "--" && l === ">" ? (t = 1, r = "") : r = l + r[0] : u ? l === u ? u = "" : r += l : l === '"' || l === "'" ? u = l : l === ">" ? (c(), t = 1) : t && (l === "=" ? (t = 5, e = r, r = "") : l === "/" && (t < 5 || n[h2][i + 1] === ">") ? (c(), t === 3 && (a = a[0]), t = a, (a = a[0]).push(this.apply(null, t.slice(1))), t = 0) : l === " " || l === "	" || l === "\n" || l === "\r" ? (c(), t = 2) : r += l), t === 3 && r === "!--" && (t = 4, a = a[0]);
  }
  return c(), a.length > 2 ? a.slice(1) : a[1];
}
function isBoolean(obj) {
  return typeof obj === "boolean" || obj instanceof Boolean;
}
var isBoolean_1 = isBoolean;
var VNodeWalker = (
  /** @class */
  (function() {
    function VNodeWalker2(current) {
      this.current = current;
      this.root = current;
      this.entering = true;
    }
    VNodeWalker2.prototype.walk = function() {
      var _a = this, entering = _a.entering, cur = _a.current;
      if (!cur) {
        return null;
      }
      if (entering) {
        if (cur.firstChild) {
          this.current = cur.firstChild;
          this.entering = true;
        } else {
          this.entering = false;
        }
      } else if (cur === this.root) {
        this.current = null;
      } else if (cur.next) {
        this.current = cur.next;
        this.entering = true;
      } else {
        this.current = cur.parent;
        this.entering = false;
      }
      return { vnode: cur, entering };
    };
    return VNodeWalker2;
  })()
);
var VNode = (
  /** @class */
  (function() {
    function VNode2(type, props, children) {
      this.parent = null;
      this.old = null;
      this.firstChild = null;
      this.next = null;
      this.skip = false;
      this.type = type;
      this.props = props;
      this.children = children;
      this.props.children = children;
      if (props.ref) {
        this.ref = props.ref;
        delete props.ref;
      }
      if (props.key) {
        this.key = props.key;
        delete props.key;
      }
    }
    VNode2.prototype.walker = function() {
      return new VNodeWalker(this);
    };
    VNode2.removalNodes = [];
    return VNode2;
  })()
);
function createTextNode(text2) {
  return new VNode("TEXT_NODE", { nodeValue: text2 }, []);
}
function excludeUnnecessaryChild(child, flatted) {
  var vnode = child;
  if (isBoolean_1(child) || child == null) {
    vnode = null;
  } else if (isString_1(child) || isNumber_1(child)) {
    vnode = createTextNode(String(child));
  }
  if (vnode) {
    flatted.push(vnode);
  }
}
function h(type, props) {
  var children = [];
  for (var _i = 2; _i < arguments.length; _i++) {
    children[_i - 2] = arguments[_i];
  }
  var flatted = [];
  children.forEach(function(child) {
    if (Array.isArray(child)) {
      child.forEach(function(vnode) {
        excludeUnnecessaryChild(vnode, flatted);
      });
    } else {
      excludeUnnecessaryChild(child, flatted);
    }
  });
  return new VNode(type, props || {}, flatted);
}
var html = html$1.bind(h);
function isObject(obj) {
  return obj === Object(obj);
}
var isObject_1 = isObject;
function createNode(vnode) {
  var node;
  if (vnode.type === "TEXT_NODE") {
    node = document.createTextNode(vnode.props.nodeValue);
  } else {
    node = document.createElement(vnode.type);
    setProps(node, {}, vnode.props);
  }
  return node;
}
function removeNode(vnode, parentNode2) {
  if (vnode.node) {
    parentNode2.removeChild(vnode.node);
  } else {
    removeNode(vnode.firstChild, parentNode2);
  }
}
function innerDiff(node, prevProps, nextProps) {
  Object.keys(prevProps).forEach(function(propName) {
    if (/^on/.test(propName)) {
      if (!nextProps[propName] || prevProps[propName] !== nextProps[propName]) {
        var eventName = propName.slice(2).toLowerCase();
        node.removeEventListener(eventName, prevProps[propName]);
      }
    } else if (propName !== "children" && !nextProps[propName] && !isTextNode(node)) {
      node.removeAttribute(propName);
    }
  });
  setProps(node, prevProps, nextProps, function(propName) {
    return !shallowEqual(prevProps[propName], nextProps[propName]);
  });
}
var reNonDimension = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
function setProps(node, prevProps, props, condition) {
  Object.keys(props).forEach(function(propName) {
    if (!condition || condition(propName)) {
      if (/^on/.test(propName)) {
        var eventName = propName.slice(2).toLowerCase();
        node.addEventListener(eventName, props[propName]);
      } else if (propName === "nodeValue") {
        node[propName] = props[propName];
      } else if (propName === "style" && isObject_1(props[propName])) {
        setStyleProps(node, prevProps[propName], props[propName]);
      } else if (propName !== "children") {
        if (props[propName] === false) {
          node.removeAttribute(propName);
        } else {
          node.setAttribute(propName, props[propName]);
        }
      }
    }
  });
}
function setStyleProps(node, prevStyleProps, styleProps) {
  if (prevStyleProps) {
    Object.keys(prevStyleProps).forEach(function(styleProp) {
      node.style[styleProp] = "";
    });
  }
  Object.keys(styleProps).forEach(function(styleProp) {
    var value = styleProps[styleProp];
    node.style[styleProp] = isNumber_1(value) && !reNonDimension.test(styleProp) ? value + "px" : value;
  });
}
function commit(vnode) {
  VNode.removalNodes.forEach(function(removalNode) {
    return diff(removalNode);
  });
  if (vnode) {
    var next = void 0;
    var walker = vnode.walker();
    while (next = walker.walk()) {
      vnode = next.vnode;
      if (next.entering) {
        diff(vnode);
      } else if (isFunction_1(vnode.type)) {
        var comp2 = vnode.component;
        if (!vnode.old && comp2.mounted) {
          comp2.mounted();
        }
        if (vnode.old && comp2.updated) {
          var prevProps = comp2.prevProps || {};
          comp2.updated(prevProps);
        }
      }
    }
  }
}
function getParentNode(vnode) {
  var parent = vnode.parent;
  while (!parent.node) {
    parent = parent.parent;
  }
  return parent.node;
}
function diff(vnode) {
  if (!vnode || !vnode.parent) {
    return;
  }
  if (vnode.node) {
    var parentNode2 = getParentNode(vnode);
    if (vnode.effect === "A") {
      parentNode2.appendChild(vnode.node);
    } else if (vnode.effect === "U") {
      innerDiff(vnode.node, vnode.old.props, vnode.props);
    }
  }
  if (vnode.effect === "D") {
    var next = void 0;
    var walker = vnode.walker();
    while (next = walker.walk()) {
      vnode = next.vnode;
      if (!next.entering) {
        if (isFunction_1(vnode.type)) {
          var comp2 = vnode.component;
          if (comp2.beforeDestroy) {
            comp2.beforeDestroy();
          }
        } else {
          var parentNode2 = getParentNode(vnode);
          removeNode(vnode, parentNode2);
        }
      }
    }
  }
  if (vnode.ref) {
    if (vnode.component) {
      vnode.ref(vnode.component);
    } else if (vnode.node) {
      vnode.ref(vnode.node);
    }
  }
}
function createComponent(Comp, vnode) {
  var props = vnode.props, component = vnode.component;
  if (component) {
    component.prevProps = component.props;
    component.props = vnode.props;
    return component;
  }
  return new Comp(props);
}
function buildVNode(vnode) {
  var root = vnode;
  while (vnode && !vnode.skip) {
    if (isFunction_1(vnode.type)) {
      var instance = createComponent(vnode.type, vnode);
      instance.vnode = vnode;
      vnode.component = instance;
      vnode.props.children = vnode.children = [instance.render()];
      buildChildrenVNode(vnode);
    } else {
      if (!vnode.node) {
        vnode.node = createNode(vnode);
      }
      buildChildrenVNode(vnode);
    }
    if (vnode.firstChild) {
      vnode = vnode.firstChild;
    } else {
      while (vnode && vnode.parent && !vnode.next) {
        vnode = vnode.parent;
        if (vnode === root) {
          break;
        }
      }
      vnode = vnode.next;
    }
  }
}
function isSameType(old, vnode) {
  return old && vnode && vnode.type === old.type && (!vnode.key || vnode.key === old.key);
}
function buildChildrenVNode(parent) {
  var children = parent.children;
  var old = parent.old ? parent.old.firstChild : null;
  var prev = null;
  children.forEach(function(vnode, index2) {
    var sameType = isSameType(old, vnode);
    if (sameType) {
      vnode.old = old;
      vnode.parent = parent;
      vnode.node = old.node;
      vnode.component = old.component;
      vnode.effect = "U";
    }
    if (vnode && !sameType) {
      vnode.old = null;
      vnode.parent = parent;
      vnode.node = null;
      vnode.effect = "A";
    }
    if (old && !sameType) {
      VNode.removalNodes.push(old);
      old.effect = "D";
    }
    if (old) {
      old = old.next;
    }
    if (index2 === 0) {
      parent.firstChild = vnode;
    } else if (vnode) {
      prev.next = vnode;
    }
    prev = vnode;
  });
  var lastChild = last$1(children);
  if (!children.length) {
    while (old) {
      VNode.removalNodes.push(old);
      old.effect = "D";
      old = old.next;
    }
  }
  while (old && lastChild) {
    if (old && lastChild.old !== old) {
      VNode.removalNodes.push(old);
      old.effect = "D";
      old = old.next;
    }
  }
}
function destroy(vnode) {
  vnode.effect = "D";
  VNode.removalNodes = [vnode];
  commit();
  VNode.removalNodes = [];
}
function rerender(comp2) {
  var root = comp2.vnode;
  root.effect = "U";
  root.old = root;
  if (root.next) {
    root.next.skip = true;
  }
  VNode.removalNodes = [];
  buildVNode(root);
  commit(root);
  if (root.next) {
    root.next.skip = false;
  }
}
function render(container, vnode) {
  var root = new VNode(container.tagName.toLowerCase(), {}, [vnode]);
  root.node = container;
  VNode.removalNodes = [];
  buildVNode(root);
  commit(root);
  return function() {
    return destroy(root.firstChild);
  };
}
var Component = (
  /** @class */
  (function() {
    function Component2(props) {
      this.props = props;
      this.state = {};
      this.refs = {};
    }
    Component2.prototype.setState = function(state) {
      var newState = __assign$1(__assign$1({}, this.state), state);
      if (!shallowEqual(this.state, newState)) {
        this.state = newState;
        rerender(this);
      }
    };
    return Component2;
  })()
);
var Switch = (
  /** @class */
  (function(_super) {
    __extends$1(Switch2, _super);
    function Switch2(props) {
      var _this = _super.call(this, props) || this;
      _this.state = {
        hide: false
      };
      return _this;
    }
    Switch2.prototype.show = function() {
      this.setState({ hide: false });
    };
    Switch2.prototype.hide = function() {
      this.setState({ hide: true });
    };
    Switch2.prototype.render = function() {
      var _a = this.props, editorType = _a.editorType, eventEmitter = _a.eventEmitter;
      return html(templateObject_1$h || (templateObject_1$h = __makeTemplateObject(['\n      <div class="', '" style="display: ', '">\n        <div\n          class="tab-item', '"\n          onClick=', "\n        >\n          ", '\n        </div>\n        <div\n          class="tab-item', '"\n          onClick=', "\n        >\n          ", "\n        </div>\n      </div>\n    "], [
        '\n      <div class="',
        '" style="display: ',
        '">\n        <div\n          class="tab-item',
        '"\n          onClick=',
        "\n        >\n          ",
        '\n        </div>\n        <div\n          class="tab-item',
        '"\n          onClick=',
        "\n        >\n          ",
        "\n        </div>\n      </div>\n    "
      ])), cls("mode-switch"), this.state.hide ? "none" : "block", editorType === "markdown" ? " active" : "", function() {
        eventEmitter.emit("needChangeMode", "markdown");
      }, i18n.get("Markdown"), editorType === "wysiwyg" ? " active" : "", function() {
        eventEmitter.emit("needChangeMode", "wysiwyg");
      }, i18n.get("WYSIWYG"));
    };
    return Switch2;
  })(Component)
);
var templateObject_1$h;
function debounce$1(fn, delay) {
  var timer, args;
  delay = delay || 0;
  function debounced() {
    args = Array.prototype.slice.call(arguments);
    window.clearTimeout(timer);
    timer = window.setTimeout(function() {
      fn.apply(null, args);
    }, delay);
  }
  return debounced;
}
var debounce_1 = debounce$1;
var debounce = debounce_1;
function throttle$1(fn, interval) {
  var base2;
  var isLeading = true;
  var tick = function(_args) {
    fn.apply(null, _args);
    base2 = null;
  };
  var debounced, stamp, args;
  interval = interval || 0;
  debounced = debounce(tick, interval);
  function throttled() {
    args = Array.prototype.slice.call(arguments);
    if (isLeading) {
      tick(args);
      isLeading = false;
      return;
    }
    stamp = Number(/* @__PURE__ */ new Date());
    base2 = base2 || stamp;
    debounced(args);
    if (stamp - base2 >= interval) {
      tick(args);
    }
  }
  function reset() {
    isLeading = true;
    base2 = null;
  }
  throttled.reset = reset;
  return throttled;
}
var throttle_1 = throttle$1;
var MapShim = (function() {
  if (typeof Map !== "undefined") {
    return Map;
  }
  function getIndex(arr, key) {
    var result = -1;
    arr.some(function(entry, index2) {
      if (entry[0] === key) {
        result = index2;
        return true;
      }
      return false;
    });
    return result;
  }
  return (
    /** @class */
    (function() {
      function class_1() {
        this.__entries__ = [];
      }
      Object.defineProperty(class_1.prototype, "size", {
        /**
         * @returns {boolean}
         */
        get: function() {
          return this.__entries__.length;
        },
        enumerable: true,
        configurable: true
      });
      class_1.prototype.get = function(key) {
        var index2 = getIndex(this.__entries__, key);
        var entry = this.__entries__[index2];
        return entry && entry[1];
      };
      class_1.prototype.set = function(key, value) {
        var index2 = getIndex(this.__entries__, key);
        if (~index2) {
          this.__entries__[index2][1] = value;
        } else {
          this.__entries__.push([key, value]);
        }
      };
      class_1.prototype.delete = function(key) {
        var entries = this.__entries__;
        var index2 = getIndex(entries, key);
        if (~index2) {
          entries.splice(index2, 1);
        }
      };
      class_1.prototype.has = function(key) {
        return !!~getIndex(this.__entries__, key);
      };
      class_1.prototype.clear = function() {
        this.__entries__.splice(0);
      };
      class_1.prototype.forEach = function(callback, ctx) {
        if (ctx === void 0) {
          ctx = null;
        }
        for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
          var entry = _a[_i];
          callback.call(ctx, entry[1], entry[0]);
        }
      };
      return class_1;
    })()
  );
})();
var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && window.document === document;
var global$1 = (function() {
  if (typeof global !== "undefined" && global.Math === Math) {
    return global;
  }
  if (typeof self !== "undefined" && self.Math === Math) {
    return self;
  }
  if (typeof window !== "undefined" && window.Math === Math) {
    return window;
  }
  return Function("return this")();
})();
var requestAnimationFrame$1 = (function() {
  if (typeof requestAnimationFrame === "function") {
    return requestAnimationFrame.bind(global$1);
  }
  return function(callback) {
    return setTimeout(function() {
      return callback(Date.now());
    }, 1e3 / 60);
  };
})();
var trailingTimeout = 2;
function throttle(callback, delay) {
  var leadingCall = false, trailingCall = false, lastCallTime = 0;
  function resolvePending() {
    if (leadingCall) {
      leadingCall = false;
      callback();
    }
    if (trailingCall) {
      proxy();
    }
  }
  function timeoutCallback() {
    requestAnimationFrame$1(resolvePending);
  }
  function proxy() {
    var timeStamp = Date.now();
    if (leadingCall) {
      if (timeStamp - lastCallTime < trailingTimeout) {
        return;
      }
      trailingCall = true;
    } else {
      leadingCall = true;
      trailingCall = false;
      setTimeout(timeoutCallback, delay);
    }
    lastCallTime = timeStamp;
  }
  return proxy;
}
var REFRESH_DELAY = 20;
var transitionKeys = ["top", "right", "bottom", "left", "width", "height", "size", "weight"];
var mutationObserverSupported = typeof MutationObserver !== "undefined";
var ResizeObserverController = (
  /** @class */
  (function() {
    function ResizeObserverController2() {
      this.connected_ = false;
      this.mutationEventsAdded_ = false;
      this.mutationsObserver_ = null;
      this.observers_ = [];
      this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
      this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
    }
    ResizeObserverController2.prototype.addObserver = function(observer) {
      if (!~this.observers_.indexOf(observer)) {
        this.observers_.push(observer);
      }
      if (!this.connected_) {
        this.connect_();
      }
    };
    ResizeObserverController2.prototype.removeObserver = function(observer) {
      var observers2 = this.observers_;
      var index2 = observers2.indexOf(observer);
      if (~index2) {
        observers2.splice(index2, 1);
      }
      if (!observers2.length && this.connected_) {
        this.disconnect_();
      }
    };
    ResizeObserverController2.prototype.refresh = function() {
      var changesDetected = this.updateObservers_();
      if (changesDetected) {
        this.refresh();
      }
    };
    ResizeObserverController2.prototype.updateObservers_ = function() {
      var activeObservers = this.observers_.filter(function(observer) {
        return observer.gatherActive(), observer.hasActive();
      });
      activeObservers.forEach(function(observer) {
        return observer.broadcastActive();
      });
      return activeObservers.length > 0;
    };
    ResizeObserverController2.prototype.connect_ = function() {
      if (!isBrowser || this.connected_) {
        return;
      }
      document.addEventListener("transitionend", this.onTransitionEnd_);
      window.addEventListener("resize", this.refresh);
      if (mutationObserverSupported) {
        this.mutationsObserver_ = new MutationObserver(this.refresh);
        this.mutationsObserver_.observe(document, {
          attributes: true,
          childList: true,
          characterData: true,
          subtree: true
        });
      } else {
        document.addEventListener("DOMSubtreeModified", this.refresh);
        this.mutationEventsAdded_ = true;
      }
      this.connected_ = true;
    };
    ResizeObserverController2.prototype.disconnect_ = function() {
      if (!isBrowser || !this.connected_) {
        return;
      }
      document.removeEventListener("transitionend", this.onTransitionEnd_);
      window.removeEventListener("resize", this.refresh);
      if (this.mutationsObserver_) {
        this.mutationsObserver_.disconnect();
      }
      if (this.mutationEventsAdded_) {
        document.removeEventListener("DOMSubtreeModified", this.refresh);
      }
      this.mutationsObserver_ = null;
      this.mutationEventsAdded_ = false;
      this.connected_ = false;
    };
    ResizeObserverController2.prototype.onTransitionEnd_ = function(_a) {
      var _b = _a.propertyName, propertyName = _b === void 0 ? "" : _b;
      var isReflowProperty = transitionKeys.some(function(key) {
        return !!~propertyName.indexOf(key);
      });
      if (isReflowProperty) {
        this.refresh();
      }
    };
    ResizeObserverController2.getInstance = function() {
      if (!this.instance_) {
        this.instance_ = new ResizeObserverController2();
      }
      return this.instance_;
    };
    ResizeObserverController2.instance_ = null;
    return ResizeObserverController2;
  })()
);
var defineConfigurable = (function(target2, props) {
  for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
    var key = _a[_i];
    Object.defineProperty(target2, key, {
      value: props[key],
      enumerable: false,
      writable: false,
      configurable: true
    });
  }
  return target2;
});
var getWindowOf = (function(target2) {
  var ownerGlobal = target2 && target2.ownerDocument && target2.ownerDocument.defaultView;
  return ownerGlobal || global$1;
});
var emptyRect = createRectInit(0, 0, 0, 0);
function toFloat(value) {
  return parseFloat(value) || 0;
}
function getBordersSize(styles) {
  var positions = [];
  for (var _i = 1; _i < arguments.length; _i++) {
    positions[_i - 1] = arguments[_i];
  }
  return positions.reduce(function(size, position) {
    var value = styles["border-" + position + "-width"];
    return size + toFloat(value);
  }, 0);
}
function getPaddings(styles) {
  var positions = ["top", "right", "bottom", "left"];
  var paddings = {};
  for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
    var position = positions_1[_i];
    var value = styles["padding-" + position];
    paddings[position] = toFloat(value);
  }
  return paddings;
}
function getSVGContentRect(target2) {
  var bbox = target2.getBBox();
  return createRectInit(0, 0, bbox.width, bbox.height);
}
function getHTMLElementContentRect(target2) {
  var clientWidth = target2.clientWidth, clientHeight = target2.clientHeight;
  if (!clientWidth && !clientHeight) {
    return emptyRect;
  }
  var styles = getWindowOf(target2).getComputedStyle(target2);
  var paddings = getPaddings(styles);
  var horizPad = paddings.left + paddings.right;
  var vertPad = paddings.top + paddings.bottom;
  var width = toFloat(styles.width), height = toFloat(styles.height);
  if (styles.boxSizing === "border-box") {
    if (Math.round(width + horizPad) !== clientWidth) {
      width -= getBordersSize(styles, "left", "right") + horizPad;
    }
    if (Math.round(height + vertPad) !== clientHeight) {
      height -= getBordersSize(styles, "top", "bottom") + vertPad;
    }
  }
  if (!isDocumentElement(target2)) {
    var vertScrollbar = Math.round(width + horizPad) - clientWidth;
    var horizScrollbar = Math.round(height + vertPad) - clientHeight;
    if (Math.abs(vertScrollbar) !== 1) {
      width -= vertScrollbar;
    }
    if (Math.abs(horizScrollbar) !== 1) {
      height -= horizScrollbar;
    }
  }
  return createRectInit(paddings.left, paddings.top, width, height);
}
var isSVGGraphicsElement = (function() {
  if (typeof SVGGraphicsElement !== "undefined") {
    return function(target2) {
      return target2 instanceof getWindowOf(target2).SVGGraphicsElement;
    };
  }
  return function(target2) {
    return target2 instanceof getWindowOf(target2).SVGElement && typeof target2.getBBox === "function";
  };
})();
function isDocumentElement(target2) {
  return target2 === getWindowOf(target2).document.documentElement;
}
function getContentRect(target2) {
  if (!isBrowser) {
    return emptyRect;
  }
  if (isSVGGraphicsElement(target2)) {
    return getSVGContentRect(target2);
  }
  return getHTMLElementContentRect(target2);
}
function createReadOnlyRect(_a) {
  var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
  var Constr = typeof DOMRectReadOnly !== "undefined" ? DOMRectReadOnly : Object;
  var rect2 = Object.create(Constr.prototype);
  defineConfigurable(rect2, {
    x,
    y,
    width,
    height,
    top: y,
    right: x + width,
    bottom: height + y,
    left: x
  });
  return rect2;
}
function createRectInit(x, y, width, height) {
  return { x, y, width, height };
}
var ResizeObservation = (
  /** @class */
  (function() {
    function ResizeObservation2(target2) {
      this.broadcastWidth = 0;
      this.broadcastHeight = 0;
      this.contentRect_ = createRectInit(0, 0, 0, 0);
      this.target = target2;
    }
    ResizeObservation2.prototype.isActive = function() {
      var rect2 = getContentRect(this.target);
      this.contentRect_ = rect2;
      return rect2.width !== this.broadcastWidth || rect2.height !== this.broadcastHeight;
    };
    ResizeObservation2.prototype.broadcastRect = function() {
      var rect2 = this.contentRect_;
      this.broadcastWidth = rect2.width;
      this.broadcastHeight = rect2.height;
      return rect2;
    };
    return ResizeObservation2;
  })()
);
var ResizeObserverEntry = (
  /** @class */
  /* @__PURE__ */ (function() {
    function ResizeObserverEntry2(target2, rectInit) {
      var contentRect = createReadOnlyRect(rectInit);
      defineConfigurable(this, { target: target2, contentRect });
    }
    return ResizeObserverEntry2;
  })()
);
var ResizeObserverSPI = (
  /** @class */
  (function() {
    function ResizeObserverSPI2(callback, controller, callbackCtx) {
      this.activeObservations_ = [];
      this.observations_ = new MapShim();
      if (typeof callback !== "function") {
        throw new TypeError("The callback provided as parameter 1 is not a function.");
      }
      this.callback_ = callback;
      this.controller_ = controller;
      this.callbackCtx_ = callbackCtx;
    }
    ResizeObserverSPI2.prototype.observe = function(target2) {
      if (!arguments.length) {
        throw new TypeError("1 argument required, but only 0 present.");
      }
      if (typeof Element === "undefined" || !(Element instanceof Object)) {
        return;
      }
      if (!(target2 instanceof getWindowOf(target2).Element)) {
        throw new TypeError('parameter 1 is not of type "Element".');
      }
      var observations = this.observations_;
      if (observations.has(target2)) {
        return;
      }
      observations.set(target2, new ResizeObservation(target2));
      this.controller_.addObserver(this);
      this.controller_.refresh();
    };
    ResizeObserverSPI2.prototype.unobserve = function(target2) {
      if (!arguments.length) {
        throw new TypeError("1 argument required, but only 0 present.");
      }
      if (typeof Element === "undefined" || !(Element instanceof Object)) {
        return;
      }
      if (!(target2 instanceof getWindowOf(target2).Element)) {
        throw new TypeError('parameter 1 is not of type "Element".');
      }
      var observations = this.observations_;
      if (!observations.has(target2)) {
        return;
      }
      observations.delete(target2);
      if (!observations.size) {
        this.controller_.removeObserver(this);
      }
    };
    ResizeObserverSPI2.prototype.disconnect = function() {
      this.clearActive();
      this.observations_.clear();
      this.controller_.removeObserver(this);
    };
    ResizeObserverSPI2.prototype.gatherActive = function() {
      var _this = this;
      this.clearActive();
      this.observations_.forEach(function(observation) {
        if (observation.isActive()) {
          _this.activeObservations_.push(observation);
        }
      });
    };
    ResizeObserverSPI2.prototype.broadcastActive = function() {
      if (!this.hasActive()) {
        return;
      }
      var ctx = this.callbackCtx_;
      var entries = this.activeObservations_.map(function(observation) {
        return new ResizeObserverEntry(observation.target, observation.broadcastRect());
      });
      this.callback_.call(ctx, entries, ctx);
      this.clearActive();
    };
    ResizeObserverSPI2.prototype.clearActive = function() {
      this.activeObservations_.splice(0);
    };
    ResizeObserverSPI2.prototype.hasActive = function() {
      return this.activeObservations_.length > 0;
    };
    return ResizeObserverSPI2;
  })()
);
var observers = typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : new MapShim();
var ResizeObserver = (
  /** @class */
  /* @__PURE__ */ (function() {
    function ResizeObserver2(callback) {
      if (!(this instanceof ResizeObserver2)) {
        throw new TypeError("Cannot call a class as a function.");
      }
      if (!arguments.length) {
        throw new TypeError("1 argument required, but only 0 present.");
      }
      var controller = ResizeObserverController.getInstance();
      var observer = new ResizeObserverSPI(callback, controller, this);
      observers.set(this, observer);
    }
    return ResizeObserver2;
  })()
);
[
  "observe",
  "unobserve",
  "disconnect"
].forEach(function(method) {
  ResizeObserver.prototype[method] = function() {
    var _a;
    return (_a = observers.get(this))[method].apply(_a, arguments);
  };
});
var index = (function() {
  if (typeof global$1.ResizeObserver !== "undefined") {
    return global$1.ResizeObserver;
  }
  return ResizeObserver;
})();
var HeadingPopupBody = (
  /** @class */
  (function(_super) {
    __extends$1(HeadingPopupBody2, _super);
    function HeadingPopupBody2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    HeadingPopupBody2.prototype.execCommand = function(ev) {
      var el2 = closest(ev.target, "li");
      this.props.execCommand("heading", {
        level: Number(el2.getAttribute("data-level"))
      });
    };
    HeadingPopupBody2.prototype.render = function() {
      var _this = this;
      return html(templateObject_2$8 || (templateObject_2$8 = __makeTemplateObject(["\n      <ul\n        onClick=", '\n        aria-role="menu"\n        aria-label="', '"\n      >\n        ', '\n        <li data-type="Paragraph" aria-role="menuitem">\n          <div>', "</div>\n        </li>\n      </ul>\n    "], [
        "\n      <ul\n        onClick=",
        '\n        aria-role="menu"\n        aria-label="',
        '"\n      >\n        ',
        '\n        <li data-type="Paragraph" aria-role="menuitem">\n          <div>',
        "</div>\n        </li>\n      </ul>\n    "
      ])), function(ev) {
        return _this.execCommand(ev);
      }, i18n.get("Headings"), [1, 2, 3, 4, 5, 6].map(function(level) {
        return html(templateObject_1$g || (templateObject_1$g = __makeTemplateObject(['\n              <li data-level="', '" data-type="Heading" aria-role="menuitem">\n                <', ">", " ", "</$>\n              </li>\n            "], ['\n              <li data-level="', '" data-type="Heading" aria-role="menuitem">\n                <', ">", " ", "</$>\n              </li>\n            "])), level, "h" + level, i18n.get("Heading"), level);
      }), i18n.get("Paragraph"));
    };
    return HeadingPopupBody2;
  })(Component)
);
var templateObject_1$g;
var templateObject_2$8;
var Tabs = (
  /** @class */
  (function(_super) {
    __extends$1(Tabs2, _super);
    function Tabs2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    Tabs2.prototype.toggleTab = function(ev, activeTab) {
      this.props.onClick(ev, activeTab);
    };
    Tabs2.prototype.render = function() {
      var _this = this;
      return html(templateObject_2$7 || (templateObject_2$7 = __makeTemplateObject(['\n      <div class="', '" aria-role="tabpanel">\n        ', "\n      </div>\n    "], [
        '\n      <div class="',
        '" aria-role="tabpanel">\n        ',
        "\n      </div>\n    "
      ])), cls("tabs"), this.props.tabs.map(function(_a) {
        var name = _a.name, text2 = _a.text;
        var isActive = _this.props.activeTab === name;
        return html(templateObject_1$f || (templateObject_1$f = __makeTemplateObject(['\n            <div\n              class="tab-item', '"\n              onClick=', '\n              aria-role="tab"\n              aria-label="', '"\n              aria-selected="', '"\n              tabindex="', '"\n            >\n              ', "\n            </div>\n          "], ['\n            <div\n              class="tab-item', '"\n              onClick=', '\n              aria-role="tab"\n              aria-label="', '"\n              aria-selected="', '"\n              tabindex="', '"\n            >\n              ', "\n            </div>\n          "])), isActive ? " active" : "", function(ev) {
          return _this.toggleTab(ev, name);
        }, i18n.get(text2), isActive ? "true" : "false", isActive ? "0" : "-1", i18n.get(text2));
      }));
    };
    return Tabs2;
  })(Component)
);
var templateObject_1$f;
var templateObject_2$7;
var TYPE_UI = "ui";
var ImagePopupBody = (
  /** @class */
  (function(_super) {
    __extends$1(ImagePopupBody2, _super);
    function ImagePopupBody2(props) {
      var _this = _super.call(this, props) || this;
      _this.initialize = function(activeTab) {
        if (activeTab === void 0) {
          activeTab = "file";
        }
        var urlEl = _this.refs.url;
        urlEl.value = "";
        _this.refs.altText.value = "";
        _this.refs.file.value = "";
        removeClass_1(urlEl, "wrong");
        _this.setState({ activeTab, file: null, fileNameElClassName: "" });
      };
      _this.execCommand = function() {
        if (_this.state.activeTab === "file") {
          _this.emitAddImageBlob();
        } else {
          _this.emitAddImage();
        }
      };
      _this.toggleTab = function(_, activeTab) {
        if (activeTab !== _this.state.activeTab) {
          _this.initialize(activeTab);
        }
      };
      _this.showFileSelectBox = function() {
        _this.refs.file.click();
      };
      _this.changeFile = function(ev) {
        var files = ev.target.files;
        if (files === null || files === void 0 ? void 0 : files.length) {
          _this.setState({ file: files[0] });
        }
      };
      _this.state = { activeTab: "file", file: null, fileNameElClassName: "" };
      _this.tabs = [
        { name: "file", text: "File" },
        { name: "url", text: "URL" }
      ];
      return _this;
    }
    ImagePopupBody2.prototype.emitAddImageBlob = function() {
      var _this = this;
      var files = this.refs.file.files;
      var altTextEl = this.refs.altText;
      var fileNameElClassName = " wrong";
      if (files === null || files === void 0 ? void 0 : files.length) {
        fileNameElClassName = "";
        var imageFile = files.item(0);
        var hookCallback = function(url, text2) {
          return _this.props.execCommand("addImage", { imageUrl: url, altText: text2 || altTextEl.value });
        };
        this.props.eventEmitter.emit("addImageBlobHook", imageFile, hookCallback, TYPE_UI);
      }
      this.setState({ fileNameElClassName });
    };
    ImagePopupBody2.prototype.emitAddImage = function() {
      var imageUrlEl = this.refs.url;
      var altTextEl = this.refs.altText;
      var imageUrl = imageUrlEl.value;
      var altText = altTextEl.value || "image";
      removeClass_1(imageUrlEl, "wrong");
      if (!imageUrl.length) {
        addClass_1(imageUrlEl, "wrong");
        return;
      }
      if (imageUrl) {
        this.props.execCommand("addImage", { imageUrl, altText });
      }
    };
    ImagePopupBody2.prototype.preventSelectStart = function(ev) {
      ev.preventDefault();
    };
    ImagePopupBody2.prototype.updated = function() {
      if (!this.props.show) {
        this.initialize();
      }
    };
    ImagePopupBody2.prototype.render = function() {
      var _this = this;
      var _a = this.state, activeTab = _a.activeTab, file = _a.file, fileNameElClassName = _a.fileNameElClassName;
      return html(templateObject_1$e || (templateObject_1$e = __makeTemplateObject(['\n      <div aria-label="', '">\n        <', " tabs=", " activeTab=", " onClick=", ' />\n        <div style="display:', '">\n          <label for="toastuiImageUrlInput">', '</label>\n          <input\n            id="toastuiImageUrlInput"\n            type="text"\n            ref=', '\n          />\n        </div>\n        <div style="display:', ';position: relative;">\n          <label for="toastuiImageFileInput">', '</label>\n          <span\n            class="', "", '"\n            onClick=', "\n            onSelectstart=", "\n          >\n            ", '\n          </span>\n          <button\n            type="button"\n            class="', '"\n            onClick=', "\n          >\n            ", '\n          </button>\n          <input\n            id="toastuiImageFileInput"\n            type="file"\n            accept="image/*"\n            onChange=', "\n            ref=", '\n          />\n        </div>\n        <label for="toastuiAltTextInput">', '</label>\n        <input\n          id="toastuiAltTextInput"\n          type="text"\n          ref=', '\n        />\n        <div class="', '">\n          <button type="button" class="', '" onClick=', ">\n            ", '\n          </button>\n          <button type="button" class="', '" onClick=', ">\n            ", "\n          </button>\n        </div>\n      </div>\n    "], ['\n      <div aria-label="', '">\n        <', " tabs=", " activeTab=", " onClick=", ' />\n        <div style="display:', '">\n          <label for="toastuiImageUrlInput">', '</label>\n          <input\n            id="toastuiImageUrlInput"\n            type="text"\n            ref=', '\n          />\n        </div>\n        <div style="display:', ';position: relative;">\n          <label for="toastuiImageFileInput">', '</label>\n          <span\n            class="', "", '"\n            onClick=', "\n            onSelectstart=", "\n          >\n            ", '\n          </span>\n          <button\n            type="button"\n            class="', '"\n            onClick=', "\n          >\n            ", '\n          </button>\n          <input\n            id="toastuiImageFileInput"\n            type="file"\n            accept="image/*"\n            onChange=', "\n            ref=", '\n          />\n        </div>\n        <label for="toastuiAltTextInput">', '</label>\n        <input\n          id="toastuiAltTextInput"\n          type="text"\n          ref=', '\n        />\n        <div class="', '">\n          <button type="button" class="', '" onClick=', ">\n            ", '\n          </button>\n          <button type="button" class="', '" onClick=', ">\n            ", "\n          </button>\n        </div>\n      </div>\n    "])), i18n.get("Insert image"), Tabs, this.tabs, activeTab, this.toggleTab, activeTab === "url" ? "block" : "none", i18n.get("Image URL"), function(el2) {
        return _this.refs.url = el2;
      }, activeTab === "file" ? "block" : "none", i18n.get("Select image file"), cls("file-name"), file ? " has-file" : fileNameElClassName, this.showFileSelectBox, this.preventSelectStart, file ? file.name : i18n.get("No file"), cls("file-select-button"), this.showFileSelectBox, i18n.get("Choose a file"), this.changeFile, function(el2) {
        return _this.refs.file = el2;
      }, i18n.get("Description"), function(el2) {
        return _this.refs.altText = el2;
      }, cls("button-container"), cls("close-button"), this.props.hidePopup, i18n.get("Cancel"), cls("ok-button"), this.execCommand, i18n.get("OK"));
    };
    return ImagePopupBody2;
  })(Component)
);
var templateObject_1$e;
var LinkPopupBody = (
  /** @class */
  (function(_super) {
    __extends$1(LinkPopupBody2, _super);
    function LinkPopupBody2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.execCommand = function() {
        var linkUrlEl = _this.refs.url;
        var linkTextEl = _this.refs.text;
        removeClass_1(linkUrlEl, "wrong");
        removeClass_1(linkTextEl, "wrong");
        if (linkUrlEl.value.length < 1) {
          addClass_1(linkUrlEl, "wrong");
          return;
        }
        var checkLinkText = isUndefined_1(_this.props.initialValues.linkUrl);
        if (checkLinkText && linkTextEl.value.length < 1) {
          addClass_1(linkTextEl, "wrong");
          return;
        }
        _this.props.execCommand("addLink", {
          linkUrl: linkUrlEl.value,
          linkText: linkTextEl.value
        });
      };
      return _this;
    }
    LinkPopupBody2.prototype.initialize = function() {
      var _a = this.props.initialValues, linkUrl = _a.linkUrl, linkText = _a.linkText;
      var linkUrlEl = this.refs.url;
      var linkTextEl = this.refs.text;
      removeClass_1(linkUrlEl, "wrong");
      removeClass_1(linkTextEl, "wrong", "disabled");
      linkTextEl.removeAttribute("disabled");
      if (linkUrl) {
        addClass_1(linkTextEl, "disabled");
        linkTextEl.setAttribute("disabled", "disabled");
      }
      linkUrlEl.value = linkUrl || "";
      linkTextEl.value = linkText || "";
    };
    LinkPopupBody2.prototype.mounted = function() {
      this.initialize();
    };
    LinkPopupBody2.prototype.updated = function(prevProps) {
      if (!prevProps.show && this.props.show) {
        this.initialize();
      }
    };
    LinkPopupBody2.prototype.render = function() {
      var _this = this;
      return html(templateObject_1$d || (templateObject_1$d = __makeTemplateObject(['\n      <div aria-label="', '">\n        <label for="toastuiLinkUrlInput">', '</label>\n        <input\n          id="toastuiLinkUrlInput"\n          type="text"\n          ref=', '\n        />\n        <label for="toastuiLinkTextInput">', '</label>\n        <input\n          id="toastuiLinkTextInput"\n          type="text"\n          ref=', '\n        />\n        <div class="', '">\n          <button type="button" class="', '" onClick=', ">\n            ", '\n          </button>\n          <button type="button" class="', '" onClick=', ">\n            ", "\n          </button>\n        </div>\n      </div>\n    "], ['\n      <div aria-label="', '">\n        <label for="toastuiLinkUrlInput">', '</label>\n        <input\n          id="toastuiLinkUrlInput"\n          type="text"\n          ref=', '\n        />\n        <label for="toastuiLinkTextInput">', '</label>\n        <input\n          id="toastuiLinkTextInput"\n          type="text"\n          ref=', '\n        />\n        <div class="', '">\n          <button type="button" class="', '" onClick=', ">\n            ", '\n          </button>\n          <button type="button" class="', '" onClick=', ">\n            ", "\n          </button>\n        </div>\n      </div>\n    "])), i18n.get("Insert link"), i18n.get("URL"), function(el2) {
        return _this.refs.url = el2;
      }, i18n.get("Link text"), function(el2) {
        return _this.refs.text = el2;
      }, cls("button-container"), cls("close-button"), this.props.hidePopup, i18n.get("Cancel"), cls("ok-button"), this.execCommand, i18n.get("OK"));
    };
    return LinkPopupBody2;
  })(Component)
);
var templateObject_1$d;
var CELL_WIDTH = 20;
var CELL_HEIGHT = 20;
var MIN_ROW_INDEX = 5;
var MAX_ROW_INDEX = 14;
var MIN_COL_INDEX = 5;
var MAX_COL_INDEX = 9;
var MIN_ROW_SELECTION_INDEX = 1;
var MIN_COL_SELECTION_INDEX = 1;
var BORDER_WIDTH = 1;
var TablePopupBody = (
  /** @class */
  (function(_super) {
    __extends$1(TablePopupBody2, _super);
    function TablePopupBody2(props) {
      var _this = _super.call(this, props) || this;
      _this.extendSelectionRange = function(_a) {
        var pageX = _a.pageX, pageY = _a.pageY;
        var x = pageX - _this.offsetRect.left;
        var y = pageY - _this.offsetRect.top;
        var range2 = _this.getSelectionRangeByOffset(x, y);
        _this.setState(__assign$1({}, range2));
      };
      _this.execCommand = function() {
        _this.props.execCommand("addTable", {
          rowCount: _this.state.rowIdx + 1,
          columnCount: _this.state.colIdx + 1
        });
      };
      _this.state = {
        rowIdx: -1,
        colIdx: -1
      };
      return _this;
    }
    TablePopupBody2.prototype.getDescription = function() {
      return this.state.colIdx === -1 ? "" : this.state.colIdx + 1 + " x " + (this.state.rowIdx + 1);
    };
    TablePopupBody2.prototype.getBoundByRange = function(colIdx, rowIdx) {
      return {
        width: (colIdx + 1) * CELL_WIDTH,
        height: (rowIdx + 1) * CELL_HEIGHT
      };
    };
    TablePopupBody2.prototype.getRangeByOffset = function(x, y) {
      return {
        colIdx: Math.floor(x / CELL_WIDTH),
        rowIdx: Math.floor(y / CELL_HEIGHT)
      };
    };
    TablePopupBody2.prototype.getTableRange = function() {
      var _a = this.state, orgColIdx = _a.colIdx, orgRowIdx = _a.rowIdx;
      var colIdx = Math.max(orgColIdx, MIN_COL_INDEX);
      var rowIdx = Math.max(orgRowIdx, MIN_ROW_INDEX);
      if (orgColIdx >= MIN_COL_INDEX && colIdx < MAX_COL_INDEX) {
        colIdx += 1;
      }
      if (orgRowIdx >= MIN_ROW_INDEX && rowIdx < MAX_ROW_INDEX) {
        rowIdx += 1;
      }
      return { colIdx: colIdx + 1, rowIdx: rowIdx + 1 };
    };
    TablePopupBody2.prototype.getSelectionAreaBound = function() {
      var _a = this.getBoundByRange(this.state.colIdx, this.state.rowIdx), width = _a.width, height = _a.height;
      if (!width && !height) {
        return { display: "none" };
      }
      return { width: width - BORDER_WIDTH, height: height - BORDER_WIDTH, display: "block" };
    };
    TablePopupBody2.prototype.getSelectionRangeByOffset = function(x, y) {
      var range2 = this.getRangeByOffset(x, y);
      range2.rowIdx = Math.min(Math.max(range2.rowIdx, MIN_ROW_SELECTION_INDEX), MAX_ROW_INDEX);
      range2.colIdx = Math.min(Math.max(range2.colIdx, MIN_COL_SELECTION_INDEX), MAX_COL_INDEX);
      return range2;
    };
    TablePopupBody2.prototype.updated = function() {
      if (!this.props.show) {
        this.setState({ colIdx: -1, rowIdx: -1 });
      } else if (this.state.colIdx === -1 && this.state.rowIdx === -1) {
        var _a = this.refs.tableEl.getBoundingClientRect(), left = _a.left, top_1 = _a.top;
        this.offsetRect = {
          left: window.pageXOffset + left,
          top: window.pageYOffset + top_1
        };
      }
    };
    TablePopupBody2.prototype.createTableArea = function(tableRange) {
      var colIdx = tableRange.colIdx, rowIdx = tableRange.rowIdx;
      var rows = [];
      for (var i = 0; i < rowIdx; i += 1) {
        var cells = [];
        for (var j = 0; j < colIdx; j += 1) {
          var cellClassNames = "" + cls("table-cell") + (i > 0 ? "" : " header");
          cells.push(html(templateObject_1$c || (templateObject_1$c = __makeTemplateObject(['<div class="', '"></div>'], ['<div class="', '"></div>'])), cellClassNames));
        }
        rows.push(html(templateObject_2$6 || (templateObject_2$6 = __makeTemplateObject(['<div class="', '">', "</div>"], ['<div class="', '">', "</div>"])), cls("table-row"), cells));
      }
      return html(templateObject_3$2 || (templateObject_3$2 = __makeTemplateObject(['<div class="', '">', "</div>"], ['<div class="', '">', "</div>"])), cls("table"), rows);
    };
    TablePopupBody2.prototype.render = function() {
      var _this = this;
      var tableRange = this.getTableRange();
      var selectionAreaBound = this.getSelectionAreaBound();
      return html(templateObject_4$1 || (templateObject_4$1 = __makeTemplateObject(['\n      <div aria-label="', '">\n        <div\n          class="', '"\n          ref=', "\n          onMousemove=", "\n          onClick=", "\n        >\n          ", '\n          <div class="', '" style=', '></div>\n        </div>\n        <p class="', '">', "</p>\n      </div>\n    "], ['\n      <div aria-label="', '">\n        <div\n          class="', '"\n          ref=', "\n          onMousemove=", "\n          onClick=", "\n        >\n          ", '\n          <div class="', '" style=', '></div>\n        </div>\n        <p class="', '">', "</p>\n      </div>\n    "])), i18n.get("Insert table"), cls("table-selection"), function(el2) {
        return _this.refs.tableEl = el2;
      }, this.extendSelectionRange, this.execCommand, this.createTableArea(tableRange), cls("table-selection-layer"), selectionAreaBound, cls("table-description"), this.getDescription());
    };
    return TablePopupBody2;
  })(Component)
);
var templateObject_1$c;
var templateObject_2$6;
var templateObject_3$2;
var templateObject_4$1;
var CustomPopupBody = (
  /** @class */
  (function(_super) {
    __extends$1(CustomPopupBody2, _super);
    function CustomPopupBody2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    CustomPopupBody2.prototype.mounted = function() {
      this.refs.el.appendChild(this.props.body);
    };
    CustomPopupBody2.prototype.updated = function(prevProps) {
      this.refs.el.replaceChild(this.props.body, prevProps.body);
    };
    CustomPopupBody2.prototype.render = function() {
      var _this = this;
      return html(templateObject_1$b || (templateObject_1$b = __makeTemplateObject(["<div ref=", "></div>"], ["<div ref=", "></div>"])), function(el2) {
        return _this.refs.el = el2;
      });
    };
    return CustomPopupBody2;
  })(Component)
);
var templateObject_1$b;
function createToolbarItemInfo(type) {
  return isString_1(type) ? createDefaultToolbarItemInfo(type) : type;
}
function createScrollSyncToolbarItem() {
  var label = document.createElement("label");
  var checkbox = document.createElement("input");
  var toggleSwitch = document.createElement("span");
  label.className = "scroll-sync active";
  checkbox.type = "checkbox";
  checkbox.checked = true;
  toggleSwitch.className = "switch";
  var onMounted = function(execCommand2) {
    return checkbox.addEventListener("change", function(ev) {
      var checked = ev.target.checked;
      if (checked) {
        addClass_1(label, "active");
      } else {
        removeClass_1(label, "active");
      }
      execCommand2("toggleScrollSync", { active: checked });
    });
  };
  label.appendChild(checkbox);
  label.appendChild(toggleSwitch);
  return {
    name: "scrollSync",
    el: label,
    onMounted
  };
}
function createDefaultToolbarItemInfo(type) {
  var info;
  switch (type) {
    case "heading":
      info = {
        name: "heading",
        className: "heading",
        tooltip: i18n.get("Headings"),
        state: "heading"
      };
      break;
    case "bold":
      info = {
        name: "bold",
        className: "bold",
        command: "bold",
        tooltip: i18n.get("Bold"),
        state: "strong"
      };
      break;
    case "italic":
      info = {
        name: "italic",
        className: "italic",
        command: "italic",
        tooltip: i18n.get("Italic"),
        state: "emph"
      };
      break;
    case "strike":
      info = {
        name: "strike",
        className: "strike",
        command: "strike",
        tooltip: i18n.get("Strike"),
        state: "strike"
      };
      break;
    case "hr":
      info = {
        name: "hr",
        className: "hrline",
        command: "hr",
        tooltip: i18n.get("Line"),
        state: "thematicBreak"
      };
      break;
    case "quote":
      info = {
        name: "quote",
        className: "quote",
        command: "blockQuote",
        tooltip: i18n.get("Blockquote"),
        state: "blockQuote"
      };
      break;
    case "ul":
      info = {
        name: "ul",
        className: "bullet-list",
        command: "bulletList",
        tooltip: i18n.get("Unordered list"),
        state: "bulletList"
      };
      break;
    case "ol":
      info = {
        name: "ol",
        className: "ordered-list",
        command: "orderedList",
        tooltip: i18n.get("Ordered list"),
        state: "orderedList"
      };
      break;
    case "task":
      info = {
        name: "task",
        className: "task-list",
        command: "taskList",
        tooltip: i18n.get("Task"),
        state: "taskList"
      };
      break;
    case "table":
      info = {
        name: "table",
        className: "table",
        tooltip: i18n.get("Insert table"),
        state: "table"
      };
      break;
    case "image":
      info = {
        name: "image",
        className: "image",
        tooltip: i18n.get("Insert image")
      };
      break;
    case "link":
      info = {
        name: "link",
        className: "link",
        tooltip: i18n.get("Insert link")
      };
      break;
    case "code":
      info = {
        name: "code",
        className: "code",
        command: "code",
        tooltip: i18n.get("Code"),
        state: "code"
      };
      break;
    case "codeblock":
      info = {
        name: "codeblock",
        className: "codeblock",
        command: "codeBlock",
        tooltip: i18n.get("Insert CodeBlock"),
        state: "codeBlock"
      };
      break;
    case "indent":
      info = {
        name: "indent",
        className: "indent",
        command: "indent",
        tooltip: i18n.get("Indent"),
        state: "indent"
      };
      break;
    case "outdent":
      info = {
        name: "outdent",
        className: "outdent",
        command: "outdent",
        tooltip: i18n.get("Outdent"),
        state: "outdent"
      };
      break;
    case "scrollSync":
      info = createScrollSyncToolbarItem();
      break;
    case "more":
      info = {
        name: "more",
        className: "more",
        tooltip: i18n.get("More")
      };
      break;
  }
  if (info.name !== "scrollSync") {
    info.className += " " + cls("toolbar-icons");
  }
  return info;
}
function createPopupInfo(type, payload) {
  var el2 = payload.el, pos = payload.pos, popup = payload.popup, initialValues = payload.initialValues;
  switch (type) {
    case "heading":
      return {
        render: function(props) {
          return html(templateObject_1$a || (templateObject_1$a = __makeTemplateObject(["<", " ...", " />"], ["<", " ...", " />"])), HeadingPopupBody, props);
        },
        className: cls("popup-add-heading"),
        fromEl: el2,
        pos
      };
    case "link":
      return {
        render: function(props) {
          return html(templateObject_2$5 || (templateObject_2$5 = __makeTemplateObject(["<", " ...", " />"], ["<", " ...", " />"])), LinkPopupBody, props);
        },
        className: cls("popup-add-link"),
        fromEl: el2,
        pos,
        initialValues
      };
    case "image":
      return {
        render: function(props) {
          return html(templateObject_3$1 || (templateObject_3$1 = __makeTemplateObject(["<", " ...", " />"], ["<", " ...", " />"])), ImagePopupBody, props);
        },
        className: cls("popup-add-image"),
        fromEl: el2,
        pos
      };
    case "table":
      return {
        render: function(props) {
          return html(templateObject_4 || (templateObject_4 = __makeTemplateObject(["<", " ...", " />"], ["<", " ...", " />"])), TablePopupBody, props);
        },
        className: cls("popup-add-table"),
        fromEl: el2,
        pos
      };
    case "customPopupBody":
      if (!popup) {
        return null;
      }
      return __assign$1({ render: function(props) {
        return html(templateObject_5 || (templateObject_5 = __makeTemplateObject(["<", " ...", " body=", " />"], ["<", " ...", " body=", " />"])), CustomPopupBody, props, popup.body);
      }, fromEl: el2, pos }, popup);
    default:
      return null;
  }
}
function setGroupState(group) {
  group.hidden = group.length === group.filter(function(info) {
    return info.hidden;
  }).length;
}
function groupToolbarItems(toolbarItems, hiddenScrollSync) {
  var toggleScrollSyncState = function(item2) {
    item2.hidden = item2.name === "scrollSync" && hiddenScrollSync;
    return item2;
  };
  return toolbarItems.reduce(function(acc, item2) {
    acc.push(item2.map(function(type) {
      return toggleScrollSyncState(createToolbarItemInfo(type));
    }));
    var group = acc[(acc.length || 1) - 1];
    if (group) {
      setGroupState(group);
    }
    return acc;
  }, []);
}
function toggleScrollSync(toolbarItems, hiddenScrollSync) {
  toolbarItems.forEach(function(group) {
    group.forEach(function(item2) {
      return item2.hidden = item2.name === "scrollSync" && hiddenScrollSync;
    });
    setGroupState(group);
  });
}
var templateObject_1$a;
var templateObject_2$5;
var templateObject_3$1;
var templateObject_4;
var templateObject_5;
var MARGIN_FROM_RIGHT_SIDE = 20;
var Popup = (
  /** @class */
  (function(_super) {
    __extends$1(Popup2, _super);
    function Popup2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.handleMousedown = function(ev) {
        if (!closest(ev.target, "." + cls("popup")) && !closest(ev.target, _this.props.info.fromEl)) {
          _this.props.hidePopup();
        }
      };
      return _this;
    }
    Popup2.prototype.mounted = function() {
      document.addEventListener("mousedown", this.handleMousedown);
      this.props.eventEmitter.listen("closePopup", this.props.hidePopup);
    };
    Popup2.prototype.beforeDestroy = function() {
      document.removeEventListener("mousedown", this.handleMousedown);
    };
    Popup2.prototype.updated = function(prevProps) {
      var _a = this.props, show = _a.show, info = _a.info;
      if (show && info.pos && prevProps.show !== show) {
        var popupPos = __assign$1({}, info.pos);
        var offsetWidth = this.refs.el.offsetWidth;
        var toolbarEl = closest(this.refs.el, "." + cls("toolbar"));
        var toolbarOffsetWidth = toolbarEl.offsetWidth;
        if (popupPos.left + offsetWidth >= toolbarOffsetWidth) {
          popupPos.left = toolbarOffsetWidth - offsetWidth - MARGIN_FROM_RIGHT_SIDE;
        }
        if (!shallowEqual(this.state.popupPos, popupPos)) {
          this.setState({ popupPos });
        }
      }
    };
    Popup2.prototype.render = function() {
      var _this = this;
      var _a = this.props, info = _a.info, show = _a.show, hidePopup = _a.hidePopup, eventEmitter = _a.eventEmitter, execCommand2 = _a.execCommand;
      var _b = info || {}, _c = _b.className, className = _c === void 0 ? "" : _c, style = _b.style, render2 = _b.render, _d = _b.initialValues, initialValues = _d === void 0 ? {} : _d;
      var popupStyle = __assign$1(__assign$1({ display: show ? "block" : "none" }, style), this.state.popupPos);
      return html(templateObject_1$9 || (templateObject_1$9 = __makeTemplateObject(['\n      <div\n        class="', " ", '"\n        style=', "\n        ref=", '\n        aria-role="dialog"\n      >\n        <div class="', '">\n          ', "\n        </div>\n      </div>\n    "], ['\n      <div\n        class="', " ", '"\n        style=', "\n        ref=", '\n        aria-role="dialog"\n      >\n        <div class="', '">\n          ', "\n        </div>\n      </div>\n    "])), cls("popup"), className, popupStyle, function(el2) {
        return _this.refs.el = el2;
      }, cls("popup-body"), render2 && render2({ eventEmitter, show, hidePopup, execCommand: execCommand2, initialValues }));
    };
    return Popup2;
  })(Component)
);
var templateObject_1$9;
var TOOLTIP_INDENT = 6;
function connectHOC(WrappedComponent) {
  return (
    /** @class */
    (function(_super) {
      __extends$1(ButtonHOC, _super);
      function ButtonHOC(props) {
        var _this = _super.call(this, props) || this;
        _this.showTooltip = function(el2) {
          var tooltip = _this.props.item.tooltip;
          if (!_this.props.disabled && tooltip) {
            var bound = _this.getBound(el2);
            var left = bound.left + TOOLTIP_INDENT + "px";
            var top_1 = bound.top + TOOLTIP_INDENT + "px";
            css_1(_this.props.tooltipRef.current, { display: "block", left, top: top_1 });
            _this.props.tooltipRef.current.querySelector(".text").textContent = tooltip;
          }
        };
        _this.hideTooltip = function() {
          css_1(_this.props.tooltipRef.current, "display", "none");
        };
        _this.state = { active: false, disabled: props.disabled };
        _this.addEvent();
        return _this;
      }
      ButtonHOC.prototype.addEvent = function() {
        var _this = this;
        var _a = this.props, item2 = _a.item, eventEmitter = _a.eventEmitter;
        if (item2.state) {
          eventEmitter.listen("changeToolbarState", function(_a2) {
            var _b;
            var toolbarState = _a2.toolbarState;
            var _c = (_b = toolbarState[item2.state]) !== null && _b !== void 0 ? _b : {}, active = _c.active, disabled = _c.disabled;
            _this.setState({ active: !!active, disabled: disabled !== null && disabled !== void 0 ? disabled : _this.props.disabled });
          });
        }
      };
      ButtonHOC.prototype.getBound = function(el2) {
        var _a = getTotalOffset(el2, closest(el2, "." + cls("toolbar"))), offsetLeft = _a.offsetLeft, offsetTop = _a.offsetTop;
        return { left: offsetLeft, top: el2.offsetHeight + offsetTop };
      };
      ButtonHOC.prototype.render = function() {
        return html(templateObject_1$8 || (templateObject_1$8 = __makeTemplateObject(["\n        <", "\n          ...", "\n          active=", "\n          showTooltip=", "\n          hideTooltip=", "\n          getBound=", "\n          disabled=", "\n        />\n      "], ["\n        <", "\n          ...", "\n          active=", "\n          showTooltip=", "\n          hideTooltip=", "\n          getBound=", "\n          disabled=", "\n        />\n      "])), WrappedComponent, this.props, this.state.active, this.showTooltip, this.hideTooltip, this.getBound, this.state.disabled || this.props.disabled);
      };
      return ButtonHOC;
    })(Component)
  );
}
var templateObject_1$8;
var DEFAULT_WIDTH = 80;
var ToolbarButtonComp = (
  /** @class */
  (function(_super) {
    __extends$1(ToolbarButtonComp2, _super);
    function ToolbarButtonComp2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.showTooltip = function() {
        _this.props.showTooltip(_this.refs.el);
      };
      _this.execCommand = function() {
        var _a = _this.props, item2 = _a.item, execCommand2 = _a.execCommand, setPopupInfo = _a.setPopupInfo, getBound = _a.getBound, eventEmitter = _a.eventEmitter;
        var command = item2.command, name = item2.name, popup = item2.popup;
        if (command) {
          execCommand2(command);
        } else {
          var popupName = popup ? "customPopupBody" : name;
          var initialValues = eventEmitter.emit("query", "getPopupInitialValues", { popupName })[0];
          var info = createPopupInfo(popupName, {
            el: _this.refs.el,
            pos: getBound(_this.refs.el),
            popup,
            initialValues
          });
          if (info) {
            setPopupInfo(info);
          }
        }
      };
      return _this;
    }
    ToolbarButtonComp2.prototype.mounted = function() {
      this.setItemWidth();
    };
    ToolbarButtonComp2.prototype.updated = function(prevProps) {
      if (prevProps.item.name !== this.props.item.name) {
        this.setItemWidth();
      }
    };
    ToolbarButtonComp2.prototype.setItemWidth = function() {
      var _a = this.props, setItemWidth = _a.setItemWidth, item2 = _a.item;
      if (setItemWidth) {
        setItemWidth(item2.name, getOuterWidth(this.refs.el) + (item2.hidden ? DEFAULT_WIDTH : 0));
      }
    };
    ToolbarButtonComp2.prototype.render = function() {
      var _this = this;
      var _a = this.props, hideTooltip = _a.hideTooltip, disabled = _a.disabled, item2 = _a.item, active = _a.active;
      var style = __assign$1({ display: item2.hidden ? "none" : null }, item2.style);
      var classNames = "" + (item2.className || "") + (active ? " active" : "");
      return html(templateObject_1$7 || (templateObject_1$7 = __makeTemplateObject(["\n      <button\n        ref=", '\n        type="button"\n        style=', "\n        class=", "\n        onClick=", "\n        onMouseover=", "\n        onMouseout=", "\n        disabled=", "\n        aria-label=", "\n      >\n        ", "\n      </button>\n    "], ["\n      <button\n        ref=", '\n        type="button"\n        style=', "\n        class=", "\n        onClick=", "\n        onMouseover=", "\n        onMouseout=", "\n        disabled=", "\n        aria-label=", "\n      >\n        ", "\n      </button>\n    "])), function(el2) {
        return _this.refs.el = el2;
      }, style, classNames, this.execCommand, this.showTooltip, hideTooltip, !!disabled, item2.text || item2.tooltip || "", item2.text || "");
    };
    return ToolbarButtonComp2;
  })(Component)
);
var ToolbarButton = connectHOC(ToolbarButtonComp);
var templateObject_1$7;
var CustomToolbarItemComp = (
  /** @class */
  (function(_super) {
    __extends$1(CustomToolbarItemComp2, _super);
    function CustomToolbarItemComp2() {
      var _this = _super !== null && _super.apply(this, arguments) || this;
      _this.showTooltip = function() {
        _this.props.showTooltip(_this.refs.el);
      };
      _this.showPopup = function() {
        var info = createPopupInfo("customPopupBody", {
          el: _this.refs.el,
          pos: _this.props.getBound(_this.refs.el),
          popup: _this.props.item.popup
        });
        if (info) {
          _this.props.setPopupInfo(info);
        }
      };
      return _this;
    }
    CustomToolbarItemComp2.prototype.mounted = function() {
      var _a = this.props, setItemWidth = _a.setItemWidth, item2 = _a.item;
      this.refs.el.appendChild(item2.el);
      if (setItemWidth) {
        setItemWidth(item2.name, getOuterWidth(this.refs.el));
      }
      if (item2.onMounted) {
        item2.onMounted(this.props.execCommand);
      }
    };
    CustomToolbarItemComp2.prototype.updated = function(prevProps) {
      var _a;
      var _b = this.props, item2 = _b.item, active = _b.active, disabled = _b.disabled;
      if (prevProps.active !== active || prevProps.disabled !== disabled) {
        (_a = item2.onUpdated) === null || _a === void 0 ? void 0 : _a.call(item2, { active, disabled });
      }
    };
    CustomToolbarItemComp2.prototype.render = function() {
      var _this = this;
      var _a = this.props, disabled = _a.disabled, item2 = _a.item;
      var style = { display: item2.hidden ? "none" : "inline-block" };
      var getListener = function(listener) {
        return disabled ? null : listener;
      };
      return html(templateObject_1$6 || (templateObject_1$6 = __makeTemplateObject(["\n      <div\n        ref=", "\n        style=", "\n        class=", "\n        onClick=", "\n        onMouseover=", "\n        onMouseout=", "\n      ></div>\n    "], ["\n      <div\n        ref=", "\n        style=", "\n        class=", "\n        onClick=", "\n        onMouseover=", "\n        onMouseout=", "\n      ></div>\n    "])), function(el2) {
        return _this.refs.el = el2;
      }, style, cls("toolbar-item-wrapper"), getListener(this.showPopup), getListener(this.showTooltip), getListener(this.props.hideTooltip));
    };
    return CustomToolbarItemComp2;
  })(Component)
);
var CustomToolbarItem = connectHOC(CustomToolbarItemComp);
var templateObject_1$6;
var ToolbarGroup = (
  /** @class */
  (function(_super) {
    __extends$1(ToolbarGroup2, _super);
    function ToolbarGroup2() {
      return _super !== null && _super.apply(this, arguments) || this;
    }
    ToolbarGroup2.prototype.render = function() {
      var _this = this;
      var _a = this.props, group = _a.group, hiddenDivider = _a.hiddenDivider;
      var groupStyle = group.hidden ? { display: "none" } : null;
      var dividerStyle = hiddenDivider ? { display: "none" } : null;
      return html(templateObject_2$4 || (templateObject_2$4 = __makeTemplateObject(['\n      <div class="', '" style=', ">\n        ", '\n        <div class="', '" style=', "></div>\n      </div>\n    "], [
        '\n      <div class="',
        '" style=',
        ">\n        ",
        '\n        <div class="',
        '" style=',
        "></div>\n      </div>\n    "
      ])), cls("toolbar-group"), groupStyle, group.map(function(item2) {
        var Comp = item2.el ? CustomToolbarItem : ToolbarButton;
        return html(templateObject_1$5 || (templateObject_1$5 = __makeTemplateObject(["<", " key=", " ...", " item=", " />"], ["<", " key=", " ...", " item=", " />"])), Comp, item2.name, _this.props, item2);
      }), cls("toolbar-divider"), dividerStyle);
    };
    return ToolbarGroup2;
  })(Component)
);
var templateObject_1$5;
var templateObject_2$4;
var POPUP_INDENT = 4;
var DropdownToolbarButtonComp = (
  /** @class */
  (function(_super) {
    __extends$1(DropdownToolbarButtonComp2, _super);
    function DropdownToolbarButtonComp2(props) {
      var _this = _super.call(this, props) || this;
      _this.handleClickDocument = function(_a) {
        var target2 = _a.target;
        if (!closest(target2, "." + cls("dropdown-toolbar")) && !closest(target2, ".more")) {
          _this.setState({ showDropdown: false, dropdownPos: null });
        }
      };
      _this.showTooltip = function() {
        _this.props.showTooltip(_this.refs.el);
      };
      _this.state = { showDropdown: false, dropdownPos: null };
      return _this;
    }
    DropdownToolbarButtonComp2.prototype.getBound = function() {
      var rect2 = this.props.getBound(this.refs.el);
      rect2.top += POPUP_INDENT;
      return __assign$1(__assign$1({}, rect2), { left: null, right: 10 });
    };
    DropdownToolbarButtonComp2.prototype.mounted = function() {
      document.addEventListener("click", this.handleClickDocument);
    };
    DropdownToolbarButtonComp2.prototype.updated = function() {
      if (this.state.showDropdown && !this.state.dropdownPos) {
        this.setState({ dropdownPos: this.getBound() });
      }
    };
    DropdownToolbarButtonComp2.prototype.beforeDestroy = function() {
      document.removeEventListener("click", this.handleClickDocument);
    };
    DropdownToolbarButtonComp2.prototype.render = function() {
      var _this = this;
      var _a = this.state, showDropdown = _a.showDropdown, dropdownPos = _a.dropdownPos;
      var _b = this.props, disabled = _b.disabled, item2 = _b.item, items = _b.items, hideTooltip = _b.hideTooltip;
      var visibleItems = items.filter(function(dropdownItem) {
        return !dropdownItem.hidden;
      });
      var groupStyle = visibleItems.length ? null : { display: "none" };
      var dropdownStyle = showDropdown ? null : { display: "none" };
      return html(templateObject_2$3 || (templateObject_2$3 = __makeTemplateObject(['\n      <div class="', '" style=', ">\n        <button\n          ref=", '\n          type="button"\n          class=', "\n          onClick=", "\n          onMouseover=", "\n          onMouseout=", "\n          disabled=", '\n        ></button>\n        <div\n          class="', '"\n          style=', "\n          ref=", "\n        >\n          ", "\n        </div>\n      </div>\n    "], [
        '\n      <div class="',
        '" style=',
        ">\n        <button\n          ref=",
        '\n          type="button"\n          class=',
        "\n          onClick=",
        "\n          onMouseover=",
        "\n          onMouseout=",
        "\n          disabled=",
        '\n        ></button>\n        <div\n          class="',
        '"\n          style=',
        "\n          ref=",
        "\n        >\n          ",
        "\n        </div>\n      </div>\n    "
      ])), cls("toolbar-group"), groupStyle, function(el2) {
        return _this.refs.el = el2;
      }, item2.className, function() {
        return _this.setState({ showDropdown: true });
      }, this.showTooltip, hideTooltip, disabled, cls("dropdown-toolbar"), __assign$1(__assign$1({}, dropdownStyle), dropdownPos), function(el2) {
        return _this.refs.dropdownEl = el2;
      }, visibleItems.length ? visibleItems.map(function(group, index2) {
        var _a2;
        return html(templateObject_1$4 || (templateObject_1$4 = __makeTemplateObject(["\n                  <", "\n                    group=", "\n                    hiddenDivider=", "\n                    ...", "\n                  />\n                "], [
          "\n                  <",
          "\n                    group=",
          "\n                    hiddenDivider=",
          "\n                    ...",
          "\n                  />\n                "
        ])), ToolbarGroup, group, index2 === visibleItems.length - 1 || ((_a2 = visibleItems[index2 + 1]) === null || _a2 === void 0 ? void 0 : _a2.hidden), _this.props);
      }) : null);
    };
    return DropdownToolbarButtonComp2;
  })(Component)
);
var DropdownToolbarButton = connectHOC(DropdownToolbarButtonComp);
var templateObject_1$4;
var templateObject_2$3;
var INLINE_PADDING = 50;
var Toolbar = (
  /** @class */
  (function(_super) {
    __extends$1(Toolbar2, _super);
    function Toolbar2(props) {
      var _this = _super.call(this, props) || this;
      _this.toggleTab = function(_, activeTab) {
        var eventEmitter = _this.props.eventEmitter;
        if (_this.state.activeTab !== activeTab) {
          var event_1 = activeTab === "write" ? "changePreviewTabWrite" : "changePreviewTabPreview";
          eventEmitter.emit(event_1);
          _this.setState({ activeTab });
        }
      };
      _this.setItemWidth = function(name, width) {
        _this.itemWidthMap[name] = width;
      };
      _this.setPopupInfo = function(popupInfo) {
        _this.setState({ showPopup: true, popupInfo });
      };
      _this.openPopup = function(popupName, initialValues) {
        if (initialValues === void 0) {
          initialValues = {};
        }
        var el2 = _this.refs.el.querySelector("." + cls("toolbar-group") + " ." + popupName);
        if (el2) {
          var _a = getTotalOffset(el2, closest(el2, "." + cls("toolbar"))), offsetLeft = _a.offsetLeft, offsetTop = _a.offsetTop;
          var info = createPopupInfo(popupName, {
            el: el2,
            pos: { left: offsetLeft, top: el2.offsetHeight + offsetTop },
            initialValues
          });
          if (info) {
            _this.setPopupInfo(info);
          }
        }
      };
      _this.hidePopup = function() {
        if (_this.state.showPopup) {
          _this.setState({ showPopup: false });
        }
      };
      _this.execCommand = function(command, payload) {
        var eventEmitter = _this.props.eventEmitter;
        eventEmitter.emit("command", command, payload);
        _this.hidePopup();
      };
      _this.tabs = [
        { name: "write", text: "Write" },
        { name: "preview", text: "Preview" }
      ];
      _this.itemWidthMap = {};
      _this.initialItems = groupToolbarItems(props.toolbarItems || [], _this.hiddenScrollSync());
      _this.state = {
        items: _this.initialItems,
        dropdownItems: [],
        showPopup: false,
        popupInfo: {},
        activeTab: "write"
      };
      _this.tooltipRef = { current: null };
      _this.resizeObserver = new index(function() {
        return _this.handleResize();
      });
      _this.addEvent();
      return _this;
    }
    Toolbar2.prototype.insertToolbarItem = function(indexList, item2) {
      var groupIndex = indexList.groupIndex, itemIndex = indexList.itemIndex;
      var group = this.initialItems[groupIndex];
      item2 = createToolbarItemInfo(item2);
      if (group) {
        group.splice(itemIndex, 0, item2);
      } else {
        this.initialItems.push([item2]);
      }
      this.setState(this.classifyToolbarItems());
    };
    Toolbar2.prototype.removeToolbarItem = function(name) {
      var _this = this;
      forEachArray_1(this.initialItems, function(group) {
        var found2 = false;
        forEachArray_1(group, function(item2, index2) {
          if (item2.name === name) {
            found2 = true;
            group.splice(index2, 1);
            _this.setState(_this.classifyToolbarItems());
            return false;
          }
          return true;
        });
        return !found2;
      });
    };
    Toolbar2.prototype.addEvent = function() {
      var _this = this;
      var eventEmitter = this.props.eventEmitter;
      this.handleResize = throttle_1(function() {
        _this.setState({ items: _this.initialItems, dropdownItems: [] });
        _this.setState(_this.classifyToolbarItems());
      }, 200);
      eventEmitter.listen("openPopup", this.openPopup);
    };
    Toolbar2.prototype.appendTooltipToRoot = function() {
      var tooltip = '<div class="' + cls("tooltip") + '" style="display:none">\n        <div class="arrow"></div>\n        <span class="text"></span>\n      </div>';
      this.tooltipRef.current = createElementWith(tooltip, this.refs.el);
    };
    Toolbar2.prototype.hiddenScrollSync = function() {
      return this.props.editorType === "wysiwyg" || this.props.previewStyle === "tab";
    };
    Toolbar2.prototype.movePrevItemToDropdownToolbar = function(itemIndex, items, group, dropdownGroup) {
      var moveItem = function(targetGroup) {
        var item2 = targetGroup.pop();
        if (item2) {
          dropdownGroup.push(item2);
        }
      };
      if (itemIndex > 1) {
        moveItem(group);
      } else {
        var prevGroup = last$1(items);
        if (prevGroup) {
          moveItem(prevGroup);
        }
      }
    };
    Toolbar2.prototype.classifyToolbarItems = function() {
      var _this = this;
      var totalWidth = 0;
      var clientWidth = this.refs.el.clientWidth;
      var divider = this.refs.el.querySelector("." + cls("toolbar-divider"));
      var dividerWidth = divider ? getOuterWidth(divider) : 0;
      var items = [];
      var dropdownItems = [];
      var moved = false;
      this.initialItems.forEach(function(initialGroup, groupIndex) {
        var group = [];
        var dropdownGroup = [];
        initialGroup.forEach(function(item2, itemIndex) {
          if (!item2.hidden) {
            totalWidth += _this.itemWidthMap[item2.name];
            if (totalWidth > clientWidth - INLINE_PADDING) {
              if (!moved) {
                _this.movePrevItemToDropdownToolbar(itemIndex, items, group, dropdownGroup);
                moved = true;
              }
              dropdownGroup.push(item2);
            } else {
              group.push(item2);
            }
          }
        });
        if (group.length) {
          setGroupState(group);
          items.push(group);
        }
        if (dropdownGroup.length) {
          setGroupState(dropdownGroup);
          dropdownItems.push(dropdownGroup);
        }
        if (groupIndex < _this.state.items.length - 1) {
          totalWidth += dividerWidth;
        }
      });
      return { items, dropdownItems };
    };
    Toolbar2.prototype.mounted = function() {
      if (this.props.previewStyle === "tab") {
        this.props.eventEmitter.emit("changePreviewTabWrite", true);
      }
      this.setState(this.classifyToolbarItems());
      this.appendTooltipToRoot();
      this.resizeObserver.observe(this.refs.el);
    };
    Toolbar2.prototype.updated = function(prevProps) {
      var _a = this.props, editorType = _a.editorType, previewStyle = _a.previewStyle, eventEmitter = _a.eventEmitter;
      var changedStyle = previewStyle !== prevProps.previewStyle;
      var changedType = editorType !== prevProps.editorType;
      if (changedStyle || changedType) {
        toggleScrollSync(this.initialItems, this.hiddenScrollSync());
        var newState = this.classifyToolbarItems();
        if (changedStyle || previewStyle === "tab" && editorType === "markdown") {
          eventEmitter.emit("changePreviewTabWrite");
          newState.activeTab = "write";
        }
        this.setState(newState);
      }
    };
    Toolbar2.prototype.beforeDestroy = function() {
      window.removeEventListener("resize", this.handleResize);
      this.resizeObserver.disconnect();
      removeNode$1(this.tooltipRef.current);
    };
    Toolbar2.prototype.render = function() {
      var _this = this;
      var _a = this.props, previewStyle = _a.previewStyle, eventEmitter = _a.eventEmitter, editorType = _a.editorType;
      var _b = this.state, popupInfo = _b.popupInfo, showPopup = _b.showPopup, activeTab = _b.activeTab, items = _b.items, dropdownItems = _b.dropdownItems;
      var props = {
        eventEmitter,
        tooltipRef: this.tooltipRef,
        disabled: editorType === "markdown" && previewStyle === "tab" && activeTab === "preview",
        execCommand: this.execCommand,
        setPopupInfo: this.setPopupInfo
      };
      var toolbarStyle = previewStyle === "tab" ? { borderTopLeftRadius: 0 } : null;
      return html(templateObject_2$2 || (templateObject_2$2 = __makeTemplateObject(['\n      <div class="', '">\n        <div\n          class="', '"\n          style="display: ', '"\n        >\n          <', " tabs=", " activeTab=", " onClick=", ' />\n        </div>\n        <div\n          class="', '"\n          ref=', "\n          style=", "\n        >\n          ", "\n          <", "\n            item=", "\n            items=", "\n            ...", "\n          />\n        </div>\n        <", "\n          info=", "\n          show=", "\n          eventEmitter=", "\n          hidePopup=", "\n          execCommand=", "\n        />\n      </div>\n    "], [
        '\n      <div class="',
        '">\n        <div\n          class="',
        '"\n          style="display: ',
        '"\n        >\n          <',
        " tabs=",
        " activeTab=",
        " onClick=",
        ' />\n        </div>\n        <div\n          class="',
        '"\n          ref=',
        "\n          style=",
        "\n        >\n          ",
        "\n          <",
        "\n            item=",
        "\n            items=",
        "\n            ...",
        "\n          />\n        </div>\n        <",
        "\n          info=",
        "\n          show=",
        "\n          eventEmitter=",
        "\n          hidePopup=",
        "\n          execCommand=",
        "\n        />\n      </div>\n    "
      ])), cls("toolbar"), cls("md-tab-container"), editorType === "wysiwyg" || previewStyle === "vertical" ? "none" : "block", Tabs, this.tabs, activeTab, this.toggleTab, cls("defaultUI-toolbar"), function(el2) {
        return _this.refs.el = el2;
      }, toolbarStyle, items.map(function(group, index2) {
        var _a2;
        return html(templateObject_1$3 || (templateObject_1$3 = __makeTemplateObject(["\n              <", "\n                group=", "\n                hiddenDivider=", "\n                setItemWidth=", "\n                ...", "\n              />\n            "], ["\n              <", "\n                group=", "\n                hiddenDivider=", "\n                setItemWidth=", "\n                ...", "\n              />\n            "])), ToolbarGroup, group, index2 === items.length - 1 || ((_a2 = items[index2 + 1]) === null || _a2 === void 0 ? void 0 : _a2.hidden), _this.setItemWidth, props);
      }), DropdownToolbarButton, createToolbarItemInfo("more"), dropdownItems, props, Popup, popupInfo, showPopup, eventEmitter, this.hidePopup, this.execCommand);
    };
    return Toolbar2;
  })(Component)
);
var templateObject_1$3;
var templateObject_2$2;
var ContextMenu = (
  /** @class */
  (function(_super) {
    __extends$1(ContextMenu2, _super);
    function ContextMenu2(props) {
      var _this = _super.call(this, props) || this;
      _this.handleClickDocument = function(ev) {
        if (!closest(ev.target, "." + cls("context-menu"))) {
          _this.setState({ pos: null });
        }
      };
      _this.state = {
        pos: null,
        menuGroups: []
      };
      _this.addEvent();
      return _this;
    }
    ContextMenu2.prototype.addEvent = function() {
      var _this = this;
      this.props.eventEmitter.listen("contextmenu", function(_a) {
        var pos = _a.pos, menuGroups = _a.menuGroups;
        _this.setState({ pos, menuGroups });
      });
    };
    ContextMenu2.prototype.mounted = function() {
      document.addEventListener("click", this.handleClickDocument);
    };
    ContextMenu2.prototype.beforeDestroy = function() {
      document.removeEventListener("click", this.handleClickDocument);
    };
    ContextMenu2.prototype.getMenuGroupElements = function() {
      var _this = this;
      var _a = this.state, pos = _a.pos, menuGroups = _a.menuGroups;
      return pos ? menuGroups.reduce(function(acc, group) {
        var menuItem = [];
        group.forEach(function(_a2) {
          var label = _a2.label, _b = _a2.className, className = _b === void 0 ? false : _b, disabled = _a2.disabled, onClick = _a2.onClick;
          var handleClick = function() {
            if (!disabled) {
              onClick();
              _this.setState({ pos: null });
            }
          };
          menuItem.push(html(templateObject_1$2 || (templateObject_1$2 = __makeTemplateObject(["\n                <li\n                  onClick=", '\n                  class="menu-item', '"\n                  aria-role="menuitem"\n                >\n                  <span class="', '">', "</span>\n                </li>\n              "], ["\n                <li\n                  onClick=", '\n                  class="menu-item', '"\n                  aria-role="menuitem"\n                >\n                  <span class="', '">', "</span>\n                </li>\n              "])), handleClick, disabled ? " disabled" : "", className, label));
        });
        acc.push(html(templateObject_2$1 || (templateObject_2$1 = __makeTemplateObject(['<ul class="menu-group">\n              ', "\n            </ul>"], ['<ul class="menu-group">\n              ', "\n            </ul>"])), menuItem));
        return acc;
      }, []) : [];
    };
    ContextMenu2.prototype.render = function() {
      var style = __assign$1({ display: this.state.pos ? "block" : "none" }, this.state.pos);
      return html(templateObject_3 || (templateObject_3 = __makeTemplateObject(['<div class="', '" style=', ' aria-role="menu">\n      ', "\n    </div>"], ['<div class="', '" style=', ' aria-role="menu">\n      ', "\n    </div>"])), cls("context-menu"), style, this.getMenuGroupElements());
    };
    return ContextMenu2;
  })(Component)
);
var templateObject_1$2;
var templateObject_2$1;
var templateObject_3;
var Layout = (
  /** @class */
  (function(_super) {
    __extends$1(Layout2, _super);
    function Layout2(props) {
      var _this = _super.call(this, props) || this;
      _this.changeMode = function(editorType2) {
        if (editorType2 !== _this.state.editorType) {
          _this.setState({ editorType: editorType2 });
        }
      };
      _this.changePreviewStyle = function(previewStyle2) {
        if (previewStyle2 !== _this.state.previewStyle) {
          _this.setState({ previewStyle: previewStyle2 });
        }
      };
      _this.hide = function() {
        _this.setState({ hide: true });
      };
      _this.show = function() {
        _this.setState({ hide: false });
      };
      var editorType = props.editorType, previewStyle = props.previewStyle;
      _this.state = {
        editorType,
        previewStyle,
        hide: false
      };
      _this.addEvent();
      return _this;
    }
    Layout2.prototype.mounted = function() {
      var _a = this.props.slots, wwEditor = _a.wwEditor, mdEditor = _a.mdEditor, mdPreview = _a.mdPreview;
      this.refs.wwContainer.appendChild(wwEditor);
      this.refs.mdContainer.insertAdjacentElement("afterbegin", mdEditor);
      this.refs.mdContainer.appendChild(mdPreview);
    };
    Layout2.prototype.insertToolbarItem = function(indexList, item2) {
      this.toolbar.insertToolbarItem(indexList, item2);
    };
    Layout2.prototype.removeToolbarItem = function(name) {
      this.toolbar.removeToolbarItem(name);
    };
    Layout2.prototype.render = function() {
      var _this = this;
      var _a = this.props, eventEmitter = _a.eventEmitter, hideModeSwitch = _a.hideModeSwitch, toolbarItems = _a.toolbarItems, theme = _a.theme;
      var _b = this.state, hide = _b.hide, previewStyle = _b.previewStyle, editorType = _b.editorType;
      var displayClassName = hide ? " hidden" : "";
      var editorTypeClassName = cls(editorType === "markdown" ? "md-mode" : "ww-mode");
      var previewClassName = cls("md") + "-" + previewStyle + "-style";
      var themeClassName = cls([theme !== "light", theme + " "]);
      return html(templateObject_2 || (templateObject_2 = __makeTemplateObject(['\n      <div\n        class="', "", "", '"\n        ref=', "\n      >\n        <", "\n          ref=", "\n          eventEmitter=", "\n          previewStyle=", "\n          toolbarItems=", "\n          editorType=", '\n        />\n        <div\n          class="', " ", '"\n          ref=', '\n        >\n          <div class="', '">\n            <div\n              class="', " ", '"\n              ref=', '\n            >\n              <div class="', '"></div>\n            </div>\n            <div\n              class="', '"\n              ref=', "\n            />\n          </div>\n        </div>\n        ", "\n        <", " eventEmitter=", " />\n      </div>\n    "], [
        '\n      <div\n        class="',
        "",
        "",
        '"\n        ref=',
        "\n      >\n        <",
        "\n          ref=",
        "\n          eventEmitter=",
        "\n          previewStyle=",
        "\n          toolbarItems=",
        "\n          editorType=",
        '\n        />\n        <div\n          class="',
        " ",
        '"\n          ref=',
        '\n        >\n          <div class="',
        '">\n            <div\n              class="',
        " ",
        '"\n              ref=',
        '\n            >\n              <div class="',
        '"></div>\n            </div>\n            <div\n              class="',
        '"\n              ref=',
        "\n            />\n          </div>\n        </div>\n        ",
        "\n        <",
        " eventEmitter=",
        " />\n      </div>\n    "
      ])), themeClassName, cls("defaultUI"), displayClassName, function(el2) {
        return _this.refs.el = el2;
      }, Toolbar, function(toolbar) {
        return _this.toolbar = toolbar;
      }, eventEmitter, previewStyle, toolbarItems, editorType, cls("main"), editorTypeClassName, function(el2) {
        return _this.refs.editorSection = el2;
      }, cls("main-container"), cls("md-container"), previewClassName, function(el2) {
        return _this.refs.mdContainer = el2;
      }, cls("md-splitter"), cls("ww-container"), function(el2) {
        return _this.refs.wwContainer = el2;
      }, !hideModeSwitch && html(templateObject_1$1 || (templateObject_1$1 = __makeTemplateObject(["<", " eventEmitter=", " editorType=", " />"], ["<", " eventEmitter=", " editorType=", " />"])), Switch, eventEmitter, editorType), ContextMenu, eventEmitter);
    };
    Layout2.prototype.addEvent = function() {
      var eventEmitter = this.props.eventEmitter;
      eventEmitter.listen("hide", this.hide);
      eventEmitter.listen("show", this.show);
      eventEmitter.listen("changeMode", this.changeMode);
      eventEmitter.listen("changePreviewStyle", this.changePreviewStyle);
    };
    return Layout2;
  })(Component)
);
var templateObject_1$1;
var templateObject_2;
var ToastUIEditor = (
  /** @class */
  (function(_super) {
    __extends$1(ToastUIEditor2, _super);
    function ToastUIEditor2(options) {
      var _a;
      var _this = _super.call(this, options) || this;
      var layoutComp;
      var destroy2 = render(_this.options.el, html(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n        <", "\n          ref=", "\n          eventEmitter=", "\n          slots=", "\n          hideModeSwitch=", "\n          toolbarItems=", "\n          previewStyle=", "\n          editorType=", "\n          theme=", "\n        />\n      "], ["\n        <", "\n          ref=", "\n          eventEmitter=", "\n          slots=", "\n          hideModeSwitch=", "\n          toolbarItems=", "\n          previewStyle=", "\n          editorType=", "\n          theme=", "\n        />\n      "])), Layout, function(layout) {
        return layoutComp = layout;
      }, _this.eventEmitter, _this.getEditorElements(), _this.options.hideModeSwitch, _this.options.toolbarItems, _this.options.previewStyle, _this.options.initialEditType, _this.options.theme));
      _this.setMinHeight(_this.options.minHeight);
      _this.setHeight(_this.options.height);
      _this.defaultUI = {
        insertToolbarItem: layoutComp.insertToolbarItem.bind(layoutComp),
        removeToolbarItem: layoutComp.removeToolbarItem.bind(layoutComp),
        destroy: destroy2
      };
      (_a = _this.pluginInfo.toolbarItems) === null || _a === void 0 ? void 0 : _a.forEach(function(toolbarItem) {
        var groupIndex = toolbarItem.groupIndex, itemIndex = toolbarItem.itemIndex, item2 = toolbarItem.item;
        _this.defaultUI.insertToolbarItem({ groupIndex, itemIndex }, item2);
      });
      _this.eventEmitter.emit("loadUI", _this);
      return _this;
    }
    ToastUIEditor2.factory = function(options) {
      return options.viewer ? new ToastUIEditorViewer(options) : new ToastUIEditor2(options);
    };
    ToastUIEditor2.prototype.insertToolbarItem = function(indexInfo, item2) {
      this.defaultUI.insertToolbarItem(indexInfo, item2);
    };
    ToastUIEditor2.prototype.removeToolbarItem = function(itemName) {
      this.defaultUI.removeToolbarItem(itemName);
    };
    ToastUIEditor2.prototype.destroy = function() {
      _super.prototype.destroy.call(this);
      this.defaultUI.destroy();
    };
    return ToastUIEditor2;
  })(ToastUIEditorCore)
);
var templateObject_1;
ToastUIEditorCore.setLanguage(["en", "en-US"], {
  Markdown: "Markdown",
  WYSIWYG: "WYSIWYG",
  Write: "Write",
  Preview: "Preview",
  Headings: "Headings",
  Paragraph: "Paragraph",
  Bold: "Bold",
  Italic: "Italic",
  Strike: "Strike",
  Code: "Inline code",
  Line: "Line",
  Blockquote: "Blockquote",
  "Unordered list": "Unordered list",
  "Ordered list": "Ordered list",
  Task: "Task",
  Indent: "Indent",
  Outdent: "Outdent",
  "Insert link": "Insert link",
  "Insert CodeBlock": "Insert codeBlock",
  "Insert table": "Insert table",
  "Insert image": "Insert image",
  Heading: "Heading",
  "Image URL": "Image URL",
  "Select image file": "Select image file",
  "Choose a file": "Choose a file",
  "No file": "No file",
  Description: "Description",
  OK: "OK",
  More: "More",
  Cancel: "Cancel",
  File: "File",
  URL: "URL",
  "Link text": "Link text",
  "Add row to up": "Add row to up",
  "Add row to down": "Add row to down",
  "Add column to left": "Add column to left",
  "Add column to right": "Add column to right",
  "Remove row": "Remove row",
  "Remove column": "Remove column",
  "Align column to left": "Align column to left",
  "Align column to center": "Align column to center",
  "Align column to right": "Align column to right",
  "Remove table": "Remove table",
  "Would you like to paste as table?": "Would you like to paste as table?",
  "Text color": "Text color",
  "Auto scroll enabled": "Auto scroll enabled",
  "Auto scroll disabled": "Auto scroll disabled",
  "Choose language": "Choose language"
});
export {
  ToastUIEditor as Editor
};
/*! Bundled license information:

@toast-ui/editor/dist/esm/index.js:
  (**
   * @toast-ui/editor
   * @version 3.2.2 | Fri Feb 17 2023
   * @author NHN Cloud FE Development Lab <dl_javascript@nhn.com>
   * @license MIT
   *)
  (*! *****************************************************************************
  Copyright (c) Microsoft Corporation.
  
  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted.
  
  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  PERFORMANCE OF THIS SOFTWARE.
  ***************************************************************************** *)
  (*! http://mths.be/fromcodepoint v0.2.1 by @mathias *)
  (*! @license DOMPurify 2.3.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.3/LICENSE *)
*/
