diff --git a/.gitignore b/.gitignore index e43b0f9..646ac51 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ .DS_Store +node_modules/ diff --git a/esbuild.config.mjs b/esbuild.config.mjs new file mode 100644 index 0000000..8a1ab1b --- /dev/null +++ b/esbuild.config.mjs @@ -0,0 +1,14 @@ +import esbuild from "esbuild"; + +await esbuild.build({ + entryPoints: ["src/main.ts"], + bundle: true, + outfile: "main.js", + format: "cjs", + platform: "browser", + target: "es2022", + sourcemap: false, + minify: true, + external: ["obsidian"], + logLevel: "info", +}); diff --git a/main.js b/main.js index 1b6ae1e..eecc2ee 100644 --- a/main.js +++ b/main.js @@ -1,18 +1,18 @@ -"use strict";var ou=Object.defineProperty;var l1=Object.getOwnPropertyDescriptor;var a1=Object.getOwnPropertyNames;var c1=Object.prototype.hasOwnProperty;var u1=(n,e)=>{for(var t in e)ou(n,t,{get:e[t],enumerable:!0})},d1=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of a1(e))!c1.call(n,s)&&s!==t&&ou(n,s,{get:()=>e[s],enumerable:!(r=l1(e,s))||r.enumerable});return n};var h1=n=>d1(ou({},"__esModule",{value:!0}),n);var FP={};u1(FP,{default:()=>nu});module.exports=h1(FP);var T=require("obsidian");function Pe(n){this.content=n}Pe.prototype={constructor:Pe,find:function(n){for(var e=0;e>1}};Pe.from=function(n){if(n instanceof Pe)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new Pe(e)};var lu=Pe;function hm(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let s=n.child(r),i=e.child(r);if(s==i){t+=s.nodeSize;continue}if(!s.sameMarkup(i))return t;if(s.isText&&s.text!=i.text){for(let o=0;s.text[o]==i.text[o];o++)t++;return t}if(s.content.size||i.content.size){let o=hm(s.content,i.content,t+1);if(o!=null)return o}t+=s.nodeSize}}function fm(n,e,t,r){for(let s=n.childCount,i=e.childCount;;){if(s==0||i==0)return s==i?null:{a:t,b:r};let o=n.child(--s),l=e.child(--i),a=o.nodeSize;if(o==l){t-=a,r-=a;continue}if(!o.sameMarkup(l))return{a:t,b:r};if(o.isText&&o.text!=l.text){let c=0,u=Math.min(o.text.length,l.text.length);for(;ce&&r(a,s+l,i||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,s+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,s){let i="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?s?typeof s=="function"?s(l):s:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:i+=r),i+=c},0),i}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,s=this.content.slice(),i=0;for(t.isText&&t.sameMarkup(r)&&(s[s.length-1]=t.withText(t.text+r.text),i=1);ie)for(let i=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),s+=l.nodeSize),o=a}return new n(r,s)}cutByIndex(e,t){return e==t?n.empty:e==0&&t==this.content.length?this:new n(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let s=this.content.slice(),i=this.size+t.nodeSize-r.nodeSize;return s[e]=t,new n(s,i)}addToStart(e){return new n([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new n(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let s=this.child(t),i=r+s.nodeSize;if(i>=e)return i==e?Po(t+1,i):Po(t,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return n.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return n.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return n.empty;let t,r=0;for(let s=0;sthis.type.rank&&(t||(t=e.slice(0,s)),t.push(this),r=!0),t&&t.push(i)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-s.type.rank),t}};j.none=[];var jn=class extends Error{},S=class n{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=mm(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new n(r,this.openStart,this.openEnd)}removeBetween(e,t){return new n(pm(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return n.empty;let r=t.openStart||0,s=t.openEnd||0;if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new n(k.fromJSON(e,t.content),r,s)}static maxOpen(e,t=!0){let r=0,s=0;for(let i=e.firstChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=e.lastChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.lastChild)s++;return new n(e,r,s)}};S.empty=new S(k.empty,0,0);function pm(n,e,t){let{index:r,offset:s}=n.findIndex(e),i=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(s==e||i.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,i.copy(pm(i.content,e-s-1,t-s-1)))}function mm(n,e,t,r,s,i){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return i&&r<=0&&s<=0&&!i.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=mm(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?s-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function f1(n,e,t){if(t.openStart>n.depth)throw new jn("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new jn("Inconsistent open depths");return gm(n,e,t,0)}function gm(n,e,t,r){let s=n.index(r),i=n.node(r);if(s==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function Hs(n,e,t,r){let s=(e||n).node(t),i=0,o=e?e.index(t):s.childCount;n&&(i=n.index(t),n.depth>t?i++:n.textOffset&&(Hn(n.nodeAfter,r),i++));for(let l=i;ls&&cu(n,e,s+1),o=r.depth>s&&cu(t,r,s+1),l=[];return Hs(null,n,s,l),i&&o&&e.index(s)==t.index(s)?(ym(i,o),Hn(Wn(i,wm(n,e,t,r,s+1)),l)):(i&&Hn(Wn(i,zo(n,e,s+1)),l),Hs(e,t,s,l),o&&Hn(Wn(o,zo(t,r,s+1)),l)),Hs(r,null,s,l),new k(l)}function zo(n,e,t){let r=[];if(Hs(null,n,t,r),n.depth>t){let s=cu(n,e,t+1);Hn(Wn(s,zo(n,e,t+1)),r)}return Hs(e,null,t,r),new k(r)}function p1(n,e){let t=e.depth-n.openStart,s=e.node(t).copy(n.content);for(let i=t-1;i>=0;i--)s=e.node(i).copy(k.from(s));return{start:s.resolveNoCache(n.openStart+t),end:s.resolveNoCache(s.content.size-n.openEnd-t)}}var $o=class n{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],s=e.child(t);return r?e.child(t).cut(r):s}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],s=t==0?0:this.path[t*3-1]+1;for(let i=0;i0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new qn(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],s=0,i=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(i),c=i-a;if(r.push(o,l,s+a),!c||(o=o.child(l),o.isText))break;i=c-1,s+=a+1}return new n(t,r,i)}static resolveCached(e,t){let r=rm.get(e);if(r)for(let i=0;ie&&this.nodesBetween(e,t,i=>(r.isInSet(i.marks)&&(s=!0),!s)),s}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),km(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=k.empty,s=0,i=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,s,i),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=s;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let s=k.fromJSON(e,t.content),i=e.nodeType(t.type).create(t.attrs,s,r);return i.type.checkAttrs(i.attrs),i}};Qe.prototype.text=void 0;var du=class n extends Qe{constructor(e,t,r,s){if(super(e,t,null,s),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):km(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new n(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new n(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function km(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var Jn=class n{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new hu(e,t);if(r.next==null)return n.empty;let s=bm(r);r.next&&r.err("Unexpected trailing text");let i=v1(S1(s));return C1(i,r),i}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let s=0;s{let i=s+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return i}).join(` -`)}};Jn.empty=new Jn(!0);var hu=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}};function bm(n){let e=[];do e.push(y1(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function y1(n){let e=[];do e.push(w1(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function w1(n){let e=x1(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=k1(n,e);else break;return e}function sm(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function k1(n,e){let t=sm(n),r=t;return n.eat(",")&&(n.next!="}"?r=sm(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function b1(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let s=[];for(let i in t){let o=t[i];o.isInGroup(e)&&s.push(o)}return s.length==0&&n.err("No node type or group '"+e+"' found"),s}function x1(n){if(n.eat("(")){let e=bm(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=b1(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function S1(n){let e=[[]];return s(i(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function s(o,l){o.forEach(a=>a.to=l)}function i(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(i(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=i(o.exprs[a],l);if(a==o.exprs.length-1)return c;s(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),s(i(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return s(i(o.expr,l),a),s(i(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(i(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u{c||s.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let i=e[r.join(",")]=new Jn(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:vm(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Qe(this,this.computeAttrs(e),k.from(t),j.setFrom(r))}createChecked(e=null,t,r){return t=k.from(t),this.checkContent(t),new Qe(this,this.computeAttrs(e),t,j.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=k.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let s=this.contentMatch.matchFragment(t),i=s&&s.fillBefore(k.empty,!0);return i?new Qe(this,e,t.append(i),j.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[i]=new n(i,t,o));let s=t.spec.topNode||"doc";if(!r[s])throw new RangeError("Schema is missing its top node type ('"+s+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let i in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function T1(n,e,t){let r=t.split("|");return s=>{let i=s===null?"null":typeof s;if(r.indexOf(i)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${i}`)}}var fu=class{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?T1(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}},js=class n{constructor(e,t,r,s){this.name=e,this.rank=t,this.schema=r,this.spec=s,this.attrs=Tm(e,s.attrs),this.excluded=null;let i=Sm(this.attrs);this.instance=i?new j(this,i):null}create(e=null){return!e&&this.instance?this.instance:new j(this,vm(this.attrs,e))}static compile(e,t){let r=Object.create(null),s=0;return e.forEach((i,o)=>r[i]=new n(i,s++,t,o)),r}removeFromSet(e){for(var t=0;t-1}},zr=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let s in e)t[s]=e[s];t.nodes=lu.from(e.nodes),t.marks=lu.from(e.marks||{}),this.nodes=Uo.compile(this.spec.nodes,this),this.marks=js.compile(this.spec.marks,this);let r=Object.create(null);for(let s in this.nodes){if(s in this.marks)throw new RangeError(s+" can not be both a node and a mark");let i=this.nodes[s],o=i.spec.content||"",l=i.spec.marks;if(i.contentMatch=r[o]||(r[o]=Jn.parse(o,this.nodes)),i.inlineContent=i.contentMatch.inlineContent,i.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!i.isInline||!i.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=i}i.markSet=l=="_"?null:l?om(this,l.split(" ")):l==""||!i.inlineContent?[]:null}for(let s in this.marks){let i=this.marks[s],o=i.spec.excludes;i.excluded=o==null?[i]:o==""?[]:om(this,o.split(" "))}this.nodeFromJSON=s=>Qe.fromJSON(this,s),this.markFromJSON=s=>j.fromJSON(this,s),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,s){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Uo){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,s)}text(e,t){let r=this.nodes.text;return new du(r,r.defaultAttrs,e,j.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}};function om(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function A1(n){return n.tag!=null}function E1(n){return n.style!=null}var Ot=class n{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(s=>{if(A1(s))this.tags.push(s);else if(E1(s)){let i=/[^=]*/.exec(s.style)[0];r.indexOf(i)<0&&r.push(i),this.styles.push(s)}}),this.normalizeLists=!this.tags.some(s=>{if(!/^(ul|ol)\b/.test(s.tag)||!s.node)return!1;let i=e.nodes[s.node];return i.contentMatch.matchType(i)})}parse(e,t={}){let r=new Fo(this,t,!1);return r.addAll(e,j.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Fo(this,t,!0);return r.addAll(e,j.none,t.from,t.to),S.maxOpen(r.finish())}matchTag(e,t,r){for(let s=r?this.tags.indexOf(r)+1:0;se.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(s){let i=s.priority==null?50:s.priority,o=0;for(;o{r(o=am(o)),o.mark||o.ignore||o.clearMark||(o.mark=s)})}for(let s in e.nodes){let i=e.nodes[s].spec.parseDOM;i&&i.forEach(o=>{r(o=am(o)),o.node||o.ignore||o.mark||(o.node=s)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new n(e,n.schemaRules(e)))}},Am={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},M1={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Em={ol:!0,ul:!0},qs=1,pu=2,Ws=4;function lm(n,e,t){return e!=null?(e?qs:0)|(e==="full"?pu:0):n&&n.whitespace=="pre"?qs|pu:t&~Ws}var Br=class{constructor(e,t,r,s,i,o){this.type=e,this.attrs=t,this.marks=r,this.solid=s,this.options=o,this.content=[],this.activeMarks=j.none,this.match=i||(o&Ws?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(k.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,s;return(s=r.findWrapping(e.type))?(this.match=r,s):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&qs)){let r=this.content[this.content.length-1],s;if(r&&r.isText&&(s=/[ \t\r\n\u000c]+$/.exec(r.text))){let i=r;r.text.length==s[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-s[0].length))}}let t=k.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(k.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Am.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},Fo=class{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let s=t.topNode,i,o=lm(null,t.preserveWhitespace,0)|(r?Ws:0);s?i=new Br(s.type,s.attrs,j.none,!0,t.topMatch||s.type.contentMatch,o):r?i=new Br(null,null,j.none,!0,null,o):i=new Br(e.schema.topNodeType,null,j.none,!0,null,o),this.nodes=[i],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,s=this.top,i=s.options&pu?"full":this.localPreserveWS||(s.options&qs)>0,{schema:o}=this.parser;if(i==="full"||s.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(i)if(i==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,s){let i,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(i=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(s)this.addElement(e,r,s);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}i&&this.sync(l)&&this.open--}addAll(e,t,r,s){let i=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=s==null?null:e.childNodes[s];o!=l;o=o.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(o,t);this.findAtPoint(e,i)}findPlace(e,t,r){let s,i;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!s||s.length>c.length+l)&&(s=c,i=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!s)return null;this.sync(i);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):cm(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Br(e,t,a,s,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=qs)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let s=r.length-1;s>=0;s--)e+=r[s].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,s=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),i=-(r?r.depth+1:0)+(s?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=i;a--)if(o(l-1,a))return!0;return!1}else{let u=a>0||a==0&&s?this.nodes[a].type:r&&a>=i?r.node(a-i).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}};function R1(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Em.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function N1(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function am(n){let e={};for(let t in n)e[t]=n[t];return e}function cm(n,e){let t=e.schema.nodes;for(let r in t){let s=t[r];if(!s.allowsMarkType(n))continue;let i=[],o=l=>{i.push(l);for(let a=0;a{if(i.length||o.marks.length){let l=0,a=0;for(;l=0;s--){let i=this.serializeMark(e.marks[s],e.isInline,t);i&&((i.contentDOM||i.dom).appendChild(r),r=i.dom)}return r}serializeMark(e,t,r={}){let s=this.marks[e.type.name];return s&&_o(Lo(r),s(e,t),null,e.attrs)}static renderSpec(e,t,r=null,s){return typeof t=="string"?{dom:e.createTextNode(t)}:_o(e,t,r,s)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new n(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=um(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return um(e.marks)}};function um(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Lo(n){return n.document||window.document}var dm=new WeakMap;function I1(n){let e=dm.get(n);return e===void 0&&dm.set(n,e=D1(n)),e}function D1(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let s=0;s-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 o=s.indexOf(" ");o>0&&(t=s.slice(0,o),s=s.slice(o+1));let l,a=t?n.createElementNS(t,s):n.createElement(s),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let d in c)if(c[d]!=null){let h=d.indexOf(" ");h>0?a.setAttributeNS(d.slice(0,h),d.slice(h+1),c[d]):d=="style"&&a.style?a.style.cssText=c[d]:a.setAttribute(d,c[d])}}for(let d=u;du)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof h=="string")a.appendChild(n.createTextNode(h));else{let{dom:f,contentDOM:p}=_o(n,h,t,r);if(a.appendChild(f),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}var Nm=65535,Im=Math.pow(2,16);function P1(n,e){return n+e*Im}function Mm(n){return n&Nm}function L1(n){return(n-(n&Nm))/Im}var Dm=1,Om=2,Vo=4,Pm=8,Ys=class{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&Pm)>0}get deletedBefore(){return(this.delInfo&(Dm|Vo))>0}get deletedAfter(){return(this.delInfo&(Om|Vo))>0}get deletedAcross(){return(this.delInfo&Vo)>0}},Qt=class n{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&n.empty)return n.empty}recover(e){let t=0,r=Mm(e);if(!this.inverted)for(let s=0;se)break;let c=this.ranges[l+i],u=this.ranges[l+o],d=a+c;if(e<=d){let h=c?e==a?-1:e==d?1:t:t,f=a+s+(h<0?0:u);if(r)return f;let p=e==(t<0?a:d)?null:P1(l/3,e-a),m=e==a?Om:e==d?Dm:Vo;return(t<0?e!=a:e!=d)&&(m|=Pm),new Ys(f,m,p)}s+=u-c}return r?e+s:new Ys(e+s,0,null)}touches(e,t){let r=0,s=Mm(t),i=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+i],u=a+c;if(e<=u&&l==s*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let s=0,i=0;s=0;t--){let s=e.getMirror(t);this.appendMap(e._maps[t].invert(),s!=null&&s>t?r-s-1:void 0)}}invert(){let e=new n;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;ri&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),s),t.openStart,t.openEnd);return Ee.fromReplace(e,this.from,this.to,i)}invert(){return new Zt(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};ve.jsonID("addMark",Xs);var Zt=class n extends ve{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new S(bu(t.content,s=>s.mark(this.mark.removeFromSet(s.marks)),e),t.openStart,t.openEnd);return Ee.fromReplace(e,this.from,this.to,r)}invert(){return new Xs(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};ve.jsonID("removeMark",Zt);var Qs=class n extends ve{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ee.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Ee.fromReplace(e,this.pos,this.pos+1,new S(k.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let s=0;sr.pos?null:new n(t.pos,r.pos,s,i,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new n(t.from,t.to,t.gapFrom,t.gapTo,S.fromJSON(e,t.slice),t.insert,!!t.structure)}};ve.jsonID("replaceAround",ue);function wu(n,e,t){let r=n.resolve(e),s=t-e,i=r.depth;for(;s>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,s--;if(s>0){let o=r.node(i).maybeChild(r.indexAfter(i));for(;s>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,s--}}return!1}function _1(n,e,t,r){let s=[],i=[],o,l;n.doc.nodesBetween(e,t,(a,c,u)=>{if(!a.isInline)return;let d=a.marks;if(!r.isInSet(d)&&u.type.allowsMarkType(r.type)){let h=Math.max(c,e),f=Math.min(c+a.nodeSize,t),p=r.addToSet(d);for(let m=0;mn.step(a)),i.forEach(a=>n.step(a))}function B1(n,e,t,r){let s=[],i=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;i++;let a=null;if(r instanceof js){let c=o.marks,u;for(;u=r.isInSet(c);)(a||(a=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let u=0;un.step(new Zt(o.from,o.to,o.style)))}function xu(n,e,t,r=t.contentMatch,s=!0){let i=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function z1(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function en(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,s=0,i=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+s,a=n.$to.indexAfter(r)-i;if(rt;p--)m||r.index(p)>0?(m=!0,u=k.from(r.node(p).copy(u)),d++):a--;let h=k.empty,f=0;for(let p=i,m=!1;p>t;p--)m||s.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=k.from(t[o].type.create(t[o].attrs,r))}let s=e.start,i=e.end;n.step(new ue(s,i,s,i,new S(r,0,0),t.length,!0))}function H1(n,e,t,r,s){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof s=="function"?s(o):s;if(o.isTextblock&&!o.hasMarkup(r,a)&&W1(n.doc,n.mapping.slice(i).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!p?c=!1:!f&&p&&(c=!0)}c===!1&&_m(n,o,l,i),xu(n,n.mapping.slice(i).map(l,1),r,void 0,c===null);let u=n.mapping.slice(i),d=u.map(l,1),h=u.map(l+o.nodeSize,1);return n.step(new ue(d,h,d+1,h-1,new S(k.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&Lm(n,o,l,i),!1}})}function Lm(n,e,t,r){e.forEach((s,i)=>{if(s.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(s.text);){let a=n.mapping.slice(r).map(t+1+i+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function _m(n,e,t,r){e.forEach((s,i)=>{if(s.type==s.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+i);n.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function W1(n,e,t){let r=n.resolve(e),s=r.index();return r.parent.canReplaceWith(s,s+1,t)}function j1(n,e,t,r,s){let i=n.doc.nodeAt(e);if(!i)throw new RangeError("No node at given position");t||(t=i.type);let o=t.create(r,null,s||i.marks);if(i.isLeaf)return n.replaceWith(e,e+i.nodeSize,o);if(!t.validContent(i.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new ue(e,e+i.nodeSize,e+1,e+i.nodeSize-1,new S(k.from(o),0,0),1,!0))}function ot(n,e,t=1,r){let s=n.resolve(e),i=s.depth-t,o=r&&r[r.length-1]||s.parent;if(i<0||s.parent.type.spec.isolating||!s.parent.canReplace(s.index(),s.parent.childCount)||!o.type.validContent(s.parent.content.cutByIndex(s.index(),s.parent.childCount)))return!1;for(let c=s.depth-1,u=t-2;c>i;c--,u--){let d=s.node(c),h=s.index(c);if(d.type.spec.isolating)return!1;let f=d.content.cutByIndex(h,d.childCount),p=r&&r[u+1];p&&(f=f.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[u]||d;if(!d.canReplace(h+1,d.childCount)||!m.type.validContent(f))return!1}let l=s.indexAfter(i),a=r&&r[0];return s.node(i).canReplaceWith(l,l,a?a.type:s.node(i+1).type)}function q1(n,e,t=1,r){let s=n.doc.resolve(e),i=k.empty,o=k.empty;for(let l=s.depth,a=s.depth-t,c=t-1;l>a;l--,c--){i=k.from(s.node(l).copy(i));let u=r&&r[c];o=k.from(u?u.type.create(u.attrs,o):s.node(l).copy(o))}n.step(new Me(e,e,new S(i.append(o),t,t),!0))}function ft(n,e){let t=n.resolve(e),r=t.index();return Bm(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function J1(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let s=0;s0?(i=r.node(s+1),l++,o=r.node(s).maybeChild(l)):(i=r.node(s).maybeChild(l-1),o=r.node(s+1)),i&&!i.isTextblock&&Bm(i,o)&&r.node(s).canReplace(l,l+1))return e;if(s==0)break;e=t<0?r.before(s):r.after(s)}}function K1(n,e,t){let r=null,{linebreakReplacement:s}=n.doc.type.schema,i=n.doc.resolve(e-t),o=i.node().type;if(s&&o.inlineContent){let u=o.whitespace=="pre",d=!!o.contentMatch.matchType(s);u&&!d?r=!1:!u&&d&&(r=!0)}let l=n.steps.length;if(r===!1){let u=n.doc.resolve(e+t);_m(n,u.node(),u.before(),l)}o.inlineContent&&xu(n,e+t-1,o,i.node().contentMatchAt(i.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new Me(c,a.map(e+t,-1),S.empty,!0)),r===!0){let u=n.doc.resolve(c);Lm(n,u.node(),u.before(),n.steps.length)}return n}function Y1(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let s=r.depth-1;s>=0;s--){let i=r.index(s);if(r.node(s).canReplaceWith(i,i,t))return r.before(s+1);if(i>0)return null}if(r.parentOffset==r.parent.content.size)for(let s=r.depth-1;s>=0;s--){let i=r.indexAfter(s);if(r.node(s).canReplaceWith(i,i,t))return r.after(s+1);if(i=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),u=!1;if(i==1)u=c.canReplace(a,a,s);else{let d=c.contentMatchAt(a).findWrapping(s.firstChild.type);u=d&&c.canReplaceWith(a,a,d[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Zs(n,e,t=e,r=S.empty){if(e==t&&!r.size)return null;let s=n.resolve(e),i=n.resolve(t);return zm(s,i,r)?new Me(e,t,r):new ku(s,i,r).fit()}function zm(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}var ku=class{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=k.empty;for(let s=0;s<=e.depth;s++){let i=e.node(s);this.frontier.push({type:i.type,match:i.contentMatchAt(e.indexAfter(s))})}for(let s=e.depth;s>0;s--)this.placed=k.from(e.node(s).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,s=this.close(e<0?this.$to:r.doc.resolve(e));if(!s)return null;let i=this.placed,o=r.depth,l=s.depth;for(;o&&l&&i.childCount==1;)i=i.firstChild.content,o--,l--;let a=new S(i,o,l);return e>-1?new ue(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new Me(r.pos,s.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,s=this.unplaced.openEnd;r1&&(s=0),i.type.spec.isolating&&s<=r){e=r;break}t=i.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let s,i=null;r?(i=gu(this.unplaced.content,r-1).firstChild,s=i.content):s=this.unplaced.content;let o=s.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],u,d=null;if(t==1&&(o?c.matchType(o.type)||(d=c.fillBefore(k.from(o),!1)):i&&a.compatibleContent(i.type)))return{sliceDepth:r,frontierDepth:l,parent:i,inject:d};if(t==2&&o&&(u=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:i,wrap:u};if(i&&c.matchType(i.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced,s=gu(e,t);return!s.childCount||s.firstChild.isLeaf?!1:(this.unplaced=new S(e,t+1,Math.max(r,s.size+t>=e.size-r?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,s=gu(e,t);if(s.childCount<=1&&t>0){let i=e.size-t<=t+s.size;this.unplaced=new S(Js(e,t-1,1),t-1,i?t-1:r)}else this.unplaced=new S(Js(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:s,wrap:i}){for(;this.depth>t;)this.closeFrontierNode();if(i)for(let m=0;m1||a==0||m.content.size)&&(d=g,u.push($m(m.mark(h.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?f:-1)))}let p=c==l.childCount;p||(f=-1),this.placed=Ks(this.placed,t,k.from(u)),this.frontier[t].match=d,p&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&s==this.$to.end(--r);)++s;return s}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:s}=this.frontier[t],i=t=0;l--){let{match:a,type:c}=this.frontier[l],u=yu(e,l,c,a,!0);if(!u||u.childCount)continue e}return{depth:t,fit:o,move:i?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=Ks(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let s=e.node(r),i=s.type.contentMatch.fillBefore(s.content,!0,e.index(r));this.openFrontierNode(s.type,s.attrs,i)}return e}openFrontierNode(e,t=null,r){let s=this.frontier[this.depth];s.match=s.match.matchType(e),this.placed=Ks(this.placed,this.depth,k.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(k.empty,!0);t.childCount&&(this.placed=Ks(this.placed,this.frontier.length,t))}};function Js(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(Js(n.firstChild.content,e-1,t)))}function Ks(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(Ks(n.lastChild.content,e-1,t)))}function gu(n,e){for(let t=0;t1&&(r=r.replaceChild(0,$m(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(k.empty,!0)))),n.copy(r)}function yu(n,e,t,r,s){let i=n.node(e),o=s?n.indexAfter(e):n.index(e);if(o==i.childCount&&!t.compatibleContent(i.type))return null;let l=r.fillBefore(i.content,!0,o);return l&&!G1(t,i.content,o)?l:null}function G1(n,e,t){for(let r=t;r0;h--,f--){let p=s.node(h).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(h)>-1?l=h:s.before(h)==f&&o.splice(1,0,-h)}let a=o.indexOf(l),c=[],u=r.openStart;for(let h=r.content,f=0;;f++){let p=h.firstChild;if(c.push(p),f==r.openStart)break;h=p.content}for(let h=u-1;h>=0;h--){let f=c[h],p=X1(f.type);if(p&&!f.sameMarkup(s.node(Math.abs(l)-1)))u=h;else if(p||!f.type.isTextblock)break}for(let h=r.openStart;h>=0;h--){let f=(h+u+1)%(r.openStart+1),p=c[f];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>d));h--){let f=o[h];f<0||(e=s.before(f),t=i.after(f))}}function Um(n,e,t,r,s){if(er){let i=s.contentMatchAt(0),o=i.fillBefore(n).append(n);n=o.append(i.matchFragment(o).fillBefore(k.empty,!0))}return n}function Z1(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let s=Y1(n.doc,e,r.type);s!=null&&(e=t=s)}n.replaceRange(e,t,new S(k.from(r),0,0))}function ev(n,e,t){let r=n.doc.resolve(e),s=n.doc.resolve(t);if(r.parent.isTextblock&&s.parent.isTextblock&&r.start()!=s.start()&&r.parentOffset==0&&s.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=s.depth;a>o;a--)s.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=s.depth;a>0&&t==s.start(a);a--)t=s.before(a);r=n.doc.resolve(e),s=n.doc.resolve(t)}}let i=Fm(r,s);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),s.indexAfter(l-1))))return n.delete(r.before(l),s.after(l))}for(let o=1;o<=r.depth&&o<=s.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&s.end(o)-t!=s.depth-o&&r.start(o-1)==s.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),s.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function Fm(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let s=r;s>=0;s--){let i=n.start(s);if(ie.pos+(e.depth-s)||n.node(s).type.spec.isolating||e.node(s).type.spec.isolating)break;(i==e.start(s)||s==n.depth&&s==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&s&&e.start(s-1)==i-1)&&t.push(s)}return t}var Ho=class n extends ve{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ee.fail("No node at attribute step's position");let r=Object.create(null);for(let i in t.attrs)r[i]=t.attrs[i];r[this.attr]=this.value;let s=t.type.create(r,null,t.marks);return Ee.fromReplace(e,this.pos,this.pos+1,new S(k.from(s),0,t.isLeaf?0:1))}getMap(){return Qt.empty}invert(e){return new n(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new n(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new n(t.pos,t.attr,t.value)}};ve.jsonID("attr",Ho);var Wo=class n extends ve{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let s in e.attrs)t[s]=e.attrs[s];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return Ee.ok(r)}getMap(){return Qt.empty}invert(e){return new n(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new n(t.attr,t.value)}};ve.jsonID("docAttr",Wo);var Ur=class extends Error{};Ur=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Ur.prototype=Object.create(Error.prototype);Ur.prototype.constructor=Ur;Ur.prototype.name="TransformError";var xn=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Gs}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Ur(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=S.empty){let s=Zs(this.doc,e,t,r);return s&&this.step(s),this}replaceWith(e,t,r){return this.replace(e,t,new S(k.from(r),0,0))}delete(e,t){return this.replace(e,t,S.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Q1(this,e,t,r),this}replaceRangeWith(e,t,r){return Z1(this,e,t,r),this}deleteRange(e,t){return ev(this,e,t),this}lift(e,t){return $1(this,e,t),this}join(e,t=1){return K1(this,e,t),this}wrap(e,t){return V1(this,e,t),this}setBlockType(e,t=e,r,s=null){return H1(this,e,t,r,s),this}setNodeMarkup(e,t,r=null,s){return j1(this,e,t,r,s),this}setNodeAttribute(e,t,r){return this.step(new Ho(e,t,r)),this}setDocAttribute(e,t){return this.step(new Wo(e,t)),this}addNodeMark(e,t){return this.step(new Qs(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof j)t.isInSet(r.marks)&&this.step(new $r(e,t));else{let s=r.marks,i,o=[];for(;i=t.isInSet(s);)o.push(new $r(e,i)),s=i.removeFromSet(s);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return q1(this,e,t,r),this}addMark(e,t,r){return _1(this,e,t,r),this}removeMark(e,t,r){return B1(this,e,t,r),this}clearIncompatible(e,t,r){return xu(this,e,t,r),this}};var Su=Object.create(null),I=class{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new Hr(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;i--){let o=t<0?Vr(e.node(0),e.node(i),e.before(i+1),e.index(i),t,r):Vr(e.node(0),e.node(i),e.after(i+1),e.index(i)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new Re(e.node(0))}static atStart(e){return Vr(e,e,0,0,1)||new Re(e)}static atEnd(e){return Vr(e,e,e.content.size,e.childCount,-1)||new Re(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Su[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Su)throw new RangeError("Duplicate use of selection JSON ID "+e);return Su[e]=t,t.prototype.jsonID=e,t}getBookmark(){return E.between(this.$anchor,this.$head).getBookmark()}};I.prototype.visible=!0;var Hr=class{constructor(e,t){this.$from=e,this.$to=t}},Vm=!1;function Hm(n){!Vm&&!n.parent.inlineContent&&(Vm=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var E=class n extends I{constructor(e,t=e){Hm(e),Hm(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return I.near(r);let s=e.resolve(t.map(this.anchor));return new n(s.parent.inlineContent?s:r,r)}replace(e,t=S.empty){if(super.replace(e,t),t==S.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof n&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Jo(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new n(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let s=e.resolve(t);return new this(s,r==t?s:e.resolve(r))}static between(e,t,r){let s=e.pos-t.pos;if((!r||s)&&(r=s>=0?1:-1),!t.parent.inlineContent){let i=I.findFrom(t,r,!0)||I.findFrom(t,-r,!0);if(i)t=i.$head;else return I.near(t,r)}return e.parent.inlineContent||(s==0?e=t:(e=(I.findFrom(e,-r,!0)||I.findFrom(e,r,!0)).$anchor,e.pos0?0:1);s>0?o=0;o+=s){let l=e.child(o);if(l.isAtom){if(!i&&M.isSelectable(l))return M.create(n,t-(s<0?l.nodeSize:0))}else{let a=Vr(n,l,t+s,s<0?l.childCount:0,s,i);if(a)return a}t+=l.nodeSize*s}return null}function Wm(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=u)}),n.setSelection(I.near(n.doc.resolve(o),t))}var jm=1,qo=2,qm=4,Tu=class extends xn{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=qo,this}ensureMarks(e){return j.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&qo)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~qo,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||j.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let s=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(s.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let i=this.storedMarks;if(!i){let o=this.doc.resolve(t);i=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,s.text(e,i)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(I.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=qm,this}get scrolledIntoView(){return(this.updated&qm)>0}};function Jm(n,e){return!e||!n?n:n.bind(e)}var Yn=class{constructor(e,t,r){this.name=e,this.init=Jm(t.init,r),this.apply=Jm(t.apply,r)}},nv=[new Yn("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Yn("selection",{init(n,e){return n.selection||I.atStart(e.doc)},apply(n){return n.selection}}),new Yn("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Yn("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})],ei=class{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=nv.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Yn(r.key,r.spec.state,r))})}},Ko=class n{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let s=e[r],i=s.spec.state;i&&i.toJSON&&(t[r]=i.toJSON.call(s,this[s.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let s=new ei(e.schema,e.plugins),i=new n(s);return s.fields.forEach(o=>{if(o.name=="doc")i.doc=Qe.fromJSON(e.schema,t.doc);else if(o.name=="selection")i.selection=I.fromJSON(i.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(i.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){i[o.name]=c.fromJSON.call(a,e,t[l],i);return}}i[o.name]=o.init(e,i)}}),i}};function Km(n,e,t){for(let r in n){let s=n[r];s instanceof Function?s=s.bind(e):r=="handleDOMEvents"&&(s=Km(s,e,{})),t[r]=s}return t}var O=class{constructor(e){this.spec=e,this.props={},e.props&&Km(e.props,this,this.props),this.key=e.key?e.key.key:Ym("plugin")}getState(e){return e[this.key]}},vu=Object.create(null);function Ym(n){return n in vu?n+"$"+ ++vu[n]:(vu[n]=0,n+"$")}var P=class{constructor(e="key"){this.key=Ym(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var Xm=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function Qm(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}var Eu=(n,e,t)=>{let r=Qm(n,t);if(!r)return!1;let s=Ru(r);if(!s){let o=r.blockRange(),l=o&&en(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let i=s.nodeBefore;if(lg(n,s,e,-1))return!0;if(r.parent.content.size==0&&(Wr(i,"end")||M.isSelectable(i)))for(let o=r.depth;;o--){let l=Zs(n.doc,r.before(o),r.after(o),S.empty);if(l&&l.slice.size1)break}return i.isAtom&&s.depth==r.depth-1?(e&&e(n.tr.delete(s.pos-i.nodeSize,s.pos).scrollIntoView()),!0):!1},Zm=(n,e,t)=>{let r=Qm(n,t);if(!r)return!1;let s=Ru(r);return s?tg(n,s,e):!1},eg=(n,e,t)=>{let r=ng(n,t);if(!r)return!1;let s=Du(r);return s?tg(n,s,e):!1};function tg(n,e,t){let r=e.nodeBefore,s=r,i=e.pos-1;for(;!s.isTextblock;i--){if(s.type.spec.isolating)return!1;let u=s.lastChild;if(!u)return!1;s=u}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let c=Zs(n.doc,i,a,S.empty);if(!c||c.from!=i||c instanceof Me&&c.slice.size>=a-i)return!1;if(t){let u=n.tr.step(c);u.setSelection(E.create(u.doc,i)),t(u.scrollIntoView())}return!0}function Wr(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}var Mu=(n,e,t)=>{let{$head:r,empty:s}=n.selection,i=r;if(!s)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;i=Ru(r)}let o=i&&i.nodeBefore;return!o||!M.isSelectable(o)?!1:(e&&e(n.tr.setSelection(M.create(n.doc,i.pos-o.nodeSize)).scrollIntoView()),!0)};function Ru(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function ng(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=ng(n,t);if(!r)return!1;let s=Du(r);if(!s)return!1;let i=s.nodeAfter;if(lg(n,s,e,1))return!0;if(r.parent.content.size==0&&(Wr(i,"start")||M.isSelectable(i))){let o=Zs(n.doc,r.before(),r.after(),S.empty);if(o&&o.slice.size{let{$head:r,empty:s}=n.selection,i=r;if(!s)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof M,s;if(r){if(t.node.isTextblock||!ft(n.doc,t.from))return!1;s=t.from}else if(s=Kn(n.doc,t.from,-1),s==null)return!1;if(e){let i=n.tr.join(s);r&&i.setSelection(M.create(i.doc,s-n.doc.resolve(s).nodeBefore.nodeSize)),e(i.scrollIntoView())}return!0},sg=(n,e)=>{let t=n.selection,r;if(t instanceof M){if(t.node.isTextblock||!ft(n.doc,t.to))return!1;r=t.to}else if(r=Kn(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},ig=(n,e)=>{let{$from:t,$to:r}=n.selection,s=t.blockRange(r),i=s&&en(s);return i==null?!1:(e&&e(n.tr.lift(s,i).scrollIntoView()),!0)},Ou=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` -`).scrollIntoView()),!0)};function Pu(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let s=t.node(-1),i=t.indexAfter(-1),o=Pu(s.contentMatchAt(i));if(!o||!s.canReplaceWith(i,i,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(I.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},_u=(n,e)=>{let t=n.selection,{$from:r,$to:s}=t;if(t instanceof Re||r.parent.inlineContent||s.parent.inlineContent)return!1;let i=Pu(s.parent.contentMatchAt(s.indexAfter()));if(!i||!i.isTextblock)return!1;if(e){let o=(!r.parentOffset&&s.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let i=t.before();if(ot(n.doc,i))return e&&e(n.tr.split(i).scrollIntoView()),!0}let r=t.blockRange(),s=r&&en(r);return s==null?!1:(e&&e(n.tr.lift(r,s).scrollIntoView()),!0)};function rv(n){return(e,t)=>{let{$from:r,$to:s}=e.selection;if(e.selection instanceof M&&e.selection.node.isBlock)return!r.parentOffset||!ot(e.doc,r.pos)?!1:(t&&t(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let i=[],o,l,a=!1,c=!1;for(let f=r.depth;;f--)if(r.node(f).isBlock){a=r.end(f)==r.pos+(r.depth-f),c=r.start(f)==r.pos-(r.depth-f),l=Pu(r.node(f-1).contentMatchAt(r.indexAfter(f-1)));let m=n&&n(s.parent,a,r);i.unshift(m||(a&&l?{type:l}:null)),o=f;break}else{if(f==1)return!1;i.unshift(null)}let u=e.tr;(e.selection instanceof E||e.selection instanceof Re)&&u.deleteSelection();let d=u.mapping.map(r.pos),h=ot(u.doc,d,i.length,i);if(h||(i[0]=l?{type:l}:null,h=ot(u.doc,d,i.length,i)),!h)return!1;if(u.split(d,i.length,i),!a&&c&&r.node(o).type!=l){let f=u.mapping.map(r.before(o)),p=u.doc.resolve(f);l&&r.node(o-1).canReplaceWith(p.index(),p.index()+1,l)&&u.setNodeMarkup(u.mapping.map(r.before(o)),l)}return t&&t(u.scrollIntoView()),!0}}var sv=rv();var og=(n,e)=>{let{$from:t,to:r}=n.selection,s,i=t.sharedDepth(r);return i==0?!1:(s=t.before(i),e&&e(n.tr.setSelection(M.create(n.doc,s))),!0)},iv=(n,e)=>(e&&e(n.tr.setSelection(new Re(n.doc))),!0);function ov(n,e,t){let r=e.nodeBefore,s=e.nodeAfter,i=e.index();return!r||!s||!r.type.compatibleContent(s.type)?!1:!r.content.size&&e.parent.canReplace(i-1,i)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(i,i+1)||!(s.isTextblock||ft(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function lg(n,e,t,r){let s=e.nodeBefore,i=e.nodeAfter,o,l,a=s.type.spec.isolating||i.type.spec.isolating;if(!a&&ov(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=s.contentMatchAt(s.childCount)).findWrapping(i.type))&&l.matchType(o[0]||i.type).validEnd){if(t){let f=e.pos+i.nodeSize,p=k.empty;for(let y=o.length-1;y>=0;y--)p=k.from(o[y].create(null,p));p=k.from(s.copy(p));let m=n.tr.step(new ue(e.pos-1,f,e.pos,f,new S(p,1,0),o.length,!0)),g=m.doc.resolve(f+2*o.length);g.nodeAfter&&g.nodeAfter.type==s.type&&ft(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&a?null:I.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),h=d&&en(d);if(h!=null&&h>=e.depth)return t&&t(n.tr.lift(d,h).scrollIntoView()),!0;if(c&&Wr(i,"start",!0)&&Wr(s,"end")){let f=s,p=[];for(;p.push(f),!f.isTextblock;)f=f.lastChild;let m=i,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(f.canReplace(f.childCount,f.childCount,m.content)){if(t){let y=k.empty;for(let b=p.length-1;b>=0;b--)y=k.from(p[b].copy(y));let w=n.tr.step(new ue(e.pos-p.length,e.pos+i.nodeSize,e.pos+g,e.pos+i.nodeSize-g,new S(y,p.length,0),0,!0));t(w.scrollIntoView())}return!0}}return!1}function ag(n){return function(e,t){let r=e.selection,s=n<0?r.$from:r.$to,i=s.depth;for(;s.node(i).isInline;){if(!i)return!1;i--}return s.node(i).isTextblock?(t&&t(e.tr.setSelection(E.create(e.doc,n<0?s.start(i):s.end(i)))),!0):!1}}var zu=ag(-1),$u=ag(1);function cg(n,e=null){return function(t,r){let{$from:s,$to:i}=t.selection,o=s.blockRange(i),l=o&&Fr(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Uu(n,e=null){return function(t,r){let s=!1;for(let i=0;i{if(s)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)s=!0;else{let u=t.doc.resolve(c),d=u.index();s=u.parent.canReplaceWith(d,d+1,n)}})}if(!s)return!1;if(r){let i=t.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);i=new qn(a,a,e.depth),e.endIndex=0;u--)i=k.from(t[u].type.create(t[u].attrs,i));n.step(new ue(e.start-(r?2:0),e.end,e.start,e.end,new S(i,0,0),t.length,!0));let o=0;for(let u=0;uo.childCount>0&&o.firstChild.type==n);return i?t?r.node(i.depth-1).type==n?uv(e,t,n,i):dv(e,t,i):!0:!1}}function uv(n,e,t,r){let s=n.tr,i=r.end,o=r.$to.end(r.depth);im;p--)f-=s.child(p).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(t.start),o=i.nodeAfter;if(r.mapping.map(t.end)!=t.start+i.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==s.childCount,c=i.node(-1),u=i.index(-1);if(!c.canReplace(u+(l?0:1),u+1,o.content.append(a?k.empty:k.from(s))))return!1;let d=i.pos,h=d+o.nodeSize;return r.step(new ue(d-(l?1:0),h+(a?1:0),d+1,h-1,new S((l?k.empty:k.from(s.copy(k.empty))).append(a?k.empty:k.from(s.copy(k.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function hg(n){return function(e,t){let{$from:r,$to:s}=e.selection,i=r.blockRange(s,c=>c.childCount>0&&c.firstChild.type==n);if(!i)return!1;let o=i.startIndex;if(o==0)return!1;let l=i.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,u=k.from(c?n.create():null),d=new S(k.from(n.create(null,k.from(l.type.create(null,u)))),c?3:1,0),h=i.start,f=i.end;t(e.tr.step(new ue(h-(c?3:1),f,h,f,d,1,!0)).scrollIntoView())}return!0}}var Ne=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},Yr=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e},Ju=null,nn=function(n,e,t){let r=Ju||(Ju=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},hv=function(){Ju=null},nr=function(n,e,t,r){return t&&(fg(n,e,t,r,-1)||fg(n,e,t,r,1))},fv=/^(img|br|input|textarea|hr)$/i;function fg(n,e,t,r,s){for(var i;;){if(n==t&&e==r)return!0;if(e==(s<0?0:mt(n))){let o=n.parentNode;if(!o||o.nodeType!=1||ai(n)||fv.test(n.nodeName)||n.contentEditable=="false")return!1;e=Ne(n)+(s<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(s<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((i=o.pmViewDesc)===null||i===void 0)&&i.ignoreForSelection)e+=s;else return!1;else n=o,e=s<0?mt(n):0}else return!1}}function mt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function pv(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=mt(n)}else if(n.parentNode&&!ai(n))e=Ne(n),n=n.parentNode;else return null}}function mv(n,e){for(;;){if(n.nodeType==3&&e2),pt=Gr||(Pt?/Mac/.test(Pt.platform):!1),Kg=Pt?/Win/.test(Pt.platform):!1,rn=/Android \d/.test(Mn),ci=!!pg&&"webkitFontSmoothing"in pg.documentElement.style,kv=ci?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function bv(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function tn(n,e){return typeof n=="number"?n:n[e]}function xv(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function mg(n,e,t){let r=n.someProp("scrollThreshold")||0,s=n.someProp("scrollMargin")||5,i=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=Yr(o);continue}let l=o,a=l==i.body,c=a?bv(i):xv(l),u=0,d=0;if(e.topc.bottom-tn(r,"bottom")&&(d=e.bottom-e.top>c.bottom-c.top?e.top+tn(s,"top")-c.top:e.bottom-c.bottom+tn(s,"bottom")),e.leftc.right-tn(r,"right")&&(u=e.right-c.right+tn(s,"right")),u||d)if(a)i.defaultView.scrollBy(u,d);else{let f=l.scrollLeft,p=l.scrollTop;d&&(l.scrollTop+=d),u&&(l.scrollLeft+=u);let m=l.scrollLeft-f,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let h=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(h))break;o=h=="absolute"?o.offsetParent:Yr(o)}}function Sv(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,s;for(let i=(e.left+e.right)/2,o=t+1;o=t-20){r=l,s=a.top;break}}return{refDOM:r,refTop:s,stack:Yg(n.dom)}}function Yg(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=Yr(r));return e}function vv({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;Gg(t,r==0?0:r-e)}function Gg(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=u,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(i=d+1)}}return!t&&a&&(t=a,s=c,r=0),t&&t.nodeType==3?Tv(t,s):!t||r&&t.nodeType==1?{node:n,offset:i}:Xg(t,s)}function Tv(n,e){let t=n.nodeValue.length,r=document.createRange(),s;for(let i=0;i=(o.left+o.right)/2?1:0)};break}}return r.detach(),s||{node:n,offset:0}}function dd(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Av(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,s,i)}function Mv(n,e,t,r){let s=-1;for(let i=e,o=!1;i!=n.dom;){let l=n.docView.nearestDesc(i,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?s=l.posBefore:(!o&&a.right-1?s:n.docView.posFromDOM(e,t,-1)}function Qg(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&s++}let c;ci&&s&&r.nodeType==1&&(c=r.childNodes[s-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&s--,r==n.dom&&s==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(s==0||r.nodeType!=1||r.childNodes[s-1].nodeName!="BR")&&(l=Mv(n,r,s,e))}l==null&&(l=Ev(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function gg(n){return n.top=0&&s==r.nodeValue.length?(a--,u=1):t<0?a--:c++,ti(vn(nn(r,a,c),u),u<0)}if(!n.state.doc.resolve(e-(i||0)).parent.inlineContent){if(i==null&&s&&(t<0||s==mt(r))){let a=r.childNodes[s-1];if(a.nodeType==1)return Vu(a.getBoundingClientRect(),!1)}if(i==null&&s=0)}if(i==null&&s&&(t<0||s==mt(r))){let a=r.childNodes[s-1],c=a.nodeType==3?nn(a,mt(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return ti(vn(c,1),!1)}if(i==null&&s=0)}function ti(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Vu(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function ey(n,e,t){let r=n.state,s=n.root.activeElement;r!=e&&n.updateState(e),s!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),s!=n.dom&&s&&s.focus()}}function Iv(n,e,t){let r=e.selection,s=t=="up"?r.$from:r.$to;return ey(n,e,()=>{let{node:i}=n.docView.domFromPos(s.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(i,!0);if(!l)break;if(l.node.isBlock){i=l.contentDOM||l.dom;break}i=l.dom.parentNode}let o=Zg(n,s.pos,1);for(let l=i.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=nn(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cu.top+1&&(t=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}var Dv=/[\u0590-\u08ac]/;function Ov(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let s=r.parentOffset,i=!s,o=s==r.parent.content.size,l=n.domSelection();return l?!Dv.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?i:o:ey(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:u,anchorOffset:d}=n.domSelectionRange(),h=l.caretBidiLevel;l.modify("move",t,"character");let f=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!f.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(u,d),a&&(a!=u||c!=d)&&l.extend&&l.extend(a,c)}catch{}return h!=null&&(l.caretBidiLevel=h),g}):r.pos==r.start()||r.pos==r.end()}var yg=null,wg=null,kg=!1;function Pv(n,e,t){return yg==e&&wg==t?kg:(yg=e,wg=t,kg=t=="up"||t=="down"?Iv(n,e,t):Ov(n,e,t))}var yt=0,bg=1,Xn=2,Lt=3,rr=class{constructor(e,t,r,s){this.parent=e,this.children=t,this.dom=r,this.contentDOM=s,this.dirty=yt,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tNe(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))s=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let i=e;;i=i.parentNode){if(i==this.dom){s=!1;break}if(i.previousSibling)break}if(s==null&&t==e.childNodes.length)for(let i=e;;i=i.parentNode){if(i==this.dom){s=!0;break}if(i.nextSibling)break}}return s??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,s=e;s;s=s.parentNode){let i=this.getDesc(s),o;if(i&&(!t||i.node))if(r&&(o=i.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return i}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let s=e;s;s=s.parentNode){let i=this.getDesc(s);if(i)return i.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof Xo){s=e-i;break}i=l}if(s)return this.children[r].domFromPos(s-this.children[r].border,t);for(let i;r&&!(i=this.children[r-1]).size&&i instanceof Yo&&i.side>=0;r--);if(t<=0){let i,o=!0;for(;i=r?this.children[r-1]:null,!(!i||i.dom.parentNode==this.contentDOM);r--,o=!1);return i&&t&&o&&!i.border&&!i.domAtom?i.domFromPos(i.size,t):{node:this.contentDOM,offset:i?Ne(i.dom)+1:0}}else{let i,o=!0;for(;i=r=u&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,u);e=o;for(let d=l;d>0;d--){let h=this.children[d-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){s=Ne(h.dom)+1;break}e-=h.size}s==-1&&(s=0)}if(s>-1&&(c>t||l==this.children.length-1)){t=c;for(let u=l+1;up&&ot){let p=l;l=a,a=p}let f=document.createRange();f.setEnd(a.node,a.offset),f.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(f)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,s=0;s=r:er){let l=r+i.border,a=o-i.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Xn:bg,e==l&&t==a&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=Lt:i.markDirty(e-l,t-l);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?Xn:Lt}r=o}this.dirty=Xn}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Xn:bg;t.dirty{if(!i)return s;if(i.parent)return i.parent.posBeforeChild(i)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,i=this}matchesWidget(e){return this.dirty==yt&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},Xu=class extends rr{constructor(e,t,r,s){super(e,[],t,null),this.textDOM=r,this.text=s}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}},Xr=class n extends rr{constructor(e,t,r,s,i){super(e,[],r,s),this.mark=t,this.spec=i}static create(e,t,r,s){let i=s.nodeViews[t.type.name],o=i&&i(t,s,r);return(!o||!o.dom)&&(o=Xt.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new n(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Lt||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Lt&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=yt){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=td(i,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,s),u=c&&c.dom,d=c&&c.contentDOM;if(t.isText){if(!u)u=document.createTextNode(t.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:d}=Xt.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!d&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let h=u;return u=ry(u,r,t),c?a=new Qu(e,t,r,s,u,d||null,h,c,i,o+1):t.isText?new Go(e,t,r,s,u,h,i):new n(e,t,r,s,u,d||null,h,i,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let r=this.children[t];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>k.empty)}return e}matchesNode(e,t,r){return this.dirty==yt&&e.eq(this.node)&&Qo(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,s=t,i=e.composing?this.localCompositionInfo(e,t):null,o=i&&i.pos>-1?i:null,l=i&&i.pos<0,a=new ed(this,o&&o.node,e);zv(this.node,this.innerDeco,(c,u,d)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!d&&a.syncToMarks(u==this.node.childCount?j.none:this.node.child(u).marks,r,e,u),a.placeWidget(c,e,s)},(c,u,d,h)=>{a.syncToMarks(c.marks,r,e,h);let f;a.findNodeMatch(c,u,d,h)||l&&e.state.selection.from>s&&e.state.selection.to-1&&a.updateNodeAt(c,u,d,f,e)||a.updateNextNode(c,u,d,e,h,s)||a.addNode(c,u,d,e,s),s+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Xn)&&(o&&this.protectLocalComposition(e,o),ty(this.contentDOM,this.children,e),Gr&&$v(this.dom))}localCompositionInfo(e,t){let{from:r,to:s}=e.state.selection;if(!(e.state.selection instanceof E)||rt+this.node.content.size)return null;let i=e.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let o=i.nodeValue,l=Uv(this.node.content,o,r-t,s-t);return l<0?null:{node:i,pos:l,text:o}}else return{node:i,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:s}){if(this.getDesc(t))return;let i=t;for(;i.parentNode!=this.contentDOM;i=i.parentNode){for(;i.previousSibling;)i.parentNode.removeChild(i.previousSibling);for(;i.nextSibling;)i.parentNode.removeChild(i.nextSibling);i.pmViewDesc&&(i.pmViewDesc=void 0)}let o=new Xu(this,i,t,s);e.input.compositionNodes.push(o),this.children=td(this.children,r,r+s.length,e,o)}update(e,t,r,s){return this.dirty==Lt||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,s),!0)}updateInner(e,t,r,s){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(s,this.posAtStart),this.dirty=yt}updateOuterDeco(e){if(Qo(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ny(this.dom,this.nodeDOM,Zu(this.outerDeco,this.node,t),Zu(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function xg(n,e,t,r,s){ry(r,e,n);let i=new En(void 0,n,e,t,r,r,r,s,0);return i.contentDOM&&i.updateChildren(s,0),i}var Go=class n extends En{constructor(e,t,r,s,i,o,l){super(e,t,r,s,i,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,s){return this.dirty==Lt||this.dirty!=yt&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=yt||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,s.trackWrites==this.nodeDOM&&(s.trackWrites=null)),this.node=e,this.dirty=yt,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let s=this.node.cut(e,t),i=document.createTextNode(s.text);return new n(this.parent,s,this.outerDeco,this.innerDeco,i,i,r)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=Lt)}get domAtom(){return!1}isText(e){return this.node.text==e}},Xo=class extends rr{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==yt&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},Qu=class extends En{constructor(e,t,r,s,i,o,l,a,c,u){super(e,t,r,s,i,o,l,c,u),this.spec=a}update(e,t,r,s){if(this.dirty==Lt)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let i=this.spec.update(e,t,r);return i&&this.updateInner(e,t,r,s),i}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,s)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,s){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,s)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function ty(n,e,t){let r=n.firstChild,s=!1;for(let i=0;i>1,l=Math.min(o,e.length);for(;i-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let u=Xr.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,s){let i=-1,o;if(s>=this.preMatch.index&&(o=this.preMatch.matches[s-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))i=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Xr)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(s-1))break;--s,i.set(l,s),o.push(l)}}return{index:s,matched:i,matches:o.reverse()}}function Bv(n,e){return n.type.side-e.type.side}function zv(n,e,t,r){let s=e.locals(n),i=0;if(s.length==0){for(let c=0;ci;)l.push(s[o++]);let p=i+h.nodeSize;if(h.isText){let g=p;o!g.inline):l.slice();r(h,m,e.forChild(i,h),f),i=p}}function $v(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function Uv(n,e,t,r){for(let s=0,i=0;s=t){if(i>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function td(n,e,t,r,s){let i=[];for(let o=0,l=0;o=t||u<=e?i.push(a):(ct&&i.push(a.slice(t-c,a.size,r)))}return i}function hd(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let s=n.docView.nearestDesc(t.focusNode),i=s&&s.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(il(t)){for(a=o;s&&!s.node;)s=s.parent;let d=s.node;if(s&&d.isAtom&&M.isSelectable(d)&&s.parent&&!(d.isInline&&gv(t.focusNode,t.focusOffset,s.dom))){let h=s.posBefore;c=new M(o==h?l:r.resolve(h))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let d=o,h=o;for(let f=0;f{(t.anchorNode!=r||t.anchorOffset!=s)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!sy(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function Vv(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,Ne(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&Ze&&An<=11&&(t.disabled=!0,t.disabled=!1)}function iy(n,e){if(e instanceof M){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ag(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ag(n)}function Ag(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function fd(n,e,t,r){return n.someProp("createSelectionBetween",s=>s(n,e,t))||E.between(e,t,r)}function Eg(n){return n.editable&&!n.hasFocus()?!1:oy(n)}function oy(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function Hv(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return nr(e.node,e.offset,t.anchorNode,t.anchorOffset)}function nd(n,e){let{$anchor:t,$head:r}=n.selection,s=e>0?t.max(r):t.min(r),i=s.parent.inlineContent?s.depth?n.doc.resolve(e>0?s.after():s.before()):null:s;return i&&I.findFrom(i,e)}function Cn(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Mg(n,e,t){let r=n.state.selection;if(r instanceof E)if(t.indexOf("s")>-1){let{$head:s}=r,i=s.textOffset?null:e<0?s.nodeBefore:s.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let o=n.state.doc.resolve(s.pos+i.nodeSize*(e<0?-1:1));return Cn(n,new E(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let s=nd(n.state,e);return s&&s instanceof M?Cn(n,s):!1}else if(!(pt&&t.indexOf("m")>-1)){let s=r.$head,i=s.textOffset?null:e<0?s.nodeBefore:s.nodeAfter,o;if(!i||i.isText)return!1;let l=e<0?s.pos-i.nodeSize:s.pos;return i.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?M.isSelectable(i)?Cn(n,new M(e<0?n.state.doc.resolve(s.pos-i.nodeSize):s)):ci?Cn(n,new E(n.state.doc.resolve(e<0?l:l+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof M&&r.node.isInline)return Cn(n,new E(e>0?r.$to:r.$from));{let s=nd(n.state,e);return s?Cn(n,s):!1}}}function Zo(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function ri(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function qr(n,e){return e<0?Wv(n):jv(n)}function Wv(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let s,i,o=!1;for(gt&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(ri(l,-1))s=t,i=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(ly(t))break;{let l=t.previousSibling;for(;l&&ri(l,-1);)s=t.parentNode,i=Ne(l),l=l.previousSibling;if(l)t=l,r=Zo(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?rd(n,t,r):s&&rd(n,s,i)}function jv(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let s=Zo(t),i,o;for(;;)if(r{n.state==s&&sn(n)},50)}function Rg(n,e){let t=n.state.doc.resolve(e);if(!(Ie||Kg)&&t.parent.inlineContent){let s=n.coordsAtPos(e);if(e>t.start()){let i=n.coordsAtPos(e-1),o=(i.top+i.bottom)/2;if(o>s.top&&o1)return i.lefts.top&&o1)return i.left>s.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Ng(n,e,t){let r=n.state.selection;if(r instanceof E&&!r.empty||t.indexOf("s")>-1||pt&&t.indexOf("m")>-1)return!1;let{$from:s,$to:i}=r;if(!s.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=nd(n.state,e);if(o&&o instanceof M)return Cn(n,o)}if(!s.parent.inlineContent){let o=e<0?s:i,l=r instanceof Re?I.near(o,e):I.findFrom(o,e);return l?Cn(n,l):!1}return!1}function Ig(n,e){if(!(n.state.selection instanceof E))return!0;let{$head:t,$anchor:r,empty:s}=n.state.selection;if(!t.sameParent(r))return!0;if(!s)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let i=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(i&&!i.isText){let o=n.state.tr;return e<0?o.delete(t.pos-i.nodeSize,t.pos):o.delete(t.pos,t.pos+i.nodeSize),n.dispatch(o),!0}return!1}function Dg(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function Kv(n){if(!_e||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Dg(n,r,"true"),setTimeout(()=>Dg(n,r,"false"),20)}return!1}function Yv(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function Gv(n,e){let t=e.keyCode,r=Yv(e);if(t==8||pt&&t==72&&r=="c")return Ig(n,-1)||qr(n,-1);if(t==46&&!e.shiftKey||pt&&t==68&&r=="c")return Ig(n,1)||qr(n,1);if(t==13||t==27)return!0;if(t==37||pt&&t==66&&r=="c"){let s=t==37?Rg(n,n.state.selection.from)=="ltr"?-1:1:-1;return Mg(n,s,r)||qr(n,s)}else if(t==39||pt&&t==70&&r=="c"){let s=t==39?Rg(n,n.state.selection.from)=="ltr"?1:-1:1;return Mg(n,s,r)||qr(n,s)}else{if(t==38||pt&&t==80&&r=="c")return Ng(n,-1,r)||qr(n,-1);if(t==40||pt&&t==78&&r=="c")return Kv(n)||Ng(n,1,r)||qr(n,1);if(r==(pt?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function pd(n,e){n.someProp("transformCopied",f=>{e=f(e,n)});let t=[],{content:r,openStart:s,openEnd:i}=e;for(;s>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){s--,i--;let f=r.firstChild;t.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=n.someProp("clipboardSerializer")||Xt.fromSchema(n.state.schema),l=fy(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,u,d=0;for(;c&&c.nodeType==1&&(u=hy[c.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let p=l.createElement(u[f]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),d++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${s} ${i}${d?` -${d}`:""} ${JSON.stringify(t)}`);let h=n.someProp("clipboardTextSerializer",f=>f(e,n))||e.content.textBetween(0,e.content.size,` +"use strict";var lu=Object.defineProperty;var dv=Object.getOwnPropertyDescriptor;var hv=Object.getOwnPropertyNames;var fv=Object.prototype.hasOwnProperty;var pv=(n,e)=>{for(var t in e)lu(n,t,{get:e[t],enumerable:!0})},mv=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of hv(e))!fv.call(n,s)&&s!==t&&lu(n,s,{get:()=>e[s],enumerable:!(r=dv(e,s))||r.enumerable});return n};var gv=n=>mv(lu({},"__esModule",{value:!0}),n);var jP={};pv(jP,{default:()=>ru});module.exports=gv(jP);var T=require("obsidian");function Pe(n){this.content=n}Pe.prototype={constructor:Pe,find:function(n){for(var e=0;e>1}};Pe.from=function(n){if(n instanceof Pe)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new Pe(e)};var au=Pe;function pm(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let s=n.child(r),i=e.child(r);if(s==i){t+=s.nodeSize;continue}if(!s.sameMarkup(i))return t;if(s.isText&&s.text!=i.text){let o=s.text,l=i.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&h>0&&c[d-1]==u[h-1];)d--,h--,t--,r--;return d&&h&&d=56320&&n<57344}function ym(n){return n>=55296&&n<56320}var k=class n{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,s+l,i||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,s+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,s){let i="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?s?typeof s=="function"?s(l):s:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:i+=r),i+=c},0),i}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,s=this.content.slice(),i=0;for(t.isText&&t.sameMarkup(r)&&(s[s.length-1]=t.withText(t.text+r.text),i=1);ie)for(let i=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),s+=l.nodeSize),o=a}return new n(r,s)}cutByIndex(e,t){return e==t?n.empty:e==0&&t==this.content.length?this:new n(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let s=this.content.slice(),i=this.size+t.nodeSize-r.nodeSize;return s[e]=t,new n(s,i)}addToStart(e){return new n([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new n(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let s=this.child(t),i=r+s.nodeSize;if(i>=e)return i==e?Lo(t+1,i):Lo(t,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return n.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return n.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return n.empty;let t,r=0;for(let s=0;sthis.type.rank&&(t||(t=e.slice(0,s)),t.push(this),r=!0),t&&t.push(i)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-s.type.rank),t}};j.none=[];var jn=class extends Error{},S=class n{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=km(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new n(r,this.openStart,this.openEnd)}removeBetween(e,t){return new n(wm(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return n.empty;let r=t.openStart||0,s=t.openEnd||0;if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new n(k.fromJSON(e,t.content),r,s)}static maxOpen(e,t=!0){let r=0,s=0;for(let i=e.firstChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=e.lastChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.lastChild)s++;return new n(e,r,s)}};S.empty=new S(k.empty,0,0);function wm(n,e,t){let{index:r,offset:s}=n.findIndex(e),i=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(s==e||i.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,i.copy(wm(i.content,e-s-1,t-s-1)))}function km(n,e,t,r,s,i){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return i&&r<=0&&s<=0&&!i.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=km(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?s-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function yv(n,e,t){if(t.openStart>n.depth)throw new jn("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new jn("Inconsistent open depths");return bm(n,e,t,0)}function bm(n,e,t,r){let s=n.index(r),i=n.node(r);if(s==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function Hs(n,e,t,r){let s=(e||n).node(t),i=0,o=e?e.index(t):s.childCount;n&&(i=n.index(t),n.depth>t?i++:n.textOffset&&(Hn(n.nodeAfter,r),i++));for(let l=i;ls&&uu(n,e,s+1),o=r.depth>s&&uu(t,r,s+1),l=[];return Hs(null,n,s,l),i&&o&&e.index(s)==t.index(s)?(xm(i,o),Hn(Wn(i,Sm(n,e,t,r,s+1)),l)):(i&&Hn(Wn(i,$o(n,e,s+1)),l),Hs(e,t,s,l),o&&Hn(Wn(o,$o(t,r,s+1)),l)),Hs(r,null,s,l),new k(l)}function $o(n,e,t){let r=[];if(Hs(null,n,t,r),n.depth>t){let s=uu(n,e,t+1);Hn(Wn(s,$o(n,e,t+1)),r)}return Hs(e,null,t,r),new k(r)}function wv(n,e){let t=e.depth-n.openStart,s=e.node(t).copy(n.content);for(let i=t-1;i>=0;i--)s=e.node(i).copy(k.from(s));return{start:s.resolveNoCache(n.openStart+t),end:s.resolveNoCache(s.content.size-n.openEnd-t)}}var Uo=class n{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],s=e.child(t);return r?e.child(t).cut(r):s}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],s=t==0?0:this.path[t*3-1]+1;for(let i=0;i0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new qn(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],s=0,i=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(i),c=i-a;if(r.push(o,l,s+a),!c||(o=o.child(l),o.isText))break;i=c-1,s+=a+1}return new n(t,r,i)}static resolveCached(e,t){let r=im.get(e);if(r)for(let i=0;ie&&this.nodesBetween(e,t,i=>(r.isInSet(i.marks)&&(s=!0),!s)),s}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),vm(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=k.empty,s=0,i=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,s,i),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=s;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let s=k.fromJSON(e,t.content),i=e.nodeType(t.type).create(t.attrs,s,r);return i.type.checkAttrs(i.attrs),i}};Qe.prototype.text=void 0;var hu=class n extends Qe{constructor(e,t,r,s){if(super(e,t,null,s),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):vm(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new n(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new n(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function vm(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var Jn=class n{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new fu(e,t);if(r.next==null)return n.empty;let s=Cm(r);r.next&&r.err("Unexpected trailing text");let i=Ev(Av(s));return Mv(i,r),i}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let s=0;s{let i=s+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return i}).join(` +`)}};Jn.empty=new Jn(!0);var fu=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}};function Cm(n){let e=[];do e.push(xv(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function xv(n){let e=[];do e.push(Sv(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Sv(n){let e=Tv(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=vv(n,e);else break;return e}function om(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function vv(n,e){let t=om(n),r=t;return n.eat(",")&&(n.next!="}"?r=om(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Cv(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let s=[];for(let i in t){let o=t[i];o.isInGroup(e)&&s.push(o)}return s.length==0&&n.err("No node type or group '"+e+"' found"),s}function Tv(n){if(n.eat("(")){let e=Cm(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Cv(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Av(n){let e=[[]];return s(i(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function s(o,l){o.forEach(a=>a.to=l)}function i(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(i(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=i(o.exprs[a],l);if(a==o.exprs.length-1)return c;s(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),s(i(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return s(i(o.expr,l),a),s(i(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(i(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u{c||s.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let i=e[r.join(",")]=new Jn(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Em(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Qe(this,this.computeAttrs(e),k.from(t),j.setFrom(r))}createChecked(e=null,t,r){return t=k.from(t),this.checkContent(t),new Qe(this,this.computeAttrs(e),t,j.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=k.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let s=this.contentMatch.matchFragment(t),i=s&&s.fillBefore(k.empty,!0);return i?new Qe(this,e,t.append(i),j.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[i]=new n(i,t,o));let s=t.spec.topNode||"doc";if(!r[s])throw new RangeError("Schema is missing its top node type ('"+s+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let i in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Rv(n,e,t){let r=t.split("|");return s=>{let i=s===null?"null":typeof s;if(r.indexOf(i)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${i}`)}}var pu=class{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Rv(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}},js=class n{constructor(e,t,r,s){this.name=e,this.rank=t,this.schema=r,this.spec=s,this.attrs=Rm(e,s.attrs),this.excluded=null;let i=Am(this.attrs);this.instance=i?new j(this,i):null}create(e=null){return!e&&this.instance?this.instance:new j(this,Em(this.attrs,e))}static compile(e,t){let r=Object.create(null),s=0;return e.forEach((i,o)=>r[i]=new n(i,s++,t,o)),r}removeFromSet(e){for(var t=0;t-1}},$r=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let s in e)t[s]=e[s];t.nodes=au.from(e.nodes),t.marks=au.from(e.marks||{}),this.nodes=Fo.compile(this.spec.nodes,this),this.marks=js.compile(this.spec.marks,this);let r=Object.create(null);for(let s in this.nodes){if(s in this.marks)throw new RangeError(s+" can not be both a node and a mark");let i=this.nodes[s],o=i.spec.content||"",l=i.spec.marks;if(i.contentMatch=r[o]||(r[o]=Jn.parse(o,this.nodes)),i.inlineContent=i.contentMatch.inlineContent,i.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!i.isInline||!i.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=i}i.markSet=l=="_"?null:l?am(this,l.split(" ")):l==""||!i.inlineContent?[]:null}for(let s in this.marks){let i=this.marks[s],o=i.spec.excludes;i.excluded=o==null?[i]:o==""?[]:am(this,o.split(" "))}this.nodeFromJSON=s=>Qe.fromJSON(this,s),this.markFromJSON=s=>j.fromJSON(this,s),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,s){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Fo){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,s)}text(e,t){let r=this.nodes.text;return new hu(r,r.defaultAttrs,e,j.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}};function am(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Nv(n){return n.tag!=null}function Iv(n){return n.style!=null}var Ot=class n{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(s=>{if(Nv(s))this.tags.push(s);else if(Iv(s)){let i=/[^=]*/.exec(s.style)[0];r.indexOf(i)<0&&r.push(i),this.styles.push(s)}}),this.normalizeLists=!this.tags.some(s=>{if(!/^(ul|ol)\b/.test(s.tag)||!s.node)return!1;let i=e.nodes[s.node];return i.contentMatch.matchType(i)})}parse(e,t={}){let r=new Vo(this,t,!1);return r.addAll(e,j.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Vo(this,t,!0);return r.addAll(e,j.none,t.from,t.to),S.maxOpen(r.finish())}matchTag(e,t,r){for(let s=r?this.tags.indexOf(r)+1:0;se.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(s){let i=s.priority==null?50:s.priority,o=0;for(;o{r(o=um(o)),o.mark||o.ignore||o.clearMark||(o.mark=s)})}for(let s in e.nodes){let i=e.nodes[s].spec.parseDOM;i&&i.forEach(o=>{r(o=um(o)),o.node||o.ignore||o.mark||(o.node=s)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new n(e,n.schemaRules(e)))}},Nm={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Dv={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Im={ol:!0,ul:!0},qs=1,mu=2,Ws=4;function cm(n,e,t){return e!=null?(e?qs:0)|(e==="full"?mu:0):n&&n.whitespace=="pre"?qs|mu:t&~Ws}var zr=class{constructor(e,t,r,s,i,o){this.type=e,this.attrs=t,this.marks=r,this.solid=s,this.options=o,this.content=[],this.activeMarks=j.none,this.match=i||(o&Ws?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(k.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,s;return(s=r.findWrapping(e.type))?(this.match=r,s):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&qs)){let r=this.content[this.content.length-1],s;if(r&&r.isText&&(s=/[ \t\r\n\u000c]+$/.exec(r.text))){let i=r;r.text.length==s[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-s[0].length))}}let t=k.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(k.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Nm.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},Vo=class{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let s=t.topNode,i,o=cm(null,t.preserveWhitespace,0)|(r?Ws:0);s?i=new zr(s.type,s.attrs,j.none,!0,t.topMatch||s.type.contentMatch,o):r?i=new zr(null,null,j.none,!0,null,o):i=new zr(e.schema.topNodeType,null,j.none,!0,null,o),this.nodes=[i],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,s=this.top,i=s.options&mu?"full":this.localPreserveWS||(s.options&qs)>0,{schema:o}=this.parser;if(i==="full"||s.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(i)if(i==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,s){let i,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(i=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(s)this.addElement(e,r,s);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}i&&this.sync(l)&&this.open--}addAll(e,t,r,s){let i=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=s==null?null:e.childNodes[s];o!=l;o=o.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(o,t);this.findAtPoint(e,i)}findPlace(e,t,r){let s,i;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!s||s.length>c.length+l)&&(s=c,i=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!s)return null;this.sync(i);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):dm(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new zr(e,t,a,s,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=qs)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let s=r.length-1;s>=0;s--)e+=r[s].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,s=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),i=-(r?r.depth+1:0)+(s?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=i;a--)if(o(l-1,a))return!0;return!1}else{let u=a>0||a==0&&s?this.nodes[a].type:r&&a>=i?r.node(a-i).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}};function Ov(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Im.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function Pv(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function um(n){let e={};for(let t in n)e[t]=n[t];return e}function dm(n,e){let t=e.schema.nodes;for(let r in t){let s=t[r];if(!s.allowsMarkType(n))continue;let i=[],o=l=>{i.push(l);for(let a=0;a{if(i.length||o.marks.length){let l=0,a=0;for(;l=0;s--){let i=this.serializeMark(e.marks[s],e.isInline,t);i&&((i.contentDOM||i.dom).appendChild(r),r=i.dom)}return r}serializeMark(e,t,r={}){let s=this.marks[e.type.name];return s&&Bo(_o(r),s(e,t),null,e.attrs)}static renderSpec(e,t,r=null,s){return typeof t=="string"?{dom:e.createTextNode(t)}:Bo(e,t,r,s)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new n(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=hm(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return hm(e.marks)}};function hm(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function _o(n){return n.document||window.document}var fm=new WeakMap;function Lv(n){let e=fm.get(n);return e===void 0&&fm.set(n,e=_v(n)),e}function _v(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let s=0;s-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 o=s.indexOf(" ");o>0&&(t=s.slice(0,o),s=s.slice(o+1));let l,a=t?n.createElementNS(t,s):n.createElement(s),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let d in c)if(c[d]!=null){let h=d.indexOf(" ");h>0?a.setAttributeNS(d.slice(0,h),d.slice(h+1),c[d]):d=="style"&&a.style?a.style.cssText=c[d]:a.setAttribute(d,c[d])}}for(let d=u;du)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof h=="string")a.appendChild(n.createTextNode(h));else{let{dom:f,contentDOM:p}=Bo(n,h,t,r);if(a.appendChild(f),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}var Pm=65535,Lm=Math.pow(2,16);function zv(n,e){return n+e*Lm}function Dm(n){return n&Pm}function $v(n){return(n-(n&Pm))/Lm}var _m=1,Bm=2,Ho=4,zm=8,Ys=class{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&zm)>0}get deletedBefore(){return(this.delInfo&(_m|Ho))>0}get deletedAfter(){return(this.delInfo&(Bm|Ho))>0}get deletedAcross(){return(this.delInfo&Ho)>0}},Qt=class n{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&n.empty)return n.empty}recover(e){let t=0,r=Dm(e);if(!this.inverted)for(let s=0;se)break;let c=this.ranges[l+i],u=this.ranges[l+o],d=a+c;if(e<=d){let h=c?e==a?-1:e==d?1:t:t,f=a+s+(h<0?0:u);if(r)return f;let p=e==(t<0?a:d)?null:zv(l/3,e-a),m=e==a?Bm:e==d?_m:Ho;return(t<0?e!=a:e!=d)&&(m|=zm),new Ys(f,m,p)}s+=u-c}return r?e+s:new Ys(e+s,0,null)}touches(e,t){let r=0,s=Dm(t),i=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+i],u=a+c;if(e<=u&&l==s*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let s=0,i=0;s=0;t--){let s=e.getMirror(t);this.appendMap(e._maps[t].invert(),s!=null&&s>t?r-s-1:void 0)}}invert(){let e=new n;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;ri&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),s),t.openStart,t.openEnd);return Me.fromReplace(e,this.from,this.to,i)}invert(){return new Zt(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};ve.jsonID("addMark",Xs);var Zt=class n extends ve{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new S(xu(t.content,s=>s.mark(this.mark.removeFromSet(s.marks)),e),t.openStart,t.openEnd);return Me.fromReplace(e,this.from,this.to,r)}invert(){return new Xs(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new n(t.pos,r.pos,this.mark)}merge(e){return e instanceof n&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new n(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new n(t.from,t.to,e.markFromJSON(t.mark))}};ve.jsonID("removeMark",Zt);var Qs=class n extends ve{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Me.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Me.fromReplace(e,this.pos,this.pos+1,new S(k.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let s=0;sr.pos?null:new n(t.pos,r.pos,s,i,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new n(t.from,t.to,t.gapFrom,t.gapTo,S.fromJSON(e,t.slice),t.insert,!!t.structure)}};ve.jsonID("replaceAround",ue);function ku(n,e,t){let r=n.resolve(e),s=t-e,i=r.depth;for(;s>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,s--;if(s>0){let o=r.node(i).maybeChild(r.indexAfter(i));for(;s>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,s--}}return!1}function Uv(n,e,t,r){let s=[],i=[],o,l;n.doc.nodesBetween(e,t,(a,c,u)=>{if(!a.isInline)return;let d=a.marks;if(!r.isInSet(d)&&u.type.allowsMarkType(r.type)){let h=Math.max(c,e),f=Math.min(c+a.nodeSize,t),p=r.addToSet(d);for(let m=0;mn.step(a)),i.forEach(a=>n.step(a))}function Fv(n,e,t,r){let s=[],i=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;i++;let a=null;if(r instanceof js){let c=o.marks,u;for(;u=r.isInSet(c);)(a||(a=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let u=0;un.step(new Zt(o.from,o.to,o.style)))}function Su(n,e,t,r=t.contentMatch,s=!0){let i=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Vv(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function en(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,s=0,i=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+s,a=n.$to.indexAfter(r)-i;if(rt;p--)m||r.index(p)>0?(m=!0,u=k.from(r.node(p).copy(u)),d++):a--;let h=k.empty,f=0;for(let p=i,m=!1;p>t;p--)m||s.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=k.from(t[o].type.create(t[o].attrs,r))}let s=e.start,i=e.end;n.step(new ue(s,i,s,i,new S(r,0,0),t.length,!0))}function Jv(n,e,t,r,s){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof s=="function"?s(o):s;if(o.isTextblock&&!o.hasMarkup(r,a)&&Kv(n.doc,n.mapping.slice(i).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!p?c=!1:!f&&p&&(c=!0)}c===!1&&Um(n,o,l,i),Su(n,n.mapping.slice(i).map(l,1),r,void 0,c===null);let u=n.mapping.slice(i),d=u.map(l,1),h=u.map(l+o.nodeSize,1);return n.step(new ue(d,h,d+1,h-1,new S(k.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&$m(n,o,l,i),!1}})}function $m(n,e,t,r){e.forEach((s,i)=>{if(s.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(s.text);){let a=n.mapping.slice(r).map(t+1+i+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function Um(n,e,t,r){e.forEach((s,i)=>{if(s.type==s.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+i);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function Kv(n,e,t){let r=n.resolve(e),s=r.index();return r.parent.canReplaceWith(s,s+1,t)}function Yv(n,e,t,r,s){let i=n.doc.nodeAt(e);if(!i)throw new RangeError("No node at given position");t||(t=i.type);let o=t.create(r,null,s||i.marks);if(i.isLeaf)return n.replaceWith(e,e+i.nodeSize,o);if(!t.validContent(i.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new ue(e,e+i.nodeSize,e+1,e+i.nodeSize-1,new S(k.from(o),0,0),1,!0))}function ot(n,e,t=1,r){let s=n.resolve(e),i=s.depth-t,o=r&&r[r.length-1]||s.parent;if(i<0||s.parent.type.spec.isolating||!s.parent.canReplace(s.index(),s.parent.childCount)||!o.type.validContent(s.parent.content.cutByIndex(s.index(),s.parent.childCount)))return!1;for(let c=s.depth-1,u=t-2;c>i;c--,u--){let d=s.node(c),h=s.index(c);if(d.type.spec.isolating)return!1;let f=d.content.cutByIndex(h,d.childCount),p=r&&r[u+1];p&&(f=f.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[u]||d;if(!d.canReplace(h+1,d.childCount)||!m.type.validContent(f))return!1}let l=s.indexAfter(i),a=r&&r[0];return s.node(i).canReplaceWith(l,l,a?a.type:s.node(i+1).type)}function Gv(n,e,t=1,r){let s=n.doc.resolve(e),i=k.empty,o=k.empty;for(let l=s.depth,a=s.depth-t,c=t-1;l>a;l--,c--){i=k.from(s.node(l).copy(i));let u=r&&r[c];o=k.from(u?u.type.create(u.attrs,o):s.node(l).copy(o))}n.step(new Re(e,e,new S(i.append(o),t,t),!0))}function ft(n,e){let t=n.resolve(e),r=t.index();return Fm(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Xv(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let s=0;s0?(i=r.node(s+1),l++,o=r.node(s).maybeChild(l)):(i=r.node(s).maybeChild(l-1),o=r.node(s+1)),i&&!i.isTextblock&&Fm(i,o)&&r.node(s).canReplace(l,l+1))return e;if(s==0)break;e=t<0?r.before(s):r.after(s)}}function Qv(n,e,t){let r=null,{linebreakReplacement:s}=n.doc.type.schema,i=n.doc.resolve(e-t),o=i.node().type;if(s&&o.inlineContent){let u=o.whitespace=="pre",d=!!o.contentMatch.matchType(s);u&&!d?r=!1:!u&&d&&(r=!0)}let l=n.steps.length;if(r===!1){let u=n.doc.resolve(e+t);Um(n,u.node(),u.before(),l)}o.inlineContent&&Su(n,e+t-1,o,i.node().contentMatchAt(i.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new Re(c,a.map(e+t,-1),S.empty,!0)),r===!0){let u=n.doc.resolve(c);$m(n,u.node(),u.before(),n.steps.length)}return n}function Zv(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let s=r.depth-1;s>=0;s--){let i=r.index(s);if(r.node(s).canReplaceWith(i,i,t))return r.before(s+1);if(i>0)return null}if(r.parentOffset==r.parent.content.size)for(let s=r.depth-1;s>=0;s--){let i=r.indexAfter(s);if(r.node(s).canReplaceWith(i,i,t))return r.after(s+1);if(i=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),u=!1;if(i==1)u=c.canReplace(a,a,s);else{let d=c.contentMatchAt(a).findWrapping(s.firstChild.type);u=d&&c.canReplaceWith(a,a,d[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Zs(n,e,t=e,r=S.empty){if(e==t&&!r.size)return null;let s=n.resolve(e),i=n.resolve(t);return Vm(s,i,r)?new Re(e,t,r):new bu(s,i,r).fit()}function Vm(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}var bu=class{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=k.empty;for(let s=0;s<=e.depth;s++){let i=e.node(s);this.frontier.push({type:i.type,match:i.contentMatchAt(e.indexAfter(s))})}for(let s=e.depth;s>0;s--)this.placed=k.from(e.node(s).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,s=this.close(e<0?this.$to:r.doc.resolve(e));if(!s)return null;let i=this.placed,o=r.depth,l=s.depth;for(;o&&l&&i.childCount==1;)i=i.firstChild.content,o--,l--;let a=new S(i,o,l);return e>-1?new ue(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new Re(r.pos,s.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,s=this.unplaced.openEnd;r1&&(s=0),i.type.spec.isolating&&s<=r){e=r;break}t=i.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let s,i=null;r?(i=yu(this.unplaced.content,r-1).firstChild,s=i.content):s=this.unplaced.content;let o=s.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],u,d=null;if(t==1&&(o?c.matchType(o.type)||(d=c.fillBefore(k.from(o),!1)):i&&a.compatibleContent(i.type)))return{sliceDepth:r,frontierDepth:l,parent:i,inject:d};if(t==2&&o&&(u=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:i,wrap:u};if(i&&c.matchType(i.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced,s=yu(e,t);return!s.childCount||s.firstChild.isLeaf?!1:(this.unplaced=new S(e,t+1,Math.max(r,s.size+t>=e.size-r?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,s=yu(e,t);if(s.childCount<=1&&t>0){let i=e.size-t<=t+s.size;this.unplaced=new S(Js(e,t-1,1),t-1,i?t-1:r)}else this.unplaced=new S(Js(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:s,wrap:i}){for(;this.depth>t;)this.closeFrontierNode();if(i)for(let m=0;m1||a==0||m.content.size)&&(d=g,u.push(Hm(m.mark(h.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?f:-1)))}let p=c==l.childCount;p||(f=-1),this.placed=Ks(this.placed,t,k.from(u)),this.frontier[t].match=d,p&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&s==this.$to.end(--r);)++s;return s}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:s}=this.frontier[t],i=t=0;l--){let{match:a,type:c}=this.frontier[l],u=wu(e,l,c,a,!0);if(!u||u.childCount)continue e}return{depth:t,fit:o,move:i?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=Ks(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let s=e.node(r),i=s.type.contentMatch.fillBefore(s.content,!0,e.index(r));this.openFrontierNode(s.type,s.attrs,i)}return e}openFrontierNode(e,t=null,r){let s=this.frontier[this.depth];s.match=s.match.matchType(e),this.placed=Ks(this.placed,this.depth,k.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(k.empty,!0);t.childCount&&(this.placed=Ks(this.placed,this.frontier.length,t))}};function Js(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(Js(n.firstChild.content,e-1,t)))}function Ks(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(Ks(n.lastChild.content,e-1,t)))}function yu(n,e){for(let t=0;t1&&(r=r.replaceChild(0,Hm(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(k.empty,!0)))),n.copy(r)}function wu(n,e,t,r,s){let i=n.node(e),o=s?n.indexAfter(e):n.index(e);if(o==i.childCount&&!t.compatibleContent(i.type))return null;let l=r.fillBefore(i.content,!0,o);return l&&!e1(t,i.content,o)?l:null}function e1(n,e,t){for(let r=t;r0;h--,f--){let p=s.node(h).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(h)>-1?l=h:s.before(h)==f&&o.splice(1,0,-h)}let a=o.indexOf(l),c=[],u=r.openStart;for(let h=r.content,f=0;;f++){let p=h.firstChild;if(c.push(p),f==r.openStart)break;h=p.content}for(let h=u-1;h>=0;h--){let f=c[h],p=t1(f.type);if(p&&!f.sameMarkup(s.node(Math.abs(l)-1)))u=h;else if(p||!f.type.isTextblock)break}for(let h=r.openStart;h>=0;h--){let f=(h+u+1)%(r.openStart+1),p=c[f];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>d));h--){let f=o[h];f<0||(e=s.before(f),t=i.after(f))}}function Wm(n,e,t,r,s){if(er){let i=s.contentMatchAt(0),o=i.fillBefore(n).append(n);n=o.append(i.matchFragment(o).fillBefore(k.empty,!0))}return n}function r1(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let s=Zv(n.doc,e,r.type);s!=null&&(e=t=s)}n.replaceRange(e,t,new S(k.from(r),0,0))}function s1(n,e,t){let r=n.doc.resolve(e),s=n.doc.resolve(t);if(r.parent.isTextblock&&s.parent.isTextblock&&r.start()!=s.start()&&r.parentOffset==0&&s.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=s.depth;a>o;a--)s.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=s.depth;a>0&&t==s.start(a);a--)t=s.before(a);r=n.doc.resolve(e),s=n.doc.resolve(t)}}let i=jm(r,s);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),s.indexAfter(l-1))))return n.delete(r.before(l),s.after(l))}for(let o=1;o<=r.depth&&o<=s.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&s.end(o)-t!=s.depth-o&&r.start(o-1)==s.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),s.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function jm(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let s=r;s>=0;s--){let i=n.start(s);if(ie.pos+(e.depth-s)||n.node(s).type.spec.isolating||e.node(s).type.spec.isolating)break;(i==e.start(s)||s==n.depth&&s==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&s&&e.start(s-1)==i-1)&&t.push(s)}return t}var Wo=class n extends ve{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return Me.fail("No node at attribute step's position");let r=Object.create(null);for(let i in t.attrs)r[i]=t.attrs[i];r[this.attr]=this.value;let s=t.type.create(r,null,t.marks);return Me.fromReplace(e,this.pos,this.pos+1,new S(k.from(s),0,t.isLeaf?0:1))}getMap(){return Qt.empty}invert(e){return new n(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new n(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new n(t.pos,t.attr,t.value)}};ve.jsonID("attr",Wo);var jo=class n extends ve{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let s in e.attrs)t[s]=e.attrs[s];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return Me.ok(r)}getMap(){return Qt.empty}invert(e){return new n(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new n(t.attr,t.value)}};ve.jsonID("docAttr",jo);var Fr=class extends Error{};Fr=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Fr.prototype=Object.create(Error.prototype);Fr.prototype.constructor=Fr;Fr.prototype.name="TransformError";var Sn=class{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Gs}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Fr(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=S.empty){let s=Zs(this.doc,e,t,r);return s&&this.step(s),this}replaceWith(e,t,r){return this.replace(e,t,new S(k.from(r),0,0))}delete(e,t){return this.replace(e,t,S.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return n1(this,e,t,r),this}replaceRangeWith(e,t,r){return r1(this,e,t,r),this}deleteRange(e,t){return s1(this,e,t),this}lift(e,t){return Hv(this,e,t),this}join(e,t=1){return Qv(this,e,t),this}wrap(e,t){return qv(this,e,t),this}setBlockType(e,t=e,r,s=null){return Jv(this,e,t,r,s),this}setNodeMarkup(e,t,r=null,s){return Yv(this,e,t,r,s),this}setNodeAttribute(e,t,r){return this.step(new Wo(e,t,r)),this}setDocAttribute(e,t){return this.step(new jo(e,t)),this}addNodeMark(e,t){return this.step(new Qs(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof j)t.isInSet(r.marks)&&this.step(new Ur(e,t));else{let s=r.marks,i,o=[];for(;i=t.isInSet(s);)o.push(new Ur(e,i)),s=i.removeFromSet(s);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Gv(this,e,t,r),this}addMark(e,t,r){return Uv(this,e,t,r),this}removeMark(e,t,r){return Fv(this,e,t,r),this}clearIncompatible(e,t,r){return Su(this,e,t,r),this}};var vu=Object.create(null),N=class{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new Wr(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;i--){let o=t<0?Hr(e.node(0),e.node(i),e.before(i+1),e.index(i),t,r):Hr(e.node(0),e.node(i),e.after(i+1),e.index(i)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new Ne(e.node(0))}static atStart(e){return Hr(e,e,0,0,1)||new Ne(e)}static atEnd(e){return Hr(e,e,e.content.size,e.childCount,-1)||new Ne(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=vu[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in vu)throw new RangeError("Duplicate use of selection JSON ID "+e);return vu[e]=t,t.prototype.jsonID=e,t}getBookmark(){return A.between(this.$anchor,this.$head).getBookmark()}};N.prototype.visible=!0;var Wr=class{constructor(e,t){this.$from=e,this.$to=t}},qm=!1;function Jm(n){!qm&&!n.parent.inlineContent&&(qm=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var A=class n extends N{constructor(e,t=e){Jm(e),Jm(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return N.near(r);let s=e.resolve(t.map(this.anchor));return new n(s.parent.inlineContent?s:r,r)}replace(e,t=S.empty){if(super.replace(e,t),t==S.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof n&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Ko(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new n(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let s=e.resolve(t);return new this(s,r==t?s:e.resolve(r))}static between(e,t,r){let s=e.pos-t.pos;if((!r||s)&&(r=s>=0?1:-1),!t.parent.inlineContent){let i=N.findFrom(t,r,!0)||N.findFrom(t,-r,!0);if(i)t=i.$head;else return N.near(t,r)}return e.parent.inlineContent||(s==0?e=t:(e=(N.findFrom(e,-r,!0)||N.findFrom(e,r,!0)).$anchor,e.pos0?0:1);s>0?o=0;o+=s){let l=e.child(o);if(l.isAtom){if(!i&&M.isSelectable(l))return M.create(n,t-(s<0?l.nodeSize:0))}else{let a=Hr(n,l,t+s,s<0?l.childCount:0,s,i);if(a)return a}t+=l.nodeSize*s}return null}function Km(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=u)}),n.setSelection(N.near(n.doc.resolve(o),t))}var Ym=1,Jo=2,Gm=4,Au=class extends Sn{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Jo,this}ensureMarks(e){return j.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Jo)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Jo,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||j.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let s=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(s.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let i=this.storedMarks;if(!i){let o=this.doc.resolve(t);i=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,s.text(e,i)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(N.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Gm,this}get scrolledIntoView(){return(this.updated&Gm)>0}};function Xm(n,e){return!e||!n?n:n.bind(e)}var Yn=class{constructor(e,t,r){this.name=e,this.init=Xm(t.init,r),this.apply=Xm(t.apply,r)}},o1=[new Yn("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Yn("selection",{init(n,e){return n.selection||N.atStart(e.doc)},apply(n){return n.selection}}),new Yn("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Yn("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})],ei=class{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=o1.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Yn(r.key,r.spec.state,r))})}},Yo=class n{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let s=e[r],i=s.spec.state;i&&i.toJSON&&(t[r]=i.toJSON.call(s,this[s.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let s=new ei(e.schema,e.plugins),i=new n(s);return s.fields.forEach(o=>{if(o.name=="doc")i.doc=Qe.fromJSON(e.schema,t.doc);else if(o.name=="selection")i.selection=N.fromJSON(i.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(i.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){i[o.name]=c.fromJSON.call(a,e,t[l],i);return}}i[o.name]=o.init(e,i)}}),i}};function Qm(n,e,t){for(let r in n){let s=n[r];s instanceof Function?s=s.bind(e):r=="handleDOMEvents"&&(s=Qm(s,e,{})),t[r]=s}return t}var O=class{constructor(e){this.spec=e,this.props={},e.props&&Qm(e.props,this,this.props),this.key=e.key?e.key.key:Zm("plugin")}getState(e){return e[this.key]}},Cu=Object.create(null);function Zm(n){return n in Cu?n+"$"+ ++Cu[n]:(Cu[n]=0,n+"$")}var P=class{constructor(e="key"){this.key=Zm(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}};var tg=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function ng(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}var Mu=(n,e,t)=>{let r=ng(n,t);if(!r)return!1;let s=Nu(r);if(!s){let o=r.blockRange(),l=o&&en(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let i=s.nodeBefore;if(dg(n,s,e,-1))return!0;if(r.parent.content.size==0&&(jr(i,"end")||M.isSelectable(i)))for(let o=r.depth;;o--){let l=Zs(n.doc,r.before(o),r.after(o),S.empty);if(l&&l.slice.size1)break}return i.isAtom&&s.depth==r.depth-1?(e&&e(n.tr.delete(s.pos-i.nodeSize,s.pos).scrollIntoView()),!0):!1},rg=(n,e,t)=>{let r=ng(n,t);if(!r)return!1;let s=Nu(r);return s?ig(n,s,e):!1},sg=(n,e,t)=>{let r=og(n,t);if(!r)return!1;let s=Ou(r);return s?ig(n,s,e):!1};function ig(n,e,t){let r=e.nodeBefore,s=r,i=e.pos-1;for(;!s.isTextblock;i--){if(s.type.spec.isolating)return!1;let u=s.lastChild;if(!u)return!1;s=u}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let c=Zs(n.doc,i,a,S.empty);if(!c||c.from!=i||c instanceof Re&&c.slice.size>=a-i)return!1;if(t){let u=n.tr.step(c);u.setSelection(A.create(u.doc,i)),t(u.scrollIntoView())}return!0}function jr(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}var Ru=(n,e,t)=>{let{$head:r,empty:s}=n.selection,i=r;if(!s)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;i=Nu(r)}let o=i&&i.nodeBefore;return!o||!M.isSelectable(o)?!1:(e&&e(n.tr.setSelection(M.create(n.doc,i.pos-o.nodeSize)).scrollIntoView()),!0)};function Nu(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function og(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=og(n,t);if(!r)return!1;let s=Ou(r);if(!s)return!1;let i=s.nodeAfter;if(dg(n,s,e,1))return!0;if(r.parent.content.size==0&&(jr(i,"start")||M.isSelectable(i))){let o=Zs(n.doc,r.before(),r.after(),S.empty);if(o&&o.slice.size{let{$head:r,empty:s}=n.selection,i=r;if(!s)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof M,s;if(r){if(t.node.isTextblock||!ft(n.doc,t.from))return!1;s=t.from}else if(s=Kn(n.doc,t.from,-1),s==null)return!1;if(e){let i=n.tr.join(s);r&&i.setSelection(M.create(i.doc,s-n.doc.resolve(s).nodeBefore.nodeSize)),e(i.scrollIntoView())}return!0},ag=(n,e)=>{let t=n.selection,r;if(t instanceof M){if(t.node.isTextblock||!ft(n.doc,t.to))return!1;r=t.to}else if(r=Kn(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},cg=(n,e)=>{let{$from:t,$to:r}=n.selection,s=t.blockRange(r),i=s&&en(s);return i==null?!1:(e&&e(n.tr.lift(s,i).scrollIntoView()),!0)},Pu=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function Lu(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let s=t.node(-1),i=t.indexAfter(-1),o=Lu(s.contentMatchAt(i));if(!o||!s.canReplaceWith(i,i,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(N.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},Bu=(n,e)=>{let t=n.selection,{$from:r,$to:s}=t;if(t instanceof Ne||r.parent.inlineContent||s.parent.inlineContent)return!1;let i=Lu(s.parent.contentMatchAt(s.indexAfter()));if(!i||!i.isTextblock)return!1;if(e){let o=(!r.parentOffset&&s.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let i=t.before();if(ot(n.doc,i))return e&&e(n.tr.split(i).scrollIntoView()),!0}let r=t.blockRange(),s=r&&en(r);return s==null?!1:(e&&e(n.tr.lift(r,s).scrollIntoView()),!0)};function l1(n){return(e,t)=>{let{$from:r,$to:s}=e.selection;if(e.selection instanceof M&&e.selection.node.isBlock)return!r.parentOffset||!ot(e.doc,r.pos)?!1:(t&&t(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let i=[],o,l,a=!1,c=!1;for(let f=r.depth;;f--)if(r.node(f).isBlock){a=r.end(f)==r.pos+(r.depth-f),c=r.start(f)==r.pos-(r.depth-f),l=Lu(r.node(f-1).contentMatchAt(r.indexAfter(f-1)));let m=n&&n(s.parent,a,r);i.unshift(m||(a&&l?{type:l}:null)),o=f;break}else{if(f==1)return!1;i.unshift(null)}let u=e.tr;(e.selection instanceof A||e.selection instanceof Ne)&&u.deleteSelection();let d=u.mapping.map(r.pos),h=ot(u.doc,d,i.length,i);if(h||(i[0]=l?{type:l}:null,h=ot(u.doc,d,i.length,i)),!h)return!1;if(u.split(d,i.length,i),!a&&c&&r.node(o).type!=l){let f=u.mapping.map(r.before(o)),p=u.doc.resolve(f);l&&r.node(o-1).canReplaceWith(p.index(),p.index()+1,l)&&u.setNodeMarkup(u.mapping.map(r.before(o)),l)}return t&&t(u.scrollIntoView()),!0}}var a1=l1();var ug=(n,e)=>{let{$from:t,to:r}=n.selection,s,i=t.sharedDepth(r);return i==0?!1:(s=t.before(i),e&&e(n.tr.setSelection(M.create(n.doc,s))),!0)},c1=(n,e)=>(e&&e(n.tr.setSelection(new Ne(n.doc))),!0);function u1(n,e,t){let r=e.nodeBefore,s=e.nodeAfter,i=e.index();return!r||!s||!r.type.compatibleContent(s.type)?!1:!r.content.size&&e.parent.canReplace(i-1,i)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(i,i+1)||!(s.isTextblock||ft(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function dg(n,e,t,r){let s=e.nodeBefore,i=e.nodeAfter,o,l,a=s.type.spec.isolating||i.type.spec.isolating;if(!a&&u1(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=s.contentMatchAt(s.childCount)).findWrapping(i.type))&&l.matchType(o[0]||i.type).validEnd){if(t){let f=e.pos+i.nodeSize,p=k.empty;for(let y=o.length-1;y>=0;y--)p=k.from(o[y].create(null,p));p=k.from(s.copy(p));let m=n.tr.step(new ue(e.pos-1,f,e.pos,f,new S(p,1,0),o.length,!0)),g=m.doc.resolve(f+2*o.length);g.nodeAfter&&g.nodeAfter.type==s.type&&ft(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&a?null:N.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),h=d&&en(d);if(h!=null&&h>=e.depth)return t&&t(n.tr.lift(d,h).scrollIntoView()),!0;if(c&&jr(i,"start",!0)&&jr(s,"end")){let f=s,p=[];for(;p.push(f),!f.isTextblock;)f=f.lastChild;let m=i,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(f.canReplace(f.childCount,f.childCount,m.content)){if(t){let y=k.empty;for(let b=p.length-1;b>=0;b--)y=k.from(p[b].copy(y));let w=n.tr.step(new ue(e.pos-p.length,e.pos+i.nodeSize,e.pos+g,e.pos+i.nodeSize-g,new S(y,p.length,0),0,!0));t(w.scrollIntoView())}return!0}}return!1}function hg(n){return function(e,t){let r=e.selection,s=n<0?r.$from:r.$to,i=s.depth;for(;s.node(i).isInline;){if(!i)return!1;i--}return s.node(i).isTextblock?(t&&t(e.tr.setSelection(A.create(e.doc,n<0?s.start(i):s.end(i)))),!0):!1}}var $u=hg(-1),Uu=hg(1);function fg(n,e=null){return function(t,r){let{$from:s,$to:i}=t.selection,o=s.blockRange(i),l=o&&Vr(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Fu(n,e=null){return function(t,r){let s=!1;for(let i=0;i{if(s)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)s=!0;else{let u=t.doc.resolve(c),d=u.index();s=u.parent.canReplaceWith(d,d+1,n)}})}if(!s)return!1;if(r){let i=t.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);i=new qn(a,a,e.depth),e.endIndex=0;u--)i=k.from(t[u].type.create(t[u].attrs,i));n.step(new ue(e.start-(r?2:0),e.end,e.start,e.end,new S(i,0,0),t.length,!0));let o=0;for(let u=0;uo.childCount>0&&o.firstChild.type==n);return i?t?r.node(i.depth-1).type==n?p1(e,t,n,i):m1(e,t,i):!0:!1}}function p1(n,e,t,r){let s=n.tr,i=r.end,o=r.$to.end(r.depth);im;p--)f-=s.child(p).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(t.start),o=i.nodeAfter;if(r.mapping.map(t.end)!=t.start+i.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==s.childCount,c=i.node(-1),u=i.index(-1);if(!c.canReplace(u+(l?0:1),u+1,o.content.append(a?k.empty:k.from(s))))return!1;let d=i.pos,h=d+o.nodeSize;return r.step(new ue(d-(l?1:0),h+(a?1:0),d+1,h-1,new S((l?k.empty:k.from(s.copy(k.empty))).append(a?k.empty:k.from(s.copy(k.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function gg(n){return function(e,t){let{$from:r,$to:s}=e.selection,i=r.blockRange(s,c=>c.childCount>0&&c.firstChild.type==n);if(!i)return!1;let o=i.startIndex;if(o==0)return!1;let l=i.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,u=k.from(c?n.create():null),d=new S(k.from(n.create(null,k.from(l.type.create(null,u)))),c?3:1,0),h=i.start,f=i.end;t(e.tr.step(new ue(h-(c?3:1),f,h,f,d,1,!0)).scrollIntoView())}return!0}}var Ie=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},Yr=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e},Ku=null,nn=function(n,e,t){let r=Ku||(Ku=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},g1=function(){Ku=null},nr=function(n,e,t,r){return t&&(yg(n,e,t,r,-1)||yg(n,e,t,r,1))},y1=/^(img|br|input|textarea|hr)$/i;function yg(n,e,t,r,s){for(var i;;){if(n==t&&e==r)return!0;if(e==(s<0?0:mt(n))){let o=n.parentNode;if(!o||o.nodeType!=1||ai(n)||y1.test(n.nodeName)||n.contentEditable=="false")return!1;e=Ie(n)+(s<0?0:1),n=o}else if(n.nodeType==1){let o=n.childNodes[e+(s<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((i=o.pmViewDesc)===null||i===void 0)&&i.ignoreForSelection)e+=s;else return!1;else n=o,e=s<0?mt(n):0}else return!1}}function mt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function w1(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=mt(n)}else if(n.parentNode&&!ai(n))e=Ie(n),n=n.parentNode;else return null}}function k1(n,e){for(;;){if(n.nodeType==3&&e2),pt=Gr||(Pt?/Mac/.test(Pt.platform):!1),Xg=Pt?/Win/.test(Pt.platform):!1,rn=/Android \d/.test(Mn),ci=!!wg&&"webkitFontSmoothing"in wg.documentElement.style,v1=ci?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function C1(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function tn(n,e){return typeof n=="number"?n:n[e]}function T1(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function kg(n,e,t){let r=n.someProp("scrollThreshold")||0,s=n.someProp("scrollMargin")||5,i=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(o.nodeType!=1){o=Yr(o);continue}let l=o,a=l==i.body,c=a?C1(i):T1(l),u=0,d=0;if(e.topc.bottom-tn(r,"bottom")&&(d=e.bottom-e.top>c.bottom-c.top?e.top+tn(s,"top")-c.top:e.bottom-c.bottom+tn(s,"bottom")),e.leftc.right-tn(r,"right")&&(u=e.right-c.right+tn(s,"right")),u||d)if(a)i.defaultView.scrollBy(u,d);else{let f=l.scrollLeft,p=l.scrollTop;d&&(l.scrollTop+=d),u&&(l.scrollLeft+=u);let m=l.scrollLeft-f,g=l.scrollTop-p;e={left:e.left-m,top:e.top-g,right:e.right-m,bottom:e.bottom-g}}let h=a?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(h))break;o=h=="absolute"?o.offsetParent:Yr(o)}}function A1(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,s;for(let i=(e.left+e.right)/2,o=t+1;o=t-20){r=l,s=a.top;break}}return{refDOM:r,refTop:s,stack:Qg(n.dom)}}function Qg(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=Yr(r));return e}function E1({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;Zg(t,r==0?0:r-e)}function Zg(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=u,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(i=d+1)}}return!t&&a&&(t=a,s=c,r=0),t&&t.nodeType==3?R1(t,s):!t||r&&t.nodeType==1?{node:n,offset:i}:ey(t,s)}function R1(n,e){let t=n.nodeValue.length,r=document.createRange(),s;for(let i=0;i=(o.left+o.right)/2?1:0)};break}}return r.detach(),s||{node:n,offset:0}}function fd(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function N1(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,s,i)}function D1(n,e,t,r){let s=-1;for(let i=e,o=!1;i!=n.dom;){let l=n.docView.nearestDesc(i,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?s=l.posBefore:(!o&&a.right-1?s:n.docView.posFromDOM(e,t,-1)}function ty(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&s++}let c;ci&&s&&r.nodeType==1&&(c=r.childNodes[s-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&s--,r==n.dom&&s==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(s==0||r.nodeType!=1||r.childNodes[s-1].nodeName!="BR")&&(l=D1(n,r,s,e))}l==null&&(l=I1(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function bg(n){return n.top=0&&s==r.nodeValue.length?(a--,u=1):t<0?a--:c++,ti(Cn(nn(r,a,c),u),u<0)}if(!n.state.doc.resolve(e-(i||0)).parent.inlineContent){if(i==null&&s&&(t<0||s==mt(r))){let a=r.childNodes[s-1];if(a.nodeType==1)return Hu(a.getBoundingClientRect(),!1)}if(i==null&&s=0)}if(i==null&&s&&(t<0||s==mt(r))){let a=r.childNodes[s-1],c=a.nodeType==3?nn(a,mt(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return ti(Cn(c,1),!1)}if(i==null&&s=0)}function ti(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Hu(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function ry(n,e,t){let r=n.state,s=n.root.activeElement;r!=e&&n.updateState(e),s!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),s!=n.dom&&s&&s.focus()}}function L1(n,e,t){let r=e.selection,s=t=="up"?r.$from:r.$to;return ry(n,e,()=>{let{node:i}=n.docView.domFromPos(s.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(i,!0);if(!l)break;if(l.node.isBlock){i=l.contentDOM||l.dom;break}i=l.dom.parentNode}let o=ny(n,s.pos,1);for(let l=i.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=nn(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cu.top+1&&(t=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}var _1=/[\u0590-\u08ac]/;function B1(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let s=r.parentOffset,i=!s,o=s==r.parent.content.size,l=n.domSelection();return l?!_1.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?i:o:ry(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:u,anchorOffset:d}=n.domSelectionRange(),h=l.caretBidiLevel;l.modify("move",t,"character");let f=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!f.contains(p.nodeType==1?p:p.parentNode)||a==p&&c==m;try{l.collapse(u,d),a&&(a!=u||c!=d)&&l.extend&&l.extend(a,c)}catch{}return h!=null&&(l.caretBidiLevel=h),g}):r.pos==r.start()||r.pos==r.end()}var xg=null,Sg=null,vg=!1;function z1(n,e,t){return xg==e&&Sg==t?vg:(xg=e,Sg=t,vg=t=="up"||t=="down"?L1(n,e,t):B1(n,e,t))}var yt=0,Cg=1,Xn=2,Lt=3,rr=class{constructor(e,t,r,s){this.parent=e,this.children=t,this.dom=r,this.contentDOM=s,this.dirty=yt,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tIe(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))s=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let i=e;;i=i.parentNode){if(i==this.dom){s=!1;break}if(i.previousSibling)break}if(s==null&&t==e.childNodes.length)for(let i=e;;i=i.parentNode){if(i==this.dom){s=!0;break}if(i.nextSibling)break}}return s??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,s=e;s;s=s.parentNode){let i=this.getDesc(s),o;if(i&&(!t||i.node))if(r&&(o=i.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return i}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let s=e;s;s=s.parentNode){let i=this.getDesc(s);if(i)return i.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te||o instanceof Qo){s=e-i;break}i=l}if(s)return this.children[r].domFromPos(s-this.children[r].border,t);for(let i;r&&!(i=this.children[r-1]).size&&i instanceof Go&&i.side>=0;r--);if(t<=0){let i,o=!0;for(;i=r?this.children[r-1]:null,!(!i||i.dom.parentNode==this.contentDOM);r--,o=!1);return i&&t&&o&&!i.border&&!i.domAtom?i.domFromPos(i.size,t):{node:this.contentDOM,offset:i?Ie(i.dom)+1:0}}else{let i,o=!0;for(;i=r=u&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,u);e=o;for(let d=l;d>0;d--){let h=this.children[d-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){s=Ie(h.dom)+1;break}e-=h.size}s==-1&&(s=0)}if(s>-1&&(c>t||l==this.children.length-1)){t=c;for(let u=l+1;up&&ot){let p=l;l=a,a=p}let f=document.createRange();f.setEnd(a.node,a.offset),f.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(f)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,s=0;s=r:er){let l=r+i.border,a=o-i.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?Xn:Cg,e==l&&t==a&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=Lt:i.markDirty(e-l,t-l);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?Xn:Lt}r=o}this.dirty=Xn}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?Xn:Cg;t.dirty{if(!i)return s;if(i.parent)return i.parent.posBeforeChild(i)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,i=this}matchesWidget(e){return this.dirty==yt&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},Qu=class extends rr{constructor(e,t,r,s){super(e,[],t,null),this.textDOM=r,this.text=s}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}},Xr=class n extends rr{constructor(e,t,r,s,i){super(e,[],r,s),this.mark=t,this.spec=i}static create(e,t,r,s){let i=s.nodeViews[t.type.name],o=i&&i(t,s,r);return(!o||!o.dom)&&(o=Xt.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new n(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Lt||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Lt&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=yt){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=nd(i,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,s),u=c&&c.dom,d=c&&c.contentDOM;if(t.isText){if(!u)u=document.createTextNode(t.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:d}=Xt.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!d&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let h=u;return u=oy(u,r,t),c?a=new Zu(e,t,r,s,u,d||null,h,c,i,o+1):t.isText?new Xo(e,t,r,s,u,h,i):new n(e,t,r,s,u,d||null,h,i,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let r=this.children[t];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>k.empty)}return e}matchesNode(e,t,r){return this.dirty==yt&&e.eq(this.node)&&Zo(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,s=t,i=e.composing?this.localCompositionInfo(e,t):null,o=i&&i.pos>-1?i:null,l=i&&i.pos<0,a=new td(this,o&&o.node,e);V1(this.node,this.innerDeco,(c,u,d)=>{c.spec.marks?a.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!d&&a.syncToMarks(u==this.node.childCount?j.none:this.node.child(u).marks,r,e,u),a.placeWidget(c,e,s)},(c,u,d,h)=>{a.syncToMarks(c.marks,r,e,h);let f;a.findNodeMatch(c,u,d,h)||l&&e.state.selection.from>s&&e.state.selection.to-1&&a.updateNodeAt(c,u,d,f,e)||a.updateNextNode(c,u,d,e,h,s)||a.addNode(c,u,d,e,s),s+=c.nodeSize}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Xn)&&(o&&this.protectLocalComposition(e,o),sy(this.contentDOM,this.children,e),Gr&&H1(this.dom))}localCompositionInfo(e,t){let{from:r,to:s}=e.state.selection;if(!(e.state.selection instanceof A)||rt+this.node.content.size)return null;let i=e.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let o=i.nodeValue,l=W1(this.node.content,o,r-t,s-t);return l<0?null:{node:i,pos:l,text:o}}else return{node:i,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:s}){if(this.getDesc(t))return;let i=t;for(;i.parentNode!=this.contentDOM;i=i.parentNode){for(;i.previousSibling;)i.parentNode.removeChild(i.previousSibling);for(;i.nextSibling;)i.parentNode.removeChild(i.nextSibling);i.pmViewDesc&&(i.pmViewDesc=void 0)}let o=new Qu(this,i,t,s);e.input.compositionNodes.push(o),this.children=nd(this.children,r,r+s.length,e,o)}update(e,t,r,s){return this.dirty==Lt||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,s),!0)}updateInner(e,t,r,s){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(s,this.posAtStart),this.dirty=yt}updateOuterDeco(e){if(Zo(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=iy(this.dom,this.nodeDOM,ed(this.outerDeco,this.node,t),ed(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function Tg(n,e,t,r,s){oy(r,e,n);let i=new En(void 0,n,e,t,r,r,r,s,0);return i.contentDOM&&i.updateChildren(s,0),i}var Xo=class n extends En{constructor(e,t,r,s,i,o,l){super(e,t,r,s,i,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,s){return this.dirty==Lt||this.dirty!=yt&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=yt||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,s.trackWrites==this.nodeDOM&&(s.trackWrites=null)),this.node=e,this.dirty=yt,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let s=this.node.cut(e,t),i=document.createTextNode(s.text);return new n(this.parent,s,this.outerDeco,this.innerDeco,i,i,r)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=Lt)}get domAtom(){return!1}isText(e){return this.node.text==e}},Qo=class extends rr{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==yt&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}},Zu=class extends En{constructor(e,t,r,s,i,o,l,a,c,u){super(e,t,r,s,i,o,l,c,u),this.spec=a}update(e,t,r,s){if(this.dirty==Lt)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let i=this.spec.update(e,t,r);return i&&this.updateInner(e,t,r,s),i}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,s)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,s){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,s)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}};function sy(n,e,t){let r=n.firstChild,s=!1;for(let i=0;i>1,l=Math.min(o,e.length);for(;i-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let u=Xr.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,s){let i=-1,o;if(s>=this.preMatch.index&&(o=this.preMatch.matches[s-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))i=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Xr)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(s-1))break;--s,i.set(l,s),o.push(l)}}return{index:s,matched:i,matches:o.reverse()}}function F1(n,e){return n.type.side-e.type.side}function V1(n,e,t,r){let s=e.locals(n),i=0;if(s.length==0){for(let c=0;ci;)l.push(s[o++]);let p=i+h.nodeSize;if(h.isText){let g=p;o!g.inline):l.slice();r(h,m,e.forChild(i,h),f),i=p}}function H1(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function W1(n,e,t,r){for(let s=0,i=0;s=t){if(i>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function nd(n,e,t,r,s){let i=[];for(let o=0,l=0;o=t||u<=e?i.push(a):(ct&&i.push(a.slice(t-c,a.size,r)))}return i}function pd(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let s=n.docView.nearestDesc(t.focusNode),i=s&&s.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(ll(t)){for(a=o;s&&!s.node;)s=s.parent;let d=s.node;if(s&&d.isAtom&&M.isSelectable(d)&&s.parent&&!(d.isInline&&b1(t.focusNode,t.focusOffset,s.dom))){let h=s.posBefore;c=new M(o==h?l:r.resolve(h))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let d=o,h=o;for(let f=0;f{(t.anchorNode!=r||t.anchorOffset!=s)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!ly(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function q1(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,Ie(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&Ze&&An<=11&&(t.disabled=!0,t.disabled=!1)}function ay(n,e){if(e instanceof M){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Ng(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Ng(n)}function Ng(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function md(n,e,t,r){return n.someProp("createSelectionBetween",s=>s(n,e,t))||A.between(e,t,r)}function Ig(n){return n.editable&&!n.hasFocus()?!1:cy(n)}function cy(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function J1(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return nr(e.node,e.offset,t.anchorNode,t.anchorOffset)}function rd(n,e){let{$anchor:t,$head:r}=n.selection,s=e>0?t.max(r):t.min(r),i=s.parent.inlineContent?s.depth?n.doc.resolve(e>0?s.after():s.before()):null:s;return i&&N.findFrom(i,e)}function Tn(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function Dg(n,e,t){let r=n.state.selection;if(r instanceof A)if(t.indexOf("s")>-1){let{$head:s}=r,i=s.textOffset?null:e<0?s.nodeBefore:s.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let o=n.state.doc.resolve(s.pos+i.nodeSize*(e<0?-1:1));return Tn(n,new A(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let s=rd(n.state,e);return s&&s instanceof M?Tn(n,s):!1}else if(!(pt&&t.indexOf("m")>-1)){let s=r.$head,i=s.textOffset?null:e<0?s.nodeBefore:s.nodeAfter,o;if(!i||i.isText)return!1;let l=e<0?s.pos-i.nodeSize:s.pos;return i.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?M.isSelectable(i)?Tn(n,new M(e<0?n.state.doc.resolve(s.pos-i.nodeSize):s)):ci?Tn(n,new A(n.state.doc.resolve(e<0?l:l+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof M&&r.node.isInline)return Tn(n,new A(e>0?r.$to:r.$from));{let s=rd(n.state,e);return s?Tn(n,s):!1}}}function el(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function ri(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function Jr(n,e){return e<0?K1(n):Y1(n)}function K1(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let s,i,o=!1;for(gt&&t.nodeType==1&&r0){if(t.nodeType!=1)break;{let l=t.childNodes[r-1];if(ri(l,-1))s=t,i=--r;else if(l.nodeType==3)t=l,r=t.nodeValue.length;else break}}else{if(uy(t))break;{let l=t.previousSibling;for(;l&&ri(l,-1);)s=t.parentNode,i=Ie(l),l=l.previousSibling;if(l)t=l,r=el(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?sd(n,t,r):s&&sd(n,s,i)}function Y1(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let s=el(t),i,o;for(;;)if(r{n.state==s&&on(n)},50)}function Og(n,e){let t=n.state.doc.resolve(e);if(!(Ce||Xg)&&t.parent.inlineContent){let s=n.coordsAtPos(e);if(e>t.start()){let i=n.coordsAtPos(e-1),o=(i.top+i.bottom)/2;if(o>s.top&&o1)return i.lefts.top&&o1)return i.left>s.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function Pg(n,e,t){let r=n.state.selection;if(r instanceof A&&!r.empty||t.indexOf("s")>-1||pt&&t.indexOf("m")>-1)return!1;let{$from:s,$to:i}=r;if(!s.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=rd(n.state,e);if(o&&o instanceof M)return Tn(n,o)}if(!s.parent.inlineContent){let o=e<0?s:i,l=r instanceof Ne?N.near(o,e):N.findFrom(o,e);return l?Tn(n,l):!1}return!1}function Lg(n,e){if(!(n.state.selection instanceof A))return!0;let{$head:t,$anchor:r,empty:s}=n.state.selection;if(!t.sameParent(r))return!0;if(!s)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let i=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(i&&!i.isText){let o=n.state.tr;return e<0?o.delete(t.pos-i.nodeSize,t.pos):o.delete(t.pos,t.pos+i.nodeSize),n.dispatch(o),!0}return!1}function _g(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function Q1(n){if(!_e||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;_g(n,r,"true"),setTimeout(()=>_g(n,r,"false"),20)}return!1}function Z1(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function eC(n,e){let t=e.keyCode,r=Z1(e);if(t==8||pt&&t==72&&r=="c")return Lg(n,-1)||Jr(n,-1);if(t==46&&!e.shiftKey||pt&&t==68&&r=="c")return Lg(n,1)||Jr(n,1);if(t==13||t==27)return!0;if(t==37||pt&&t==66&&r=="c"){let s=t==37?Og(n,n.state.selection.from)=="ltr"?-1:1:-1;return Dg(n,s,r)||Jr(n,s)}else if(t==39||pt&&t==70&&r=="c"){let s=t==39?Og(n,n.state.selection.from)=="ltr"?1:-1:1;return Dg(n,s,r)||Jr(n,s)}else{if(t==38||pt&&t==80&&r=="c")return Pg(n,-1,r)||Jr(n,-1);if(t==40||pt&&t==78&&r=="c")return Q1(n)||Pg(n,1,r)||Jr(n,1);if(r==(pt?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function gd(n,e){n.someProp("transformCopied",f=>{e=f(e,n)});let t=[],{content:r,openStart:s,openEnd:i}=e;for(;s>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){s--,i--;let f=r.firstChild;t.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let o=n.someProp("clipboardSerializer")||Xt.fromSchema(n.state.schema),l=gy(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,u,d=0;for(;c&&c.nodeType==1&&(u=my[c.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let p=l.createElement(u[f]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),d++}c=a.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${s} ${i}${d?` -${d}`:""} ${JSON.stringify(t)}`);let h=n.someProp("clipboardTextSerializer",f=>f(e,n))||e.content.textBetween(0,e.content.size,` -`);return{dom:a,text:h,slice:e}}function ay(n,e,t,r,s){let i=s.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||i||!t);if(a){if(n.someProp("transformPastedText",h=>{e=h(e,i||r,n)}),i)return l=new S(k.from(n.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),n.someProp("transformPasted",h=>{l=h(l,n,!0)}),l;let d=n.someProp("clipboardTextParser",h=>h(e,s,r,n));if(d)l=d;else{let h=s.marks(),{schema:f}=n.state,p=Xt.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(f.text(m,h)))})}}else n.someProp("transformPastedHTML",d=>{t=d(t,n)}),o=eC(t),ci&&tC(o);let c=o&&o.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let d=+u[3];d>0;d--){let h=o.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;o=h}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||Ot.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||u),context:s,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!Xv.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)l=nC(Og(l,+u[1],+u[2]),u[4]);else if(l=S.maxOpen(Qv(l.content,s),!0),l.openStart||l.openEnd){let d=0,h=0;for(let f=l.content.firstChild;d{l=d(l,n,a)}),l}var Xv=/^(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 Qv(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let s=e.node(t).contentMatchAt(e.index(t)),i,o=[];if(n.forEach(l=>{if(!o)return;let a=s.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&i.length&&uy(a,i,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=dy(o[o.length-1],i.length));let u=cy(l,a);o.push(u),s=s.matchType(u.type),i=a}}),o)return k.from(o)}return n}function cy(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,k.from(n));return n}function uy(n,e,t,r,s){if(s1&&(i=0),s=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,i<=s).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(k.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Og(n,e,t){return et})),Wu.createHTML(n)):n}function eC(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=fy().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(n),s;if((s=r&&hy[r[1].toLowerCase()])&&(n=s.map(i=>"<"+i+">").join("")+n+s.map(i=>"").reverse().join("")),t.innerHTML=Zv(n),s)for(let i=0;i=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;s=k.from(a.create(r[l+1],s)),i++,o++}return new S(s,i,o)}var qe={},Je={},rC={touchstart:!0,touchmove:!0},id=class{constructor(){this.shiftKey=!1,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=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function sC(n){for(let e in qe){let t=qe[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{oC(n,r)&&!md(n,r)&&(n.editable||!(r.type in Je))&&t(n,r)},rC[e]?{passive:!0}:void 0)}_e&&n.dom.addEventListener("input",()=>null),od(n)}function Tn(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function iC(n){n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function od(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>md(n,r))})}function md(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function oC(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function lC(n,e){!md(n,e)&&qe[e.type]&&(n.editable||!(e.type in Je))&&qe[e.type](n,e)}Je.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!my(n,t)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(rn&&Ie&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),Gr&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",s=>s(n,Gn(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||Gv(n,t)?t.preventDefault():Tn(n,"key")};Je.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};Je.keypress=(n,e)=>{let t=e;if(my(n,t)||!t.charCode||t.ctrlKey&&!t.altKey||pt&&t.metaKey)return;if(n.someProp("handleKeyPress",s=>s(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof E)||!r.$from.sameParent(r.$to)){let s=String.fromCharCode(t.charCode),i=()=>n.state.tr.insertText(s).scrollIntoView();!/[\r\n]/.test(s)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,s,i))&&n.dispatch(i()),t.preventDefault()}};function ol(n){return{left:n.clientX,top:n.clientY}}function aC(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function gd(n,e,t,r,s){if(r==-1)return!1;let i=n.state.doc.resolve(r);for(let o=i.depth+1;o>0;o--)if(n.someProp(e,l=>o>i.depth?l(n,t,i.nodeAfter,i.before(o),s,!0):l(n,t,i.node(o),i.before(o),s,!1)))return!0;return!1}function Kr(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);t=="pointer"&&r.setMeta("pointer",!0),n.dispatch(r)}function cC(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&M.isSelectable(r)?(Kr(n,new M(t),"pointer"),!0):!1}function uC(n,e){if(e==-1)return!1;let t=n.state.selection,r,s;t instanceof M&&(r=t.node);let i=n.state.doc.resolve(e);for(let o=i.depth+1;o>0;o--){let l=o>i.depth?i.nodeAfter:i.node(o);if(M.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&i.before(t.$from.depth+1)==t.$from.pos?s=i.before(t.$from.depth):s=i.before(o);break}}return s!=null?(Kr(n,M.create(n.state.doc,s),"pointer"),!0):!1}function dC(n,e,t,r,s){return gd(n,"handleClickOn",e,t,r)||n.someProp("handleClick",i=>i(n,e,r))||(s?uC(n,t):cC(n,t))}function hC(n,e,t,r){return gd(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",s=>s(n,e,r))}function fC(n,e,t,r){return gd(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",s=>s(n,e,r))||pC(n,t,r)}function pC(n,e,t){if(t.button!=0)return!1;let r=n.state.doc;if(e==-1)return r.inlineContent?(Kr(n,E.create(r,0,r.content.size),"pointer"),!0):!1;let s=r.resolve(e);for(let i=s.depth+1;i>0;i--){let o=i>s.depth?s.nodeAfter:s.node(i),l=s.before(i);if(o.inlineContent)Kr(n,E.create(r,l+1,l+1+o.content.size),"pointer");else if(M.isSelectable(o))Kr(n,M.create(r,l),"pointer");else continue;return!0}}function yd(n){return el(n)}var py=pt?"metaKey":"ctrlKey";qe.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=yd(n),s=Date.now(),i="singleClick";s-n.input.lastClick.time<500&&aC(t,n.input.lastClick)&&!t[py]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?i="doubleClick":n.input.lastClick.type=="doubleClick"&&(i="tripleClick")),n.input.lastClick={time:s,x:t.clientX,y:t.clientY,type:i,button:t.button};let o=n.posAtCoords(ol(t));o&&(i=="singleClick"?(n.input.mouseDown&&n.input.mouseDown.done(),n.input.mouseDown=new ld(n,o,t,!!r)):(i=="doubleClick"?hC:fC)(n,o.pos,o.inside,t)?t.preventDefault():Tn(n,"pointer"))};var ld=class{constructor(e,t,r,s){this.view=e,this.pos=t,this.event=r,this.flushed=s,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[py],this.allowDefault=r.shiftKey;let i,o;if(t.inside>-1)i=e.state.doc.nodeAt(t.inside),o=t.inside;else{let u=e.state.doc.resolve(t.pos);i=u.parent,o=u.depth?u.before():0}let l=s?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||c instanceof M&&c.from<=o&&c.to>o)&&(this.mightDrag={node:i,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&>&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),Tn(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>sn(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(ol(e))),this.updateAllowDefault(e),this.allowDefault||!t?Tn(this.view,"pointer"):dC(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||_e&&this.mightDrag&&!this.mightDrag.node.isAtom||Ie&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(Kr(this.view,I.near(this.view.state.doc.resolve(t.pos)),"pointer"),e.preventDefault()):Tn(this.view,"pointer")}move(e){this.updateAllowDefault(e),Tn(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}};qe.touchstart=n=>{n.input.lastTouch=Date.now(),yd(n),Tn(n,"pointer")};qe.touchmove=n=>{n.input.lastTouch=Date.now(),Tn(n,"pointer")};qe.contextmenu=n=>yd(n);function my(n,e){return n.composing?!0:_e&&Math.abs(e.timeStamp-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}var mC=rn?5e3:-1;Je.compositionstart=Je.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof E&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Ie&&Kg&&gC(n)))n.markCursor=n.state.storedMarks||t.marks(),el(n,!0),n.markCursor=null;else if(el(n,!e.selection.empty),gt&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let s=r.focusNode,i=r.focusOffset;s&&s.nodeType==1&&i!=0;){let o=i<0?s.lastChild:s.childNodes[i-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else s=o,i=-1}}n.input.composing=!0}gy(n,mC)};function gC(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}Je.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=e.timeStamp,n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,gy(n,20))};function gy(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>el(n),e))}function yy(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=wC());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function yC(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=pv(e.focusNode,e.focusOffset),r=mv(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let s=r.pmViewDesc,i=n.domObserver.lastChangedTextNode;if(t==i||r==i)return i;if(!s||!s.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function wC(){let n=document.createEvent("Event");return n.initEvent("event",!0,!0),n.timeStamp}function el(n,e=!1){if(!(rn&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),yy(n),e||n.docView&&n.docView.dirty){let t=hd(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function kC(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),s=document.createRange();s.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(s),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}var si=Ze&&An<15||Gr&&kv<604;qe.copy=Je.cut=(n,e)=>{let t=e,r=n.state.selection,s=t.type=="cut";if(r.empty)return;let i=si?null:t.clipboardData,o=r.content(),{dom:l,text:a}=pd(n,o);i?(t.preventDefault(),i.clearData(),i.setData("text/html",l.innerHTML),i.setData("text/plain",a)):kC(n,l),s&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function bC(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function xC(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let s=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?ii(n,r.value,null,s,e):ii(n,r.textContent,r.innerHTML,s,e)},50)}function ii(n,e,t,r,s){let i=ay(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,s,i||S.empty)))return!0;if(!i)return!1;let o=bC(i),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(i);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function wy(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}Je.paste=(n,e)=>{let t=e;if(n.composing&&!rn)return;let r=si?null:t.clipboardData,s=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&ii(n,wy(r),r.getData("text/html"),s,t)?t.preventDefault():xC(n,t)};var tl=class{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}},SC=pt?"altKey":"ctrlKey";function ky(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[SC]}qe.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let s=n.state.selection,i=s.empty?null:n.posAtCoords(ol(t)),o;if(!(i&&i.pos>=s.from&&i.pos<=(s instanceof M?s.to-1:s.to))){if(r&&r.mightDrag)o=M.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let d=n.docView.nearestDesc(t.target,!0);d&&d.node.type.spec.draggable&&d!=n.docView&&(o=M.create(n.state.doc,d.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:u}=pd(n,l);(!t.dataTransfer.files.length||!Ie||Jg>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(si?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",si||t.dataTransfer.setData("text/plain",c),n.dragging=new tl(u,ky(n,t),o)};qe.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};Je.dragover=Je.dragenter=(n,e)=>e.preventDefault();Je.drop=(n,e)=>{try{vC(n,e,n.dragging)}finally{n.dragging=null}};function vC(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(ol(e));if(!r)return;let s=n.state.doc.resolve(r.pos),i=t&&t.slice;i?n.someProp("transformPasted",f=>{i=f(i,n,!1)}):i=ay(n,wy(e.dataTransfer),si?null:e.dataTransfer.getData("text/html"),!1,s);let o=!!(t&&ky(n,e));if(n.someProp("handleDrop",f=>f(n,e,i||S.empty,o))){e.preventDefault();return}if(!i)return;e.preventDefault();let l=i?jo(n.state.doc,s.pos,i):s.pos;l==null&&(l=s.pos);let a=n.state.tr;if(o){let{node:f}=t;f?f.replace(a):a.deleteSelection()}let c=a.mapping.map(l),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,d=a.doc;if(u?a.replaceRangeWith(c,c,i.content.firstChild):a.replaceRange(c,c,i),a.doc.eq(d))return;let h=a.doc.resolve(c);if(u&&M.isSelectable(i.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(i.content.firstChild))a.setSelection(new M(h));else{let f=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>f=y),a.setSelection(fd(n,h,a.doc.resolve(f)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}qe.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&sn(n)},20))};qe.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)};qe.beforeinput=(n,e)=>{if(Ie&&rn&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",i=>i(n,Gn(8,"Backspace")))))return;let{$cursor:s}=n.state.selection;s&&s.pos>0&&n.dispatch(n.state.tr.delete(s.pos-1,s.pos).scrollIntoView())},50)}};for(let n in Je)qe[n]=Je[n];function oi(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}var nl=class n{constructor(e,t){this.toDOM=e,this.spec=t||er,this.side=this.spec.side||0}map(e,t,r,s){let{pos:i,deleted:o}=e.mapResult(t.from+s,this.side<0?-1:1);return o?null:new de(i-r,i-r,this)}valid(){return!0}eq(e){return this==e||e instanceof n&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&oi(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Zn=class n{constructor(e,t){this.attrs=e,this.spec=t||er}map(e,t,r,s){let i=e.map(t.from+s,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+s,this.spec.inclusiveEnd?1:-1)-r;return i>=o?null:new de(i,o,this)}valid(e,t){return t.from=e&&(!i||i(l.spec))&&r.push(l.copy(l.from+s,l.to+s))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,s+l,i)}}map(e,t,r){return this==Le||e.maps.length==0?this:this.mapInner(e,t,0,0,r||er)}mapInner(e,t,r,s,i){let o;for(let l=0;l{let c=a+r,u;if(u=xy(t,l,c)){for(s||(s=this.children.slice());il&&d.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let i=e+1,o=i+t.content.size;for(let l=0;li&&a.type instanceof Zn){let c=Math.max(i,a.from)-i,u=Math.min(o,a.to)-i;cs.map(e,t,er));return n.from(r)}forChild(e,t){if(t.isLeaf)return X.empty;let r=[];for(let s=0;st instanceof X)?e:e.reduce((t,r)=>t.concat(r instanceof X?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(f-h);for(let y=0;yw+u-d)continue;let b=l[y]+u-d;f>=b?l[y+1]=h<=b?-2:-1:h>=u&&g&&(l[y]+=g,l[y+1]+=g)}d+=g}),u=t.maps[c].map(u,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let h=t.map(n[c+1]+i,-1),f=h-s,{index:p,offset:m}=r.content.findIndex(d),g=r.maybeChild(p);if(g&&m==d&&m+g.nodeSize==f){let y=l[c+2].mapInner(t,g,u+1,n[c]+i+1,o);y!=Le?(l[c]=d,l[c+1]=f,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=TC(l,n,e,t,s,i,o),u=sl(c,r,0,o);e=u.local;for(let d=0;dt&&o.to{let c=xy(n,l,a+t);if(c){i=!0;let u=sl(c,l,t+a+1,r);u!=Le&&s.push(a,a+l.nodeSize,u)}});let o=by(i?Sy(n):n,-t).sort(tr);for(let l=0;l0;)e++;n.splice(e,0,t)}function ju(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=Le&&e.push(r)}),n.cursorWrapper&&e.push(X.create(n.state.doc,[n.cursorWrapper.deco])),rl.from(e)}var AC={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},EC=Ze&&An<=11,cd=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},ud=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new cd,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let s=0;ss.type=="childList"&&s.removedNodes.length||s.type=="characterData"&&s.oldValue.length>s.target.nodeValue.length)?this.flushSoon():_e&&e.composing&&r.some(s=>s.type=="childList"&&s.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),EC&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,AC)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}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=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Eg(this.view)){if(this.suppressingSelectionUpdates)return sn(this.view);if(Ze&&An<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&nr(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let i=e.focusNode;i;i=Yr(i))t.add(i);for(let i=e.anchorNode;i;i=Yr(i))if(t.has(i)){r=i;break}let s=r&&this.view.docView.nearestDesc(r);if(s&&s.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),s=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Eg(e)&&!this.ignoreSelectionChange(r),i=-1,o=-1,l=!1,a=[];if(e.editable)for(let u=0;uu.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of a)if(u.nodeName=="BR"&&u.parentNode){let d=u.nextSibling;for(;d&&d.nodeType==1;){if(d.contentEditable=="false"){u.parentNode.removeChild(u);break}d=d.firstChild}}}else if(gt&&a.length){let u=a.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,h]=u;d.parentNode&&d.parentNode.parentNode==h.parentNode?h.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let h of u){let f=h.parentNode;f&&f.nodeName=="LI"&&(!d||NC(e,d)!=f)&&h.remove()}}}let c=null;i<0&&s&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||s)&&(i>-1&&(e.docView.markDirty(i,o),MC(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,IC(e,a)),this.handleDOMChange(i,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||sn(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;us;g--){let y=r.childNodes[g-1],w=y.pmViewDesc;if(y.nodeName=="BR"&&!w){i=g;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||Ot.fromSchema(n.state.schema),f=d.resolve(o),p=null,m=h.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:s,to:i,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:OC,context:f});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),p={anchor:g+o,head:y+o}}return{doc:m,sel:p,from:o,to:l}}function OC(n){let e=n.pmViewDesc;if(e)return e.parseRule();if(n.nodeName=="BR"&&n.parentNode){if(_e&&/^(ul|ol)$/i.test(n.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}else if(n.parentNode.lastChild==n||_e&&/^(tr|table)$/i.test(n.parentNode.nodeName))return{ignore:!0}}else if(n.nodeName=="IMG"&&n.getAttribute("mark-placeholder"))return{ignore:!0};return null}var PC=/^(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 LC(n,e,t,r,s){let i=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let A=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,_=hd(n,A);if(_&&!n.state.selection.eq(_)){if(Ie&&rn&&n.input.lastKeyCode===13&&Date.now()-100ae(n,Gn(13,"Enter"))))return;let U=n.state.tr.setSelection(_);A=="pointer"?U.setMeta("pointer",!0):A=="key"&&U.scrollIntoView(),i&&U.setMeta("composition",i),n.dispatch(U)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=DC(n,e,t),u=n.state.doc,d=u.slice(c.from,c.to),h,f;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||rn)&&s.some(A=>A.nodeType==1&&!PC.test(A.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",A=>A(n,Gn(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof E&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let A=$g(n,n.state.doc,c.sel);if(A&&!A.eq(n.state.selection)){let _=n.state.tr.setSelection(A);i&&_.setMeta("composition",i),n.dispatch(_)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),Ze&&An<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)==" \xA0"&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=u.resolve(p.start),w=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((Gr&&n.input.lastIOSEnter>Date.now()-225&&(!w||s.some(A=>A.nodeName=="DIV"||A.nodeName=="P"))||!w&&m.posA(n,Gn(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&BC(u,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",A=>A(n,Gn(8,"Backspace")))){rn&&Ie&&n.domObserver.suppressSelectionUpdates();return}Ie&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),rn&&!w&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(A){return A(n,Gn(13,"Enter"))})},20));let b=p.start,v=p.endA,C=A=>{let _=A||n.state.tr.replace(b,v,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let U=$g(n,_.doc,c.sel);U&&!(Ie&&n.composing&&U.empty&&(p.start!=p.endB||n.input.lastChromeDeletesn(n),20));let A=C(n.state.tr.delete(b,v)),_=u.resolve(p.start).marksAcross(u.resolve(p.endA));_&&A.ensureMarks(_),n.dispatch(A)}else if(p.endA==p.endB&&(R=_C(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let A=C(n.state.tr);R.type=="add"?A.addMark(b,v,R.mark):A.removeMark(b,v,R.mark),n.dispatch(A)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let A=m.parent.textBetween(m.parentOffset,g.parentOffset),_=()=>C(n.state.tr.insertText(A,b,v));n.someProp("handleTextInput",U=>U(n,b,v,A,_))||n.dispatch(_())}else n.dispatch(C());else n.dispatch(C())}function $g(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:fd(n,e.resolve(t.anchor),e.resolve(t.head))}function _C(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,s=t,i=r,o,l,a;for(let u=0;uu.mark(l.addToSet(u.marks));else if(s.length==0&&i.length==1)l=i[0],o="remove",a=u=>u.mark(l.removeFromSet(u.marks));else return null;let c=[];for(let u=0;ut||qu(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,s++,e=!1;if(t){let i=n.node(r).maybeChild(n.indexAfter(r));for(;i&&!i.isLeaf;)i=i.firstChild,s++}return s}function zC(n,e,t,r,s){let i=n.findDiffStart(e,t);if(i==null)return null;let{a:o,b:l}=n.findDiffEnd(e,t+n.size,t+e.size);if(s=="end"){let a=Math.max(0,i-Math.min(o,l));r-=o+a-i}if(o=o?i-r:0;i-=a,i&&i=l?i-r:0;i-=a,i&&i=56320&&e<=57343&&t>=55296&&t<=56319}var li=class{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new id,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(jg),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Hg(this),Vg(this),this.nodeViews=Wg(this),this.docView=xg(this.state.doc,Fg(this),ju(this),this.dom,this),this.domObserver=new ud(this,(r,s,i,o)=>LC(this,r,s,i,o)),this.domObserver.start(),sC(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&od(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(jg),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let s=this.state,i=!1,o=!1;e.storedMarks&&this.composing&&(yy(this),o=!0),this.state=e;let l=s.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let f=Wg(this);UC(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&od(this),this.editable=Hg(this),Vg(this);let a=ju(this),c=Fg(this),u=s.plugins!=e.plugins&&!s.doc.eq(e.doc)?"reset":e.scrollToSelection>s.scrollToSelection?"to selection":"preserve",d=i||!this.docView.matchesNode(e.doc,c,a);(d||!e.selection.eq(s.selection))&&(o=!0);let h=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Sv(this);if(o){this.domObserver.stop();let f=d&&(Ze||Ie)&&!this.composing&&!s.selection.empty&&!e.selection.empty&&$C(s.selection,e.selection);if(d){let p=Ie?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=yC(this)),(i||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=xg(e.doc,c,a,this.dom,this)),p&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&Hv(this))?sn(this,f):(iy(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(s),!((r=this.dragging)===null||r===void 0)&&r.node&&!s.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,s),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():h&&vv(h)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof M){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&mg(this,t.getBoundingClientRect(),e)}else mg(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&it.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Rv(this,e)}coordsAtPos(e,t=1){return Zg(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let s=this.docView.posFromDOM(e,t,r);if(s==null)throw new RangeError("DOM position not inside the editor");return s}endOfTextblock(e,t){return Pv(this,t||this.state,e)}pasteHTML(e,t){return ii(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return ii(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return pd(this,e)}destroy(){this.docView&&(iC(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ju(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,hv())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return lC(this,e)}domSelectionRange(){let e=this.domSelection();return e?_e&&this.root.nodeType===11&&yv(this.dom.ownerDocument)==this.dom&&RC(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};li.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function Fg(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[de.node(0,n.state.doc.content.size,e)]}function Vg(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:de.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function Hg(n){return!n.someProp("editable",e=>e(n.state)===!1)}function $C(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function Wg(n){let e=Object.create(null);function t(r){for(let s in r)Object.prototype.hasOwnProperty.call(e,s)||(e[s]=r[s])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function UC(n,e){let t=0,r=0;for(let s in n){if(n[s]!=e[s])return!0;t++}for(let s in e)r++;return t!=r}function jg(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var on={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:"'"},al={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},FC=typeof navigator<"u"&&/Mac/.test(navigator.platform),VC=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(he=0;he<10;he++)on[48+he]=on[96+he]=String(he);var he;for(he=1;he<=24;he++)on[he+111]="F"+he;var he;for(he=65;he<=90;he++)on[he]=String.fromCharCode(he+32),al[he]=String.fromCharCode(he);var he;for(ll in on)al.hasOwnProperty(ll)||(al[ll]=on[ll]);var ll;function vy(n){var e=FC&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||VC&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?al:on)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var HC=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),WC=typeof navigator<"u"&&/Win/.test(navigator.platform);function jC(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,s,i,o;for(let l=0;l{for(var t in e)JC(n,t,{get:e[t],enumerable:!0})};function gl(n){let{state:e,transaction:t}=n,{selection:r}=t,{doc:s}=t,{storedMarks:i}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return i},get selection(){return r},get doc(){return s},get tr(){return r=t.selection,s=t.doc,i=t.storedMarks,t}}}var yl=class{constructor(n){this.editor=n.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=n.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){let{rawCommands:n,editor:e,state:t}=this,{view:r}=e,{tr:s}=t,i=this.buildProps(s);return Object.fromEntries(Object.entries(n).map(([o,l])=>[o,(...c)=>{let u=l(...c)(i);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(n,e=!0){let{rawCommands:t,editor:r,state:s}=this,{view:i}=r,o=[],l=!!n,a=n||s.tr,c=()=>(!l&&e&&!a.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(a),o.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(t).map(([d,h])=>[d,(...p)=>{let m=this.buildProps(a,e),g=h(...p)(m);return o.push(g),u}])),run:c};return u}createCan(n){let{rawCommands:e,state:t}=this,r=!1,s=n||t.tr,i=this.buildProps(s,r);return{...Object.fromEntries(Object.entries(e).map(([l,a])=>[l,(...c)=>a(...c)({...i,dispatch:void 0})])),chain:()=>this.createChain(s,r)}}buildProps(n,e=!0){let{rawCommands:t,editor:r,state:s}=this,{view:i}=r,o={tr:n,editor:r,view:i,state:gl({state:s,transaction:n}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(n,e),can:()=>this.createCan(n),get commands(){return Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)(o)]))}};return o}},Ly={};Td(Ly,{blur:()=>KC,clearContent:()=>YC,clearNodes:()=>GC,command:()=>XC,createParagraphNear:()=>QC,cut:()=>ZC,deleteCurrentNode:()=>eT,deleteNode:()=>tT,deleteRange:()=>nT,deleteSelection:()=>iT,enter:()=>oT,exitCode:()=>lT,extendMarkRange:()=>aT,first:()=>cT,focus:()=>dT,forEach:()=>hT,insertContent:()=>fT,insertContentAt:()=>gT,joinBackward:()=>kT,joinDown:()=>wT,joinForward:()=>bT,joinItemBackward:()=>xT,joinItemForward:()=>ST,joinTextblockBackward:()=>vT,joinTextblockForward:()=>CT,joinUp:()=>yT,keyboardShortcut:()=>AT,lift:()=>ET,liftEmptyBlock:()=>MT,liftListItem:()=>RT,newlineInCode:()=>NT,resetAttributes:()=>IT,scrollIntoView:()=>DT,selectAll:()=>OT,selectNodeBackward:()=>PT,selectNodeForward:()=>LT,selectParentNode:()=>_T,selectTextblockEnd:()=>BT,selectTextblockStart:()=>zT,setContent:()=>$T,setMark:()=>eA,setMeta:()=>tA,setNode:()=>nA,setNodeSelection:()=>rA,setTextDirection:()=>sA,setTextSelection:()=>iA,sinkListItem:()=>oA,splitBlock:()=>lA,splitListItem:()=>aA,toggleList:()=>uA,toggleMark:()=>dA,toggleNode:()=>hA,toggleWrap:()=>fA,undoInputRule:()=>pA,unsetAllMarks:()=>mA,unsetMark:()=>gA,unsetTextDirection:()=>yA,updateAttributes:()=>wA,wrapIn:()=>kA,wrapInList:()=>bA});var KC=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{var t;n.isDestroyed||(e.dom.blur(),(t=window?.getSelection())==null||t.removeAllRanges())}),!0),YC=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),GC=()=>({state:n,tr:e,dispatch:t})=>{let{selection:r}=e,{ranges:s}=r;return t&&s.forEach(({$from:i,$to:o})=>{n.doc.nodesBetween(i.pos,o.pos,(l,a)=>{if(l.type.isText)return;let{doc:c,mapping:u}=e,d=c.resolve(u.map(a)),h=c.resolve(u.map(a+l.nodeSize)),f=d.blockRange(h);if(!f)return;let p=en(f);if(l.type.isTextblock){let{defaultType:m}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(f.start,m)}(p||p===0)&&e.lift(f,p)})}),!0},XC=n=>e=>n(e),QC=()=>({state:n,dispatch:e})=>_u(n,e),ZC=(n,e)=>({editor:t,tr:r})=>{let{state:s}=t,i=s.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);let o=r.mapping.map(e);return r.insert(o,i.content),r.setSelection(new E(r.doc.resolve(Math.max(o-1,0)))),!0},eT=()=>({tr:n,dispatch:e})=>{let{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;let s=n.selection.$anchor;for(let i=s.depth;i>0;i-=1)if(s.node(i).type===r.type){if(e){let l=s.before(i),a=s.after(i);n.delete(l,a).scrollIntoView()}return!0}return!1};function te(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}var tT=n=>({tr:e,state:t,dispatch:r})=>{let s=te(n,t.schema),i=e.selection.$anchor;for(let o=i.depth;o>0;o-=1)if(i.node(o).type===s){if(r){let a=i.before(o),c=i.after(o);e.delete(a,c).scrollIntoView()}return!0}return!1},nT=n=>({tr:e,dispatch:t})=>{let{from:r,to:s}=n;return t&&e.delete(r,s),!0},rT=n=>n.content?/^text(\*|\+)/.test(n.content):!1,Ty=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos{let r=Ty(n,t,"left"),s=Ty(e,t,"right");return{from:r,to:s}},iT=()=>({state:n,dispatch:e})=>{let{$from:t,$to:r}=n.selection;if(n.selection.empty)return!1;let{from:s,to:i}=sT(t,r,n.schema);return e&&(n.tr.deleteRange(s,i).scrollIntoView(),e(n.tr)),!0},oT=()=>({commands:n})=>n.keyboardShortcut("Enter"),lT=()=>({state:n,dispatch:e})=>Lu(n,e);function Ad(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function pl(n,e,t={strict:!0}){let r=Object.keys(e);return r.length?r.every(s=>t.strict?e[s]===n[s]:Ad(e[s])?e[s].test(n[s]):e[s]===n[s]):!0}function _y(n,e,t={}){return n.find(r=>r.type===e&&pl(Object.fromEntries(Object.keys(t).map(s=>[s,r.attrs[s]])),t))}function Ay(n,e,t={}){return!!_y(n,e,t)}function Ed(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(c=>c.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(c=>c.type===e))return;if(!t){let c=r.node.marks.find(u=>u.type===e);c&&(t=c.attrs)}if(!_y([...r.node.marks],e,t))return;let i=r.index,o=n.start()+r.offset,l=i+1,a=o+r.node.nodeSize;for(;i>0&&Ay([...n.parent.child(i-1).marks],e,t);)i-=1,o-=n.parent.child(i).nodeSize;for(;l({tr:t,state:r,dispatch:s})=>{let i=ln(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:u}=l;if(s){let d=Ed(a,i,e);if(d&&d.from<=c&&d.to>=u){let h=E.create(o,d.from,d.to);t.setSelection(h)}}return!0},cT=n=>e=>{let t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:s,dispatch:i})=>{e={scrollIntoView:!0,...e};let o=()=>{(ml()||Ey())&&r.dom.focus(),uT()&&!ml()&&!Ey()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(i&&n===null&&!By(t.state.selection))return o(),!0;let l=zy(s.doc,n)||t.state.selection,a=t.state.selection.eq(l);return i&&(a||s.setSelection(l),a&&s.storedMarks&&s.setStoredMarks(s.storedMarks),o()),!0},hT=(n,e)=>t=>n.every((r,s)=>e(r,{...t,index:s})),fT=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),$y=n=>{let e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){let r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&$y(r)}return n};function cl(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");let e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return $y(t)}function pi(n,e,t){if(n instanceof Qe||n instanceof k)return n;t={slice:!0,parseOptions:{},...t};let r=typeof n=="object"&&n!==null,s=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return k.fromArray(n.map(l=>e.nodeFromJSON(l)));let o=e.nodeFromJSON(n);return t.errorOnInvalidContent&&o.check(),o}catch(i){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",i),pi("",e,t)}if(s){if(t.errorOnInvalidContent){let o=!1,l="",a=new zr({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?Ot.fromSchema(a).parseSlice(cl(n),t.parseOptions):Ot.fromSchema(a).parse(cl(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}let i=Ot.fromSchema(e);return t.slice?i.parseSlice(cl(n),t.parseOptions).content:i.parse(cl(n),t.parseOptions)}return pi("",e,t)}function pT(n,e,t){let r=n.steps.length-1;if(r{o===0&&(o=u)}),n.setSelection(I.near(n.doc.resolve(o),t))}var mT=n=>!("type"in n),gT=(n,e,t)=>({tr:r,dispatch:s,editor:i})=>{var o;if(s){t={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l,a=g=>{i.emit("contentError",{editor:i,error:g,disableCollaboration:()=>{"collaboration"in i.storage&&typeof i.storage.collaboration=="object"&&i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{pi(e,i.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{l=pi(e,i.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!=null?o:i.options.enableContentCheck})}catch(g){return a(g),!1}let{from:u,to:d}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},h=!0,f=!0;if((mT(l)?l:[l]).forEach(g=>{g.check(),h=h?g.isText&&g.marks.length===0:!1,f=f?g.isBlock:!1}),u===d&&f){let{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,d+=1)}let m;if(h){if(Array.isArray(e))m=e.map(g=>g.text||"").join("");else if(e instanceof k){let g="";e.forEach(y=>{y.text&&(g+=y.text)}),m=g}else typeof e=="object"&&e&&e.text?m=e.text:m=e;r.insertText(m,u,d)}else{m=l;let g=r.doc.resolve(u),y=g.node(),w=g.parentOffset===0,b=y.isText||y.isTextblock,v=y.content.size>0;w&&b&&v&&f&&(u=Math.max(0,u-1)),r.replaceWith(u,d,m)}t.updateSelection&&pT(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:m})}return!0},yT=()=>({state:n,dispatch:e})=>rg(n,e),wT=()=>({state:n,dispatch:e})=>sg(n,e),kT=()=>({state:n,dispatch:e})=>Eu(n,e),bT=()=>({state:n,dispatch:e})=>Nu(n,e),xT=()=>({state:n,dispatch:e,tr:t})=>{try{let r=Kn(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},ST=()=>({state:n,dispatch:e,tr:t})=>{try{let r=Kn(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},vT=()=>({state:n,dispatch:e})=>Zm(n,e),CT=()=>({state:n,dispatch:e})=>eg(n,e);function Uy(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function TT(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t==="Space"&&(t=" ");let r,s,i,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:s})=>{let i=TT(n).split(/-(?!$)/),o=i.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{let u=c.map(r.mapping);u&&s&&r.maybeStep(u)}),!0};function _t(n,e,t={}){let{from:r,to:s,empty:i}=n.selection,o=e?te(e,n.schema):null,l=[];n.doc.nodesBetween(r,s,(d,h)=>{if(d.isText)return;let f=Math.max(r,h),p=Math.min(s,h+d.nodeSize);l.push({node:d,from:f,to:p})});let a=s-r,c=l.filter(d=>o?o.name===d.node.type.name:!0).filter(d=>pl(d.node.attrs,t,{strict:!1}));return i?!!c.length:c.reduce((d,h)=>d+h.to-h.from,0)>=a}var ET=(n,e={})=>({state:t,dispatch:r})=>{let s=te(n,t.schema);return _t(t,s,e)?ig(t,r):!1},MT=()=>({state:n,dispatch:e})=>Bu(n,e),RT=n=>({state:e,dispatch:t})=>{let r=te(n,e.schema);return dg(r)(e,t)},NT=()=>({state:n,dispatch:e})=>Ou(n,e);function wl(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function My(n,e){let t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,s)=>(t.includes(s)||(r[s]=n[s]),r),{})}var IT=(n,e)=>({tr:t,state:r,dispatch:s})=>{let i=null,o=null,l=wl(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(i=te(n,r.schema)),l==="mark"&&(o=ln(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,d)=>{i&&i===u.type&&(a=!0,s&&t.setNodeMarkup(d,void 0,My(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(h=>{o===h.type&&(a=!0,s&&t.addMark(d,d+u.nodeSize,o.create(My(h.attrs,e))))})})}),a},DT=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),OT=()=>({tr:n,dispatch:e})=>{if(e){let t=new Re(n.doc);n.setSelection(t)}return!0},PT=()=>({state:n,dispatch:e})=>Mu(n,e),LT=()=>({state:n,dispatch:e})=>Iu(n,e),_T=()=>({state:n,dispatch:e})=>og(n,e),BT=()=>({state:n,dispatch:e})=>$u(n,e),zT=()=>({state:n,dispatch:e})=>zu(n,e);function vd(n,e,t={},r={}){return pi(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}var $T=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:s,tr:i,dispatch:o,commands:l})=>{let{doc:a}=i;if(r.preserveWhitespace!=="full"){let c=vd(n,s.schema,r,{errorOnInvalidContent:e??s.options.enableContentCheck});return o&&i.replaceWith(0,a.content.size,c).setMeta("preventUpdate",!t),!0}return o&&i.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??s.options.enableContentCheck})};function Fy(n,e){let t=ln(e,n.schema),{from:r,to:s,empty:i}=n.selection,o=[];i?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,s,a=>{o.push(...a.marks)});let l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function Md(n,e){let t=new xn(n);return e.forEach(r=>{r.steps.forEach(s=>{t.step(s)})}),t}function UT(n){for(let e=0;e{t(s)&&r.push({node:s,pos:i})}),r}function Rd(n,e){for(let t=n.depth;t>0;t-=1){let r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function kl(n){return e=>Rd(e.$from,n)}function N(n,e,t){return n.config[e]===void 0&&n.parent?N(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?N(n.parent,e,t):null}):n.config[e]}function Nd(n){return n.map(e=>{let t={name:e.name,options:e.options,storage:e.storage},r=N(e,"addExtensions",t);return r?[e,...Nd(r())]:e}).flat(10)}function Id(n,e){let t=Xt.fromSchema(e).serializeFragment(n),s=document.implementation.createHTMLDocument().createElement("div");return s.appendChild(t),s.innerHTML}function Hy(n){return typeof n=="function"}function W(n,e=void 0,...t){return Hy(n)?e?n.bind(e)(...t):n(...t):n}function FT(n={}){return Object.keys(n).length===0&&n.constructor===Object}function Qr(n){let e=n.filter(s=>s.type==="extension"),t=n.filter(s=>s.type==="node"),r=n.filter(s=>s.type==="mark");return{baseExtensions:e,nodeExtensions:t,markExtensions:r}}function Wy(n){let e=[],{nodeExtensions:t,markExtensions:r}=Qr(n),s=[...t,...r],i={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{let u={name:c.name,options:c.options,storage:c.storage,extensions:s},d=N(c,"addGlobalAttributes",u);if(!d)return;d().forEach(f=>{let p;Array.isArray(f.types)?p=f.types:f.types==="*"?p=a:f.types==="nodes"?p=o:f.types==="marks"?p=l:p=[],p.forEach(m=>{Object.entries(f.attributes).forEach(([g,y])=>{e.push({type:m,name:g,attribute:{...i,...y}})})})})}),s.forEach(c=>{let u={name:c.name,options:c.options,storage:c.storage},d=N(c,"addAttributes",u);if(!d)return;let h=d();Object.entries(h).forEach(([f,p])=>{let m={...i,...p};typeof m?.default=="function"&&(m.default=m.default()),m?.isRequired&&m?.default===void 0&&delete m.default,e.push({type:c.name,name:f,attribute:m})})}),e}function VT(n){let e=[],t="",r=!1,s=!1,i=0,o=n.length;for(let l=0;l0){i-=1,t+=a;continue}if(a===";"&&i===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Ry(n){let e=[],t=VT(n||""),r=t.length;for(let s=0;s!!e).reduce((e,t)=>{let r={...e};return Object.entries(t).forEach(([s,i])=>{if(!r[s]){r[s]=i;return}if(s==="class"){let l=i?String(i).split(" "):[],a=r[s]?r[s].split(" "):[],c=l.filter(u=>!a.includes(u));r[s]=[...a,...c].join(" ")}else if(s==="style"){let l=new Map([...Ry(r[s]),...Ry(i)]);r[s]=Array.from(l.entries()).map(([a,c])=>`${a}: ${c}`).join("; ")}else r[s]=i}),r},{})}function Zr(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>B(t,r),{})}function HT(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Ny(n,e){return"style"in n?n:{...n,getAttrs:t=>{let r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;let s=e.reduce((i,o)=>{let l=o.attribute.parseHTML?o.attribute.parseHTML(t):HT(t.getAttribute(o.name));return l==null?i:{...i,[o.name]:l}},{});return{...r,...s}}}}function Iy(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&FT(t)?!1:t!=null))}function Dy(n){var e,t;let r={};return!((e=n?.attribute)!=null&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),((t=n?.attribute)==null?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function WT(n,e){var t;let r=Wy(n),{nodeExtensions:s,markExtensions:i}=Qr(n),o=(t=s.find(c=>N(c,"topNode")))==null?void 0:t.name,l=Object.fromEntries(s.map(c=>{let u=r.filter(y=>y.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=n.reduce((y,w)=>{let b=N(w,"extendNodeSchema",d);return{...y,...b?b(c):{}}},{}),f=Iy({...h,content:W(N(c,"content",d)),marks:W(N(c,"marks",d)),group:W(N(c,"group",d)),inline:W(N(c,"inline",d)),atom:W(N(c,"atom",d)),selectable:W(N(c,"selectable",d)),draggable:W(N(c,"draggable",d)),code:W(N(c,"code",d)),whitespace:W(N(c,"whitespace",d)),linebreakReplacement:W(N(c,"linebreakReplacement",d)),defining:W(N(c,"defining",d)),isolating:W(N(c,"isolating",d)),attrs:Object.fromEntries(u.map(Dy))}),p=W(N(c,"parseHTML",d));p&&(f.parseDOM=p.map(y=>Ny(y,u)));let m=N(c,"renderHTML",d);m&&(f.toDOM=y=>m({node:y,HTMLAttributes:Zr(y,u)}));let g=N(c,"renderText",d);return g&&(f.toText=g),[c.name,f]})),a=Object.fromEntries(i.map(c=>{let u=r.filter(g=>g.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=n.reduce((g,y)=>{let w=N(y,"extendMarkSchema",d);return{...g,...w?w(c):{}}},{}),f=Iy({...h,inclusive:W(N(c,"inclusive",d)),excludes:W(N(c,"excludes",d)),group:W(N(c,"group",d)),spanning:W(N(c,"spanning",d)),code:W(N(c,"code",d)),attrs:Object.fromEntries(u.map(Dy))}),p=W(N(c,"parseHTML",d));p&&(f.parseDOM=p.map(g=>Ny(g,u)));let m=N(c,"renderHTML",d);return m&&(f.toDOM=g=>m({mark:g,HTMLAttributes:Zr(g,u)})),[c.name,f]}));return new zr({topNode:o,nodes:l,marks:a})}function jT(n){let e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function fi(n){return n.sort((t,r)=>{let s=N(t,"priority")||100,i=N(r,"priority")||100;return s>i?-1:sr.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function qy(n,e,t){let{from:r,to:s}=e,{blockSeparator:i=` +`);return{dom:a,text:h,slice:e}}function dy(n,e,t,r,s){let i=s.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||i||!t);if(a){if(n.someProp("transformPastedText",h=>{e=h(e,i||r,n)}),i)return l=new S(k.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",h=>{l=h(l,n,!0)}),l;let d=n.someProp("clipboardTextParser",h=>h(e,s,r,n));if(d)l=d;else{let h=s.marks(),{schema:f}=n.state,p=Xt.fromSchema(f);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(f.text(m,h)))})}}else n.someProp("transformPastedHTML",d=>{t=d(t,n)}),o=sC(t),ci&&iC(o);let c=o&&o.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let d=+u[3];d>0;d--){let h=o.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;o=h}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||Ot.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||u),context:s,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!tC.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)l=oC(Bg(l,+u[1],+u[2]),u[4]);else if(l=S.maxOpen(nC(l.content,s),!0),l.openStart||l.openEnd){let d=0,h=0;for(let f=l.content.firstChild;d{l=d(l,n,a)}),l}var tC=/^(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 nC(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let s=e.node(t).contentMatchAt(e.index(t)),i,o=[];if(n.forEach(l=>{if(!o)return;let a=s.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&i.length&&fy(a,i,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=py(o[o.length-1],i.length));let u=hy(l,a);o.push(u),s=s.matchType(u.type),i=a}}),o)return k.from(o)}return n}function hy(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,k.from(n));return n}function fy(n,e,t,r,s){if(s1&&(i=0),s=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,i<=s).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(k.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function Bg(n,e,t){return et})),ju.createHTML(n)):n}function sC(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=gy().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(n),s;if((s=r&&my[r[1].toLowerCase()])&&(n=s.map(i=>"<"+i+">").join("")+n+s.map(i=>"").reverse().join("")),t.innerHTML=rC(n),s)for(let i=0;i=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;s=k.from(a.create(r[l+1],s)),i++,o++}return new S(s,i,o)}var qe={},Je={},lC={touchstart:!0,touchmove:!0},od=class{constructor(){this.shiftKey=!1,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=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function aC(n){for(let e in qe){let t=qe[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{uC(n,r)&&!yd(n,r)&&(n.editable||!(r.type in Je))&&t(n,r)},lC[e]?{passive:!0}:void 0)}_e&&n.dom.addEventListener("input",()=>null),ld(n)}function sn(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function cC(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function ld(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>yd(n,r))})}function yd(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function uC(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function dC(n,e){!yd(n,e)&&qe[e.type]&&(n.editable||!(e.type in Je))&&qe[e.type](n,e)}Je.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!ky(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(rn&&Ce&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),Gr&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",s=>s(n,Gn(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||eC(n,t)?t.preventDefault():sn(n,"key")};Je.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};Je.keypress=(n,e)=>{let t=e;if(ky(n)||!t.charCode||t.ctrlKey&&!t.altKey||pt&&t.metaKey)return;if(n.someProp("handleKeyPress",s=>s(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof A)||!r.$from.sameParent(r.$to)){let s=String.fromCharCode(t.charCode),i=()=>n.state.tr.insertText(s).scrollIntoView();!/[\r\n]/.test(s)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,s,i))&&n.dispatch(i()),t.preventDefault()}};function ui(n){return{left:n.clientX,top:n.clientY}}function hC(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function wd(n,e,t,r,s){if(r==-1)return!1;let i=n.state.doc.resolve(r);for(let o=i.depth+1;o>0;o--)if(n.someProp(e,l=>o>i.depth?l(n,t,i.nodeAfter,i.before(o),s,!0):l(n,t,i.node(o),i.before(o),s,!1)))return!0;return!1}function di(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);t=="pointer"&&r.setMeta("pointer",!0),n.dispatch(r)}function fC(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&M.isSelectable(r)?(di(n,new M(t),"pointer"),!0):!1}function pC(n,e){if(e==-1)return!1;let t=n.state.selection,r,s;t instanceof M&&(r=t.node);let i=n.state.doc.resolve(e);for(let o=i.depth+1;o>0;o--){let l=o>i.depth?i.nodeAfter:i.node(o);if(M.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&i.before(t.$from.depth+1)==t.$from.pos?s=i.before(t.$from.depth):s=i.before(o);break}}return s!=null?(di(n,M.create(n.state.doc,s),"pointer"),!0):!1}function mC(n,e,t,r,s){return wd(n,"handleClickOn",e,t,r)||n.someProp("handleClick",i=>i(n,e,r))||(s?pC(n,t):fC(n,t))}function gC(n,e,t,r){return wd(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",s=>s(n,e,r))}function yC(n,e,t,r){return wd(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",s=>s(n,e,r))||wC(n,t,r)}function wC(n,e,t){if(t.button!=0)return!1;let r=yy(n,e,!0),s=n.state.doc;return r?(di(n,r,"pointer"),r instanceof A&&s.eq(n.state.doc)&&(n.input.mouseDown=new cd(n,r)),!0):!1}function yy(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?A.create(r,0,r.content.size):null;let s=r.resolve(e);for(let i=s.depth+1;i>0;i--){let o=i>s.depth?s.nodeAfter:s.node(i),l=s.before(i);if(o.inlineContent)return A.create(r,l+1,l+1+o.content.size);if(t&&M.isSelectable(o))return M.create(r,l)}return null}function kd(n){return nl(n)}var wy=pt?"metaKey":"ctrlKey";qe.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=kd(n),s=Date.now(),i="singleClick";s-n.input.lastClick.time<500&&hC(t,n.input.lastClick)&&!t[wy]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?i="doubleClick":n.input.lastClick.type=="doubleClick"&&(i="tripleClick")),n.input.lastClick={time:s,x:t.clientX,y:t.clientY,type:i,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(ui(t));o&&(i=="singleClick"?n.input.mouseDown=new ad(n,o,t,!!r):(i=="doubleClick"?gC:yC)(n,o.pos,o.inside,t)?t.preventDefault():sn(n,"pointer"))};var tl=class{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}},ad=class extends tl{constructor(e,t,r,s){super(e),this.pos=t,this.event=r,this.flushed=s,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[wy],this.allowDefault=r.shiftKey;let i,o;if(t.inside>-1)i=e.state.doc.nodeAt(t.inside),o=t.inside;else{let u=e.state.doc.resolve(t.pos);i=u.parent,o=u.depth?u.before():0}let l=s?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.nodeDOM.nodeType==1?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||c instanceof M&&c.from<=o&&c.to>o)&&(this.mightDrag={node:i,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&>&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),sn(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||on(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(ui(e))),this.updateAllowDefault(e),this.allowDefault||!t?sn(this.view,"pointer"):mC(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||_e&&this.mightDrag&&!this.mightDrag.node.isAtom||Ce&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(di(this.view,N.near(this.view.state.doc.resolve(t.pos)),"pointer"),e.preventDefault()):sn(this.view,"pointer")}move(e){this.updateAllowDefault(e),sn(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}},cd=class extends tl{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),sn(this.view,"pointer");let t=this.view.posAtCoords(ui(e)),r=t&&yy(this.view,t.inside,!1);if(!r)return;let{doc:s}=this.view.state,i=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),kd(n),sn(n,"pointer")};qe.touchmove=n=>{n.input.lastTouch=Date.now(),sn(n,"pointer")};qe.contextmenu=n=>kd(n);function ky(n,e){return n.composing?!0:_e&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}var kC=rn?5e3:-1;Je.compositionstart=Je.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof A&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Ce&&Xg&&bC(n)))n.markCursor=n.state.storedMarks||t.marks(),nl(n,!0),n.markCursor=null;else if(nl(n,!e.selection.empty),gt&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let s=r.focusNode,i=r.focusOffset;s&&s.nodeType==1&&i!=0;){let o=i<0?s.lastChild:s.childNodes[i-1];if(!o)break;if(o.nodeType==3){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else s=o,i=-1}}n.input.composing=!0}by(n,kC)};function bC(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}Je.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,by(n,20))};function by(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nl(n),e))}function xy(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function xC(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=w1(e.focusNode,e.focusOffset),r=k1(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let s=r.pmViewDesc,i=n.domObserver.lastChangedTextNode;if(t==i||r==i)return i;if(!s||!s.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nl(n,e=!1){if(!(rn&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),xy(n),e||n.docView&&n.docView.dirty){let t=pd(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function SC(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),s=document.createRange();s.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(s),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}var si=Ze&&An<15||Gr&&v1<604;qe.copy=Je.cut=(n,e)=>{let t=e,r=n.state.selection,s=t.type=="cut";if(r.empty)return;let i=si?null:t.clipboardData,o=r.content(),{dom:l,text:a}=gd(n,o);i?(t.preventDefault(),i.clearData(),i.setData("text/html",l.innerHTML),i.setData("text/plain",a)):SC(n,l),s&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function vC(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function CC(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let s=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?ii(n,r.value,null,s,e):ii(n,r.textContent,r.innerHTML,s,e)},50)}function ii(n,e,t,r,s){let i=dy(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,s,i||S.empty)))return!0;if(!i)return!1;let o=vC(i),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(i);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Sy(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}Je.paste=(n,e)=>{let t=e;if(n.composing&&!rn)return;let r=si?null:t.clipboardData,s=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&ii(n,Sy(r),r.getData("text/html"),s,t)?t.preventDefault():CC(n,t)};var rl=class{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}},TC=pt?"altKey":"ctrlKey";function vy(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[TC]}qe.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let s=n.state.selection,i=s.empty?null:n.posAtCoords(ui(t)),o;if(!(i&&i.pos>=s.from&&i.pos<=(s instanceof M?s.to-1:s.to))){if(r&&r.mightDrag)o=M.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let d=n.docView.nearestDesc(t.target,!0);d&&d.node.type.spec.draggable&&d!=n.docView&&(o=M.create(n.state.doc,d.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:u}=gd(n,l);(!t.dataTransfer.files.length||!Ce||Gg>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(si?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",si||t.dataTransfer.setData("text/plain",c),n.dragging=new rl(u,vy(n,t),o)};qe.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};Je.dragover=Je.dragenter=(n,e)=>e.preventDefault();Je.drop=(n,e)=>{try{AC(n,e,n.dragging)}finally{n.dragging=null}};function AC(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(ui(e));if(!r)return;let s=n.state.doc.resolve(r.pos),i=t&&t.slice;i?n.someProp("transformPasted",f=>{i=f(i,n,!1)}):i=dy(n,Sy(e.dataTransfer),si?null:e.dataTransfer.getData("text/html"),!1,s);let o=!!(t&&vy(n,e));if(n.someProp("handleDrop",f=>f(n,e,i||S.empty,o))){e.preventDefault();return}if(!i)return;e.preventDefault();let l=i?qo(n.state.doc,s.pos,i):s.pos;l==null&&(l=s.pos);let a=n.state.tr;if(o){let{node:f}=t;f?f.replace(a):a.deleteSelection()}let c=a.mapping.map(l),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,d=a.doc;if(u?a.replaceRangeWith(c,c,i.content.firstChild):a.replaceRange(c,c,i),a.doc.eq(d))return;let h=a.doc.resolve(c);if(u&&M.isSelectable(i.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(i.content.firstChild))a.setSelection(new M(h));else{let f=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>f=y),a.setSelection(md(n,h,a.doc.resolve(f)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}qe.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&on(n)},20))};qe.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)};qe.beforeinput=(n,e)=>{if(Ce&&rn&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",i=>i(n,Gn(8,"Backspace")))))return;let{$cursor:s}=n.state.selection;s&&s.pos>0&&n.dispatch(n.state.tr.delete(s.pos-1,s.pos).scrollIntoView())},50)}};for(let n in Je)qe[n]=Je[n];function oi(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}var sl=class n{constructor(e,t){this.toDOM=e,this.spec=t||er,this.side=this.spec.side||0}map(e,t,r,s){let{pos:i,deleted:o}=e.mapResult(t.from+s,this.side<0?-1:1);return o?null:new de(i-r,i-r,this)}valid(){return!0}eq(e){return this==e||e instanceof n&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&oi(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}},Zn=class n{constructor(e,t){this.attrs=e,this.spec=t||er}map(e,t,r,s){let i=e.map(t.from+s,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+s,this.spec.inclusiveEnd?1:-1)-r;return i>=o?null:new de(i,o,this)}valid(e,t){return t.from=e&&(!i||i(l.spec))&&r.push(l.copy(l.from+s,l.to+s))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,s+l,i)}}map(e,t,r){return this==Le||e.maps.length==0?this:this.mapInner(e,t,0,0,r||er)}mapInner(e,t,r,s,i){let o;for(let l=0;l{let c=a+r,u;if(u=Ty(t,l,c)){for(s||(s=this.children.slice());il&&d.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let i=e+1,o=i+t.content.size;for(let l=0;li&&a.type instanceof Zn){let c=Math.max(i,a.from)-i,u=Math.min(o,a.to)-i;cs.map(e,t,er));return n.from(r)}forChild(e,t){if(t.isLeaf)return X.empty;let r=[];for(let s=0;st instanceof X)?e:e.reduce((t,r)=>t.concat(r instanceof X?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(f-h);for(let y=0;yw+u-d)continue;let b=l[y]+u-d;f>=b?l[y+1]=h<=b?-2:-1:h>=u&&g&&(l[y]+=g,l[y+1]+=g)}d+=g}),u=t.maps[c].map(u,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let h=t.map(n[c+1]+i,-1),f=h-s,{index:p,offset:m}=r.content.findIndex(d),g=r.maybeChild(p);if(g&&m==d&&m+g.nodeSize==f){let y=l[c+2].mapInner(t,g,u+1,n[c]+i+1,o);y!=Le?(l[c]=d,l[c+1]=f,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=MC(l,n,e,t,s,i,o),u=ol(c,r,0,o);e=u.local;for(let d=0;dt&&o.to{let c=Ty(n,l,a+t);if(c){i=!0;let u=ol(c,l,t+a+1,r);u!=Le&&s.push(a,a+l.nodeSize,u)}});let o=Cy(i?Ay(n):n,-t).sort(tr);for(let l=0;l0;)e++;n.splice(e,0,t)}function qu(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=Le&&e.push(r)}),n.cursorWrapper&&e.push(X.create(n.state.doc,[n.cursorWrapper.deco])),il.from(e)}var RC={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},NC=Ze&&An<=11,dd=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}},hd=class{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new dd,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let s=0;ss.type=="childList"&&s.removedNodes.length||s.type=="characterData"&&s.oldValue.length>s.target.nodeValue.length)?this.flushSoon():_e&&e.composing&&r.some(s=>s.type=="childList"&&s.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),NC&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,RC)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}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=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Ig(this.view)){if(this.suppressingSelectionUpdates)return on(this.view);if(Ze&&An<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&nr(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let i=e.focusNode;i;i=Yr(i))t.add(i);for(let i=e.anchorNode;i;i=Yr(i))if(t.has(i)){r=i;break}let s=r&&this.view.docView.nearestDesc(r);if(s&&s.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),s=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Ig(e)&&!this.ignoreSelectionChange(r),i=-1,o=-1,l=!1,a=[];if(e.editable)for(let u=0;uu.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||Ce&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of a)if(u.nodeName=="BR"&&u.parentNode){let d=u.nextSibling;for(;d&&d.nodeType==1;){if(d.contentEditable=="false"){u.parentNode.removeChild(u);break}d=d.firstChild}}}else if(gt&&a.length){let u=a.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,h]=u;d.parentNode&&d.parentNode.parentNode==h.parentNode?h.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let h of u){let f=h.parentNode;f&&f.nodeName=="LI"&&(!d||OC(e,d)!=f)&&h.remove()}}}let c=null;i<0&&s&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||s)&&(i>-1&&(e.docView.markDirty(i,o),IC(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,PC(e,a)),this.handleDOMChange(i,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||on(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;us;g--){let y=r.childNodes[g-1],w=y.pmViewDesc;if(y.nodeName=="BR"&&!w){i=g;break}if(!w||w.size)break}let d=n.state.doc,h=n.someProp("domParser")||Ot.fromSchema(n.state.schema),f=d.resolve(o),p=null,m=h.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:s,to:i,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:_C,context:f});if(c&&c[0].pos!=null){let g=c[0].pos,y=c[1]&&c[1].pos;y==null&&(y=g),p={anchor:g+o,head:y+o}}return{doc:m,sel:p,from:o,to:l}}function _C(n){let e=n.pmViewDesc;if(e)return e.parseRule();if(n.nodeName=="BR"&&n.parentNode){if(_e&&/^(ul|ol)$/i.test(n.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}else if(n.parentNode.lastChild==n||_e&&/^(tr|table)$/i.test(n.parentNode.nodeName))return{ignore:!0}}else if(n.nodeName=="IMG"&&n.getAttribute("mark-placeholder"))return{ignore:!0};return null}var BC=/^(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 zC(n,e,t,r,s){let i=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let E=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,_=pd(n,E);if(_&&!n.state.selection.eq(_)){if(Ce&&rn&&n.input.lastKeyCode===13&&Date.now()-100ae(n,Gn(13,"Enter"))))return;let U=n.state.tr.setSelection(_);E=="pointer"?U.setMeta("pointer",!0):E=="key"&&U.scrollIntoView(),i&&U.setMeta("composition",i),n.dispatch(U)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=LC(n,e,t),u=n.state.doc,d=u.slice(c.from,c.to),h,f;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||rn)&&s.some(E=>E.nodeType==1&&!BC.test(E.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",E=>E(n,Gn(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof A&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let E=Hg(n,n.state.doc,c.sel);if(E&&!E.eq(n.state.selection)){let _=n.state.tr.setSelection(E);i&&_.setMeta("composition",i),n.dispatch(_)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),Ze&&An<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)==" \xA0"&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=u.resolve(p.start),w=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((Gr&&n.input.lastIOSEnter>Date.now()-225&&(!w||s.some(E=>E.nodeName=="DIV"||E.nodeName=="P"))||!w&&m.posE(n,Gn(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&UC(u,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",E=>E(n,Gn(8,"Backspace")))){rn&&Ce&&n.domObserver.suppressSelectionUpdates();return}Ce&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),rn&&!w&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(E){return E(n,Gn(13,"Enter"))})},20));let b=p.start,v=p.endA,C=E=>{let _=E||n.state.tr.replace(b,v,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let U=Hg(n,_.doc,c.sel);U&&!(Ce&&n.composing&&U.empty&&(p.start!=p.endB||n.input.lastChromeDeleteon(n),20));let E=C(n.state.tr.delete(b,v)),_=u.resolve(p.start).marksAcross(u.resolve(p.endA));_&&E.ensureMarks(_),n.dispatch(E)}else if(p.endA==p.endB&&(R=$C(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let E=C(n.state.tr);R.type=="add"?E.addMark(b,v,R.mark):E.removeMark(b,v,R.mark),n.dispatch(E)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let E=m.parent.textBetween(m.parentOffset,g.parentOffset),_=()=>C(n.state.tr.insertText(E,b,v));n.someProp("handleTextInput",U=>U(n,b,v,E,_))||n.dispatch(_())}else n.dispatch(C());else n.dispatch(C())}function Hg(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:md(n,e.resolve(t.anchor),e.resolve(t.head))}function $C(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,s=t,i=r,o,l,a;for(let u=0;uu.mark(l.addToSet(u.marks));else if(s.length==0&&i.length==1)l=i[0],o="remove",a=u=>u.mark(l.removeFromSet(u.marks));else return null;let c=[];for(let u=0;ut||Ju(o,!0,!1)0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,s++,e=!1;if(t){let i=n.node(r).maybeChild(n.indexAfter(r));for(;i&&!i.isLeaf;)i=i.firstChild,s++}return s}function FC(n,e,t,r,s){let i=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(i==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(s=="end"){let u=Math.max(0,i-Math.min(a,c));r-=a+u-i}if(a=a?i-r:0;i-=u,c=i+(c-a),a=i}else if(c=c?i-r:0;i-=u,a=i+(a-c),c=i}return{start:i,endA:a,endB:c}}var li=class{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new od,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(Kg),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=qg(this),jg(this),this.nodeViews=Jg(this),this.docView=Tg(this.state.doc,Wg(this),qu(this),this.dom,this),this.domObserver=new hd(this,(r,s,i,o)=>zC(this,r,s,i,o)),this.domObserver.start(),aC(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ld(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Kg),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let s=this.state,i=!1,o=!1;e.storedMarks&&this.composing&&(xy(this),o=!0),this.state=e;let l=s.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let f=Jg(this);HC(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&ld(this),this.editable=qg(this),jg(this);let a=qu(this),c=Wg(this),u=s.plugins!=e.plugins&&!s.doc.eq(e.doc)?"reset":e.scrollToSelection>s.scrollToSelection?"to selection":"preserve",d=i||!this.docView.matchesNode(e.doc,c,a);(d||!e.selection.eq(s.selection))&&(o=!0);let h=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&A1(this);if(o){this.domObserver.stop();let f=d&&(Ze||Ce)&&!this.composing&&!s.selection.empty&&!e.selection.empty&&VC(s.selection,e.selection);if(d){let m=Ce?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=xC(this)),(i||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=Tg(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}let p=this.input.mouseDown;f||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&J1(this)&&p.delaySelUpdate())?on(this,f):(ay(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(s),!((r=this.dragging)===null||r===void 0)&&r.node&&!s.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,s),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():h&&E1(h)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof M){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&kg(this,t.getBoundingClientRect(),e)}else kg(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&it.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return O1(this,e)}coordsAtPos(e,t=1){return ny(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let s=this.docView.posFromDOM(e,t,r);if(s==null)throw new RangeError("DOM position not inside the editor");return s}endOfTextblock(e,t){return z1(this,t||this.state,e)}pasteHTML(e,t){return ii(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return ii(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return gd(this,e)}destroy(){this.docView&&(cC(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],qu(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,g1())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return dC(this,e)}domSelectionRange(){let e=this.domSelection();return e?_e&&this.root.nodeType===11&&x1(this.dom.ownerDocument)==this.dom&&DC(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};li.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function Wg(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[de.node(0,n.state.doc.content.size,e)]}function jg(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:de.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function qg(n){return!n.someProp("editable",e=>e(n.state)===!1)}function VC(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function Jg(n){let e=Object.create(null);function t(r){for(let s in r)Object.prototype.hasOwnProperty.call(e,s)||(e[s]=r[s])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function HC(n,e){let t=0,r=0;for(let s in n){if(n[s]!=e[s])return!0;t++}for(let s in e)r++;return t!=r}function Kg(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var ln={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:"'"},cl={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},WC=typeof navigator<"u"&&/Mac/.test(navigator.platform),jC=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(he=0;he<10;he++)ln[48+he]=ln[96+he]=String(he);var he;for(he=1;he<=24;he++)ln[he+111]="F"+he;var he;for(he=65;he<=90;he++)ln[he]=String.fromCharCode(he+32),cl[he]=String.fromCharCode(he);var he;for(al in ln)cl.hasOwnProperty(al)||(cl[al]=ln[al]);var al;function Ey(n){var e=WC&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||jC&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?cl:ln)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var qC=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),JC=typeof navigator<"u"&&/Win/.test(navigator.platform);function KC(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,s,i,o;for(let l=0;l{for(var t in e)GC(n,t,{get:e[t],enumerable:!0})};function yl(n){let{state:e,transaction:t}=n,{selection:r}=t,{doc:s}=t,{storedMarks:i}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return i},get selection(){return r},get doc(){return s},get tr(){return r=t.selection,s=t.doc,i=t.storedMarks,t}}}var wl=class{constructor(n){this.editor=n.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=n.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){let{rawCommands:n,editor:e,state:t}=this,{view:r}=e,{tr:s}=t,i=this.buildProps(s);return Object.fromEntries(Object.entries(n).map(([o,l])=>[o,(...c)=>{let u=l(...c)(i);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(n,e=!0){let{rawCommands:t,editor:r,state:s}=this,{view:i}=r,o=[],l=!!n,a=n||s.tr,c=()=>(!l&&e&&!a.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(a),o.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(t).map(([d,h])=>[d,(...p)=>{let m=this.buildProps(a,e),g=h(...p)(m);return o.push(g),u}])),run:c};return u}createCan(n){let{rawCommands:e,state:t}=this,r=!1,s=n||t.tr,i=this.buildProps(s,r);return{...Object.fromEntries(Object.entries(e).map(([l,a])=>[l,(...c)=>a(...c)({...i,dispatch:void 0})])),chain:()=>this.createChain(s,r)}}buildProps(n,e=!0){let{rawCommands:t,editor:r,state:s}=this,{view:i}=r,o={tr:n,editor:r,view:i,state:yl({state:s,transaction:n}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(n,e),can:()=>this.createCan(n),get commands(){return Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)(o)]))}};return o}},$y={};Ed($y,{blur:()=>XC,clearContent:()=>QC,clearNodes:()=>ZC,command:()=>eT,createParagraphNear:()=>tT,cut:()=>nT,deleteCurrentNode:()=>rT,deleteNode:()=>sT,deleteRange:()=>iT,deleteSelection:()=>aT,enter:()=>cT,exitCode:()=>uT,extendMarkRange:()=>dT,first:()=>hT,focus:()=>pT,forEach:()=>mT,insertContent:()=>gT,insertContentAt:()=>kT,joinBackward:()=>ST,joinDown:()=>xT,joinForward:()=>vT,joinItemBackward:()=>CT,joinItemForward:()=>TT,joinTextblockBackward:()=>AT,joinTextblockForward:()=>ET,joinUp:()=>bT,keyboardShortcut:()=>RT,lift:()=>NT,liftEmptyBlock:()=>IT,liftListItem:()=>DT,newlineInCode:()=>OT,resetAttributes:()=>PT,scrollIntoView:()=>LT,selectAll:()=>_T,selectNodeBackward:()=>BT,selectNodeForward:()=>zT,selectParentNode:()=>$T,selectTextblockEnd:()=>UT,selectTextblockStart:()=>FT,setContent:()=>VT,setMark:()=>rA,setMeta:()=>sA,setNode:()=>iA,setNodeSelection:()=>oA,setTextDirection:()=>lA,setTextSelection:()=>aA,sinkListItem:()=>cA,splitBlock:()=>uA,splitListItem:()=>dA,toggleList:()=>fA,toggleMark:()=>pA,toggleNode:()=>mA,toggleWrap:()=>gA,undoInputRule:()=>yA,unsetAllMarks:()=>wA,unsetMark:()=>kA,unsetTextDirection:()=>bA,updateAttributes:()=>xA,wrapIn:()=>SA,wrapInList:()=>vA});var XC=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{var t;n.isDestroyed||(e.dom.blur(),(t=window?.getSelection())==null||t.removeAllRanges())}),!0),QC=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),ZC=()=>({state:n,tr:e,dispatch:t})=>{let{selection:r}=e,{ranges:s}=r;return t&&s.forEach(({$from:i,$to:o})=>{n.doc.nodesBetween(i.pos,o.pos,(l,a)=>{if(l.type.isText)return;let{doc:c,mapping:u}=e,d=c.resolve(u.map(a)),h=c.resolve(u.map(a+l.nodeSize)),f=d.blockRange(h);if(!f)return;let p=en(f);if(l.type.isTextblock){let{defaultType:m}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(f.start,m)}(p||p===0)&&e.lift(f,p)})}),!0},eT=n=>e=>n(e),tT=()=>({state:n,dispatch:e})=>Bu(n,e),nT=(n,e)=>({editor:t,tr:r})=>{let{state:s}=t,i=s.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);let o=r.mapping.map(e);return r.insert(o,i.content),r.setSelection(new A(r.doc.resolve(Math.max(o-1,0)))),!0},rT=()=>({tr:n,dispatch:e})=>{let{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;let s=n.selection.$anchor;for(let i=s.depth;i>0;i-=1)if(s.node(i).type===r.type){if(e){let l=s.before(i),a=s.after(i);n.delete(l,a).scrollIntoView()}return!0}return!1};function te(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}var sT=n=>({tr:e,state:t,dispatch:r})=>{let s=te(n,t.schema),i=e.selection.$anchor;for(let o=i.depth;o>0;o-=1)if(i.node(o).type===s){if(r){let a=i.before(o),c=i.after(o);e.delete(a,c).scrollIntoView()}return!0}return!1},iT=n=>({tr:e,dispatch:t})=>{let{from:r,to:s}=n;return t&&e.delete(r,s),!0},oT=n=>n.content?/^text(\*|\+)/.test(n.content):!1,Ry=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos{let r=Ry(n,t,"left"),s=Ry(e,t,"right");return{from:r,to:s}},aT=()=>({state:n,dispatch:e})=>{let{$from:t,$to:r}=n.selection;if(n.selection.empty)return!1;let{from:s,to:i}=lT(t,r,n.schema);return e&&(n.tr.deleteRange(s,i).scrollIntoView(),e(n.tr)),!0},cT=()=>({commands:n})=>n.keyboardShortcut("Enter"),uT=()=>({state:n,dispatch:e})=>_u(n,e);function Md(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function ml(n,e,t={strict:!0}){let r=Object.keys(e);return r.length?r.every(s=>t.strict?e[s]===n[s]:Md(e[s])?e[s].test(n[s]):e[s]===n[s]):!0}function Uy(n,e,t={}){return n.find(r=>r.type===e&&ml(Object.fromEntries(Object.keys(t).map(s=>[s,r.attrs[s]])),t))}function Ny(n,e,t={}){return!!Uy(n,e,t)}function Rd(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(c=>c.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(c=>c.type===e))return;if(!t){let c=r.node.marks.find(u=>u.type===e);c&&(t=c.attrs)}if(!Uy([...r.node.marks],e,t))return;let i=r.index,o=n.start()+r.offset,l=i+1,a=o+r.node.nodeSize;for(;i>0&&Ny([...n.parent.child(i-1).marks],e,t);)i-=1,o-=n.parent.child(i).nodeSize;for(;l({tr:t,state:r,dispatch:s})=>{let i=an(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:u}=l;if(s){let d=Rd(a,i,e);if(d&&d.from<=c&&d.to>=u){let h=A.create(o,d.from,d.to);t.setSelection(h)}}return!0},hT=n=>e=>{let t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:s,dispatch:i})=>{e={scrollIntoView:!0,...e};let o=()=>{(gl()||Iy())&&r.dom.focus(),fT()&&!gl()&&!Iy()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(i&&n===null&&!Fy(t.state.selection))return o(),!0;let l=Vy(s.doc,n)||t.state.selection,a=t.state.selection.eq(l);return i&&(a||s.setSelection(l),a&&s.storedMarks&&s.setStoredMarks(s.storedMarks),o()),!0},mT=(n,e)=>t=>n.every((r,s)=>e(r,{...t,index:s})),gT=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),Hy=n=>{let e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){let r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&Hy(r)}return n};function ul(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");let e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return Hy(t)}function gi(n,e,t){if(n instanceof Qe||n instanceof k)return n;t={slice:!0,parseOptions:{},...t};let r=typeof n=="object"&&n!==null,s=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return k.fromArray(n.map(l=>e.nodeFromJSON(l)));let o=e.nodeFromJSON(n);return t.errorOnInvalidContent&&o.check(),o}catch(i){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",i),gi("",e,t)}if(s){if(t.errorOnInvalidContent){let o=!1,l="",a=new $r({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?Ot.fromSchema(a).parseSlice(ul(n),t.parseOptions):Ot.fromSchema(a).parse(ul(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}let i=Ot.fromSchema(e);return t.slice?i.parseSlice(ul(n),t.parseOptions).content:i.parse(ul(n),t.parseOptions)}return gi("",e,t)}function yT(n,e,t){let r=n.steps.length-1;if(r{o===0&&(o=u)}),n.setSelection(N.near(n.doc.resolve(o),t))}var wT=n=>!("type"in n),kT=(n,e,t)=>({tr:r,dispatch:s,editor:i})=>{var o;if(s){t={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l,a=g=>{i.emit("contentError",{editor:i,error:g,disableCollaboration:()=>{"collaboration"in i.storage&&typeof i.storage.collaboration=="object"&&i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{gi(e,i.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{l=gi(e,i.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!=null?o:i.options.enableContentCheck})}catch(g){return a(g),!1}let{from:u,to:d}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},h=!0,f=!0;if((wT(l)?l:[l]).forEach(g=>{g.check(),h=h?g.isText&&g.marks.length===0:!1,f=f?g.isBlock:!1}),u===d&&f){let{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,d+=1)}let m;if(h){if(Array.isArray(e))m=e.map(g=>g.text||"").join("");else if(e instanceof k){let g="";e.forEach(y=>{y.text&&(g+=y.text)}),m=g}else typeof e=="object"&&e&&e.text?m=e.text:m=e;r.insertText(m,u,d)}else{m=l;let g=r.doc.resolve(u),y=g.node(),w=g.parentOffset===0,b=y.isText||y.isTextblock,v=y.content.size>0;w&&b&&v&&f&&(u=Math.max(0,u-1)),r.replaceWith(u,d,m)}t.updateSelection&&yT(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:m})}return!0},bT=()=>({state:n,dispatch:e})=>lg(n,e),xT=()=>({state:n,dispatch:e})=>ag(n,e),ST=()=>({state:n,dispatch:e})=>Mu(n,e),vT=()=>({state:n,dispatch:e})=>Iu(n,e),CT=()=>({state:n,dispatch:e,tr:t})=>{try{let r=Kn(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},TT=()=>({state:n,dispatch:e,tr:t})=>{try{let r=Kn(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},AT=()=>({state:n,dispatch:e})=>rg(n,e),ET=()=>({state:n,dispatch:e})=>sg(n,e);function Wy(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function MT(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t==="Space"&&(t=" ");let r,s,i,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:s})=>{let i=MT(n).split(/-(?!$)/),o=i.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{let u=c.map(r.mapping);u&&s&&r.maybeStep(u)}),!0};function _t(n,e,t={}){let{from:r,to:s,empty:i}=n.selection,o=e?te(e,n.schema):null,l=[];n.doc.nodesBetween(r,s,(d,h)=>{if(d.isText)return;let f=Math.max(r,h),p=Math.min(s,h+d.nodeSize);l.push({node:d,from:f,to:p})});let a=s-r,c=l.filter(d=>o?o.name===d.node.type.name:!0).filter(d=>ml(d.node.attrs,t,{strict:!1}));return i?!!c.length:c.reduce((d,h)=>d+h.to-h.from,0)>=a}var NT=(n,e={})=>({state:t,dispatch:r})=>{let s=te(n,t.schema);return _t(t,s,e)?cg(t,r):!1},IT=()=>({state:n,dispatch:e})=>zu(n,e),DT=n=>({state:e,dispatch:t})=>{let r=te(n,e.schema);return mg(r)(e,t)},OT=()=>({state:n,dispatch:e})=>Pu(n,e);function kl(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Dy(n,e){let t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,s)=>(t.includes(s)||(r[s]=n[s]),r),{})}var PT=(n,e)=>({tr:t,state:r,dispatch:s})=>{let i=null,o=null,l=kl(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(i=te(n,r.schema)),l==="mark"&&(o=an(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,d)=>{i&&i===u.type&&(a=!0,s&&t.setNodeMarkup(d,void 0,Dy(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(h=>{o===h.type&&(a=!0,s&&t.addMark(d,d+u.nodeSize,o.create(Dy(h.attrs,e))))})})}),a},LT=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),_T=()=>({tr:n,dispatch:e})=>{if(e){let t=new Ne(n.doc);n.setSelection(t)}return!0},BT=()=>({state:n,dispatch:e})=>Ru(n,e),zT=()=>({state:n,dispatch:e})=>Du(n,e),$T=()=>({state:n,dispatch:e})=>ug(n,e),UT=()=>({state:n,dispatch:e})=>Uu(n,e),FT=()=>({state:n,dispatch:e})=>$u(n,e);function Td(n,e,t={},r={}){return gi(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}var VT=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:s,tr:i,dispatch:o,commands:l})=>{let{doc:a}=i;if(r.preserveWhitespace!=="full"){let c=Td(n,s.schema,r,{errorOnInvalidContent:e??s.options.enableContentCheck});return o&&i.replaceWith(0,a.content.size,c).setMeta("preventUpdate",!t),!0}return o&&i.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??s.options.enableContentCheck})};function jy(n,e){let t=an(e,n.schema),{from:r,to:s,empty:i}=n.selection,o=[];i?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,s,a=>{o.push(...a.marks)});let l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function Nd(n,e){let t=new Sn(n);return e.forEach(r=>{r.steps.forEach(s=>{t.step(s)})}),t}function HT(n){for(let e=0;e{t(s)&&r.push({node:s,pos:i})}),r}function Id(n,e){for(let t=n.depth;t>0;t-=1){let r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function bl(n){return e=>Id(e.$from,n)}function I(n,e,t){return n.config[e]===void 0&&n.parent?I(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?I(n.parent,e,t):null}):n.config[e]}function Dd(n){return n.map(e=>{let t={name:e.name,options:e.options,storage:e.storage},r=I(e,"addExtensions",t);return r?[e,...Dd(r())]:e}).flat(10)}function Od(n,e){let t=Xt.fromSchema(e).serializeFragment(n),s=document.implementation.createHTMLDocument().createElement("div");return s.appendChild(t),s.innerHTML}function Jy(n){return typeof n=="function"}function W(n,e=void 0,...t){return Jy(n)?e?n.bind(e)(...t):n(...t):n}function WT(n={}){return Object.keys(n).length===0&&n.constructor===Object}function Qr(n){let e=n.filter(s=>s.type==="extension"),t=n.filter(s=>s.type==="node"),r=n.filter(s=>s.type==="mark");return{baseExtensions:e,nodeExtensions:t,markExtensions:r}}function Ky(n){let e=[],{nodeExtensions:t,markExtensions:r}=Qr(n),s=[...t,...r],i={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{let u={name:c.name,options:c.options,storage:c.storage,extensions:s},d=I(c,"addGlobalAttributes",u);if(!d)return;d().forEach(f=>{let p;Array.isArray(f.types)?p=f.types:f.types==="*"?p=a:f.types==="nodes"?p=o:f.types==="marks"?p=l:p=[],p.forEach(m=>{Object.entries(f.attributes).forEach(([g,y])=>{e.push({type:m,name:g,attribute:{...i,...y}})})})})}),s.forEach(c=>{let u={name:c.name,options:c.options,storage:c.storage},d=I(c,"addAttributes",u);if(!d)return;let h=d();Object.entries(h).forEach(([f,p])=>{let m={...i,...p};typeof m?.default=="function"&&(m.default=m.default()),m?.isRequired&&m?.default===void 0&&delete m.default,e.push({type:c.name,name:f,attribute:m})})}),e}function jT(n){let e=[],t="",r=!1,s=!1,i=0,o=n.length;for(let l=0;l0){i-=1,t+=a;continue}if(a===";"&&i===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Oy(n){let e=[],t=jT(n||""),r=t.length;for(let s=0;s!!e).reduce((e,t)=>{let r={...e};return Object.entries(t).forEach(([s,i])=>{if(!r[s]){r[s]=i;return}if(s==="class"){let l=i?String(i).split(" "):[],a=r[s]?r[s].split(" "):[],c=l.filter(u=>!a.includes(u));r[s]=[...a,...c].join(" ")}else if(s==="style"){let l=new Map([...Oy(r[s]),...Oy(i)]);r[s]=Array.from(l.entries()).map(([a,c])=>`${a}: ${c}`).join("; ")}else r[s]=i}),r},{})}function Zr(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>B(t,r),{})}function qT(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Py(n,e){return"style"in n?n:{...n,getAttrs:t=>{let r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;let s=e.reduce((i,o)=>{let l=o.attribute.parseHTML?o.attribute.parseHTML(t):qT(t.getAttribute(o.name));return l==null?i:{...i,[o.name]:l}},{});return{...r,...s}}}}function Ly(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&WT(t)?!1:t!=null))}function _y(n){var e,t;let r={};return!((e=n?.attribute)!=null&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),((t=n?.attribute)==null?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function JT(n,e){var t;let r=Ky(n),{nodeExtensions:s,markExtensions:i}=Qr(n),o=(t=s.find(c=>I(c,"topNode")))==null?void 0:t.name,l=Object.fromEntries(s.map(c=>{let u=r.filter(y=>y.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=n.reduce((y,w)=>{let b=I(w,"extendNodeSchema",d);return{...y,...b?b(c):{}}},{}),f=Ly({...h,content:W(I(c,"content",d)),marks:W(I(c,"marks",d)),group:W(I(c,"group",d)),inline:W(I(c,"inline",d)),atom:W(I(c,"atom",d)),selectable:W(I(c,"selectable",d)),draggable:W(I(c,"draggable",d)),code:W(I(c,"code",d)),whitespace:W(I(c,"whitespace",d)),linebreakReplacement:W(I(c,"linebreakReplacement",d)),defining:W(I(c,"defining",d)),isolating:W(I(c,"isolating",d)),attrs:Object.fromEntries(u.map(_y))}),p=W(I(c,"parseHTML",d));p&&(f.parseDOM=p.map(y=>Py(y,u)));let m=I(c,"renderHTML",d);m&&(f.toDOM=y=>m({node:y,HTMLAttributes:Zr(y,u)}));let g=I(c,"renderText",d);return g&&(f.toText=g),[c.name,f]})),a=Object.fromEntries(i.map(c=>{let u=r.filter(g=>g.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=n.reduce((g,y)=>{let w=I(y,"extendMarkSchema",d);return{...g,...w?w(c):{}}},{}),f=Ly({...h,inclusive:W(I(c,"inclusive",d)),excludes:W(I(c,"excludes",d)),group:W(I(c,"group",d)),spanning:W(I(c,"spanning",d)),code:W(I(c,"code",d)),attrs:Object.fromEntries(u.map(_y))}),p=W(I(c,"parseHTML",d));p&&(f.parseDOM=p.map(g=>Py(g,u)));let m=I(c,"renderHTML",d);return m&&(f.toDOM=g=>m({mark:g,HTMLAttributes:Zr(g,u)})),[c.name,f]}));return new $r({topNode:o,nodes:l,marks:a})}function KT(n){let e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function mi(n){return n.sort((t,r)=>{let s=I(t,"priority")||100,i=I(r,"priority")||100;return s>i?-1:sr.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Gy(n,e,t){let{from:r,to:s}=e,{blockSeparator:i=` -`,textSerializers:o={}}=t||{},l="";return n.nodesBetween(r,s,(a,c,u,d)=>{var h;a.isBlock&&c>r&&(l+=i);let f=o?.[a.type.name];if(f)return u&&(l+=f({node:a,pos:c,parent:u,index:d,range:e})),!1;a.isText&&(l+=(h=a?.text)==null?void 0:h.slice(Math.max(r,c)-c,s-c))}),l}function qT(n,e){let t={from:0,to:n.content.size};return qy(n,t,e)}function Jy(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function JT(n,e){let t=te(e,n.schema),{from:r,to:s}=n.selection,i=[];n.doc.nodesBetween(r,s,l=>{i.push(l)});let o=i.reverse().find(l=>l.type.name===t.name);return o?{...o.attrs}:{}}function Dd(n,e){let t=wl(typeof e=="string"?e:e.name,n.schema);return t==="node"?JT(n,e):t==="mark"?Fy(n,e):{}}function KT(n,e=JSON.stringify){let t={};return n.filter(r=>{let s=e(r);return Object.prototype.hasOwnProperty.call(t,s)?!1:t[s]=!0})}function YT(n){let e=KT(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,o)=>o!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Od(n){let{mapping:e,steps:t}=n,r=[];return e.maps.forEach((s,i)=>{let o=[];if(s.ranges.length)s.forEach((l,a)=>{o.push({from:l,to:a})});else{let{from:l,to:a}=t[i];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{let c=e.slice(i).map(l,-1),u=e.slice(i).map(a),d=e.invert().map(c,-1),h=e.invert().map(u);r.push({oldRange:{from:d,to:h},newRange:{from:c,to:u}})})}),YT(r)}function bl(n,e,t){let r=[];return n===e?t.resolve(n).marks().forEach(s=>{let i=t.resolve(n),o=Ed(i,s.type);o&&r.push({mark:s,...o})}):t.nodesBetween(n,e,(s,i)=>{!s||s?.nodeSize===void 0||r.push(...s.marks.map(o=>({from:i,to:i+s.nodeSize,mark:o})))}),r}var Ky=(n,e,t,r=20)=>{let s=n.doc.resolve(t),i=r,o=null;for(;i>0&&o===null;){let l=s.node(i);l?.type.name===e?o=l:i-=1}return[o,i]};function di(n,e){return e.nodes[n]||e.marks[n]||null}function fl(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{let s=n.find(i=>i.type===e&&i.name===r);return s?s.attribute.keepOnSplit:!1}))}var GT=(n,e=500)=>{let t="",r=n.parentOffset;return n.parent.nodesBetween(Math.max(0,r-e),r,(s,i,o,l)=>{var a,c;let u=((c=(a=s.type.spec).toText)==null?void 0:c.call(a,{node:s,pos:i,parent:o,index:l}))||s.textContent||"%leaf%";t+=s.isAtom&&!s.isText?u:u.slice(0,Math.max(0,r-i))}),t};function Cd(n,e,t={}){let{empty:r,ranges:s}=n.selection,i=e?ln(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(d=>i?i.name===d.type.name:!0).find(d=>pl(d.attrs,t,{strict:!1}));let o=0,l=[];if(s.forEach(({$from:d,$to:h})=>{let f=d.pos,p=h.pos;n.doc.nodesBetween(f,p,(m,g)=>{if(i&&m.inlineContent&&!m.type.allowsMarkType(i))return!1;if(!m.isText&&!m.marks.length)return;let y=Math.max(f,g),w=Math.min(p,g+m.nodeSize),b=w-y;o+=b,l.push(...m.marks.map(v=>({mark:v,from:y,to:w})))})}),o===0)return!1;let a=l.filter(d=>i?i.name===d.mark.type.name:!0).filter(d=>pl(d.mark.attrs,t,{strict:!1})).reduce((d,h)=>d+h.to-h.from,0),c=l.filter(d=>i?d.mark.type!==i&&d.mark.type.excludes(i):!0).reduce((d,h)=>d+h.to-h.from,0);return(a>0?a+c:a)>=o}function XT(n,e,t={}){if(!e)return _t(n,null,t)||Cd(n,null,t);let r=wl(e,n.schema);return r==="node"?_t(n,e,t):r==="mark"?Cd(n,e,t):!1}var Yy=(n,e)=>{let{$from:t,$to:r,$anchor:s}=n.selection;if(e){let i=kl(l=>l.type.name===e)(n.selection);if(!i)return!1;let o=n.doc.resolve(i.pos+1);return s.pos+1===o.end()}return!(r.parentOffset{let{$from:e,$to:t}=n.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function Oy(n,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===n.name):e}function bd(n,e){let{nodeExtensions:t}=Qr(e),r=t.find(o=>o.name===n);if(!r)return!1;let s={name:r.name,options:r.options,storage:r.storage},i=W(N(r,"group",s));return typeof i!="string"?!1:i.split(" ").includes("list")}function es(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){var r;if(t){if(n.type.name==="hardBreak")return!0;if(n.isText)return!/\S/.test((r=n.text)!=null?r:"")}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let s=!0;return n.content.forEach(i=>{s!==!1&&(es(i,{ignoreWhitespace:t,checkChildren:e})||(s=!1))}),s}return!1}function xl(n){return n instanceof M}var Sl=class Xy{constructor(e){this.position=e}static fromJSON(e){return new Xy(e.position)}toJSON(){return{position:this.position}}};function Pd(n,e){let t=e.mapping.mapResult(n.position);return{position:new Sl(t.pos),mapResult:t}}function QT(n){return new Sl(n)}function ZT(n,e,t){var r;let{selection:s}=e,i=null;if(By(s)&&(i=s.$cursor),i){let l=(r=n.storedMarks)!=null?r:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(c=>c.type.excludes(t)))}let{ranges:o}=s;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(u,d,h)=>{if(c)return!1;if(u.isInline){let f=!h||h.type.allowsMarkType(t),p=!!t.isInSet(u.marks)||!u.marks.some(m=>m.type.excludes(t));c=f&&p}return!c}),c})}var eA=(n,e={})=>({tr:t,state:r,dispatch:s})=>{let{selection:i}=t,{empty:o,ranges:l}=i,a=ln(n,r.schema);if(s)if(o){let c=Fy(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{let u=c.$from.pos,d=c.$to.pos;r.doc.nodesBetween(u,d,(h,f)=>{let p=Math.max(f,u),m=Math.min(f+h.nodeSize,d);h.marks.find(y=>y.type===a)?h.marks.forEach(y=>{a===y.type&&t.addMark(p,m,a.create({...y.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return ZT(r,t,a)},tA=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),nA=(n,e={})=>({state:t,dispatch:r,chain:s})=>{let i=te(n,t.schema),o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),i.isTextblock?s().command(({commands:l})=>Uu(i,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Uu(i,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},rA=n=>({tr:e,dispatch:t})=>{if(t){let{doc:r}=e,s=sr(n,0,r.content.size),i=M.create(r,s);e.setSelection(i)}return!0},sA=(n,e)=>({tr:t,state:r,dispatch:s})=>{let{selection:i}=r,o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=i.from,l=i.to),s&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},iA=n=>({tr:e,dispatch:t})=>{if(t){let{doc:r}=e,{from:s,to:i}=typeof n=="number"?{from:n,to:n}:n,o=E.atStart(r).from,l=E.atEnd(r).to,a=sr(s,o,l),c=sr(i,o,l),u=E.create(r,a,c);e.setSelection(u)}return!0},oA=n=>({state:e,dispatch:t})=>{let r=te(n,e.schema);return hg(r)(e,t)};function Py(n,e){let t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){let r=t.filter(s=>e?.includes(s.type.name));n.tr.ensureMarks(r)}}var lA=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:s})=>{let{selection:i,doc:o}=e,{$from:l,$to:a}=i,c=s.extensionManager.attributes,u=fl(c,l.node().type.name,l.node().attrs);if(i instanceof M&&i.node.isBlock)return!l.parentOffset||!ot(o,l.pos)?!1:(r&&(n&&Py(t,s.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;let d=a.parentOffset===a.parent.content.size,h=l.depth===0?void 0:UT(l.node(-1).contentMatchAt(l.indexAfter(-1))),f=d&&h?[{type:h,attrs:u}]:void 0,p=ot(e.doc,e.mapping.map(l.pos),1,f);if(!f&&!p&&ot(e.doc,e.mapping.map(l.pos),1,h?[{type:h}]:void 0)&&(p=!0,f=h?[{type:h,attrs:u}]:void 0),r){if(p&&(i instanceof E&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,f),h&&!d&&!l.parentOffset&&l.parent.type!==h)){let m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,h)&&e.setNodeMarkup(e.mapping.map(l.before()),h)}n&&Py(t,s.extensionManager.splittableMarks),e.scrollIntoView()}return p},aA=(n,e={})=>({tr:t,state:r,dispatch:s,editor:i})=>{var o;let l=te(n,r.schema),{$from:a,$to:c}=r.selection,u=r.selection.node;if(u&&u.isBlock||a.depth<2||!a.sameParent(c))return!1;let d=a.node(-1);if(d.type!==l)return!1;let h=i.extensionManager.attributes;if(a.parent.content.size===0&&a.node(-1).childCount===a.indexAfter(-1)){if(a.depth===2||a.node(-3).type!==l||a.index(-2)!==a.node(-2).childCount-1)return!1;if(s){let y=k.empty,w=a.index(-1)?1:a.index(-2)?2:3;for(let _=a.depth-w;_>=a.depth-3;_-=1)y=k.from(a.node(_).copy(y));let b=a.indexAfter(-1){if(A>-1)return!1;_.isTextblock&&_.content.size===0&&(A=U+1)}),A>-1&&t.setSelection(E.near(t.doc.resolve(A))),t.scrollIntoView()}return!0}let f=c.pos===a.end()?d.contentMatchAt(0).defaultType:null,p={...fl(h,d.type.name,d.attrs),...e},m={...fl(h,a.node().type.name,a.node().attrs),...e};t.delete(a.pos,c.pos);let g=f?[{type:l,attrs:p},{type:f,attrs:m}]:[{type:l,attrs:p}];if(!ot(t.doc,a.pos,2))return!1;if(s){let{selection:y,storedMarks:w}=r,{splittableMarks:b}=i.extensionManager,v=w||y.$to.parentOffset&&y.$from.marks();if(t.split(a.pos,2,g).scrollIntoView(),!v||!s)return!0;let C=v.filter(R=>b.includes(R.type.name));t.ensureMarks(C)}return!0},xd=(n,e)=>{let t=kl(o=>o.type===e)(n.selection);if(!t)return!0;let r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;let s=n.doc.nodeAt(r);return t.node.type===s?.type&&ft(n.doc,t.pos)&&n.join(t.pos),!0},Sd=(n,e)=>{let t=kl(o=>o.type===e)(n.selection);if(!t)return!0;let r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;let s=n.doc.nodeAt(r);return t.node.type===s?.type&&ft(n.doc,r)&&n.join(r),!0};function cA(n){let e=n.doc,t=e.firstChild;if(!t)return null;let r=e.resolve(1),s=e.resolve(t.nodeSize-1);return E.between(r,s)}var uA=(n,e,t,r={})=>({editor:s,tr:i,state:o,dispatch:l,chain:a,commands:c,can:u})=>{let{extensions:d,splittableMarks:h}=s.extensionManager,f=te(n,o.schema),p=te(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:w}=m,b=y.blockRange(w),v=g||m.$to.parentOffset&&m.$from.marks();if(!b)return!1;let C=kl(ge=>bd(ge.type.name,d))(m),R=m.from===0&&m.to===o.doc.content.size,A=o.doc.content.content,_=A.length===1?A[0]:null,U=R&&_&&bd(_.type.name,d)?{node:_,pos:0,depth:0}:null,ae=C??U,ce=!!C&&b.depth>=1&&b.depth-C.depth<=1,xe=!!U;if((ce||xe)&&ae){if(ae.node.type===f)return R&&xe?a().command(({tr:ge,dispatch:Se})=>{let ie=cA(ge);return ie?(ge.setSelection(ie),Se&&Se(ge),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(bd(ae.node.type.name,d)&&f.validContent(ae.node.content))return a().command(()=>(i.setNodeMarkup(ae.pos,f),!0)).command(()=>xd(i,f)).command(()=>Sd(i,f)).run()}return!t||!v||!l?a().command(()=>u().wrapInList(f,r)?!0:c.clearNodes()).wrapInList(f,r).command(()=>xd(i,f)).command(()=>Sd(i,f)).run():a().command(()=>{let ge=u().wrapInList(f,r),Se=v.filter(ie=>h.includes(ie.type.name));return i.ensureMarks(Se),ge?!0:c.clearNodes()}).wrapInList(f,r).command(()=>xd(i,f)).command(()=>Sd(i,f)).run()},dA=(n,e={},t={})=>({state:r,commands:s})=>{let{extendEmptyMarkRange:i=!1}=t,o=ln(n,r.schema);return Cd(r,o,e)?s.unsetMark(o,{extendEmptyMarkRange:i}):s.setMark(o,e)},hA=(n,e,t={})=>({state:r,commands:s})=>{let i=te(n,r.schema),o=te(e,r.schema),l=_t(r,i,t),a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?s.setNode(o,a):s.setNode(i,{...a,...t})},fA=(n,e={})=>({state:t,commands:r})=>{let s=te(n,t.schema);return _t(t,s,e)?r.lift(s):r.wrapIn(s,e)},pA=()=>({state:n,dispatch:e})=>{let t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(i.text){let a=o.doc.resolve(i.from).marks();o.replaceWith(i.from,i.to,n.schema.text(i.text,a))}else o.delete(i.from,i.to)}return!0}}return!1},mA=(n={})=>({tr:e,dispatch:t,editor:r})=>{let{ignoreClearable:s=!1}=n,{selection:i}=e,{empty:o,ranges:l}=i;if(o)return!0;let{nonClearableMarks:a}=r.extensionManager;if(t){let c=Object.values(r.schema.marks).filter(u=>s||!a.includes(u.name));l.forEach(u=>{for(let d of c)e.removeMark(u.$from.pos,u.$to.pos,d)})}return!0},gA=(n,e={})=>({tr:t,state:r,dispatch:s})=>{var i;let{extendEmptyMarkRange:o=!1}=e,{selection:l}=t,a=ln(n,r.schema),{$from:c,empty:u,ranges:d}=l;if(!s)return!0;if(u&&o){let{from:h,to:f}=l,p=(i=c.marks().find(g=>g.type===a))==null?void 0:i.attrs,m=Ed(c,a,p);m&&(h=m.from,f=m.to),t.removeMark(h,f,a)}else d.forEach(h=>{t.removeMark(h.$from.pos,h.$to.pos,a)});return t.removeStoredMark(a),!0},yA=n=>({tr:e,state:t,dispatch:r})=>{let{selection:s}=t,i,o;return typeof n=="number"?(i=n,o=n):n&&"from"in n&&"to"in n?(i=n.from,o=n.to):(i=s.from,o=s.to),r&&e.doc.nodesBetween(i,o,(l,a)=>{if(l.isText)return;let c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},wA=(n,e={})=>({tr:t,state:r,dispatch:s})=>{let i=null,o=null,l=wl(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(i=te(n,r.schema)),l==="mark"&&(o=ln(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{let u=c.$from.pos,d=c.$to.pos,h,f,p,m;t.selection.empty?r.doc.nodesBetween(u,d,(g,y)=>{i&&i===g.type&&(a=!0,p=Math.max(y,u),m=Math.min(y+g.nodeSize,d),h=y,f=g)}):r.doc.nodesBetween(u,d,(g,y)=>{y=u&&y<=d&&(i&&i===g.type&&(a=!0,s&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(w=>{if(o===w.type&&(a=!0,s)){let b=Math.max(y,u),v=Math.min(y+g.nodeSize,d);t.addMark(b,v,o.create({...w.attrs,...e}))}}))}),f&&(h!==void 0&&s&&t.setNodeMarkup(h,void 0,{...f.attrs,...e}),o&&f.marks.length&&f.marks.forEach(g=>{o===g.type&&s&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},kA=(n,e={})=>({state:t,dispatch:r})=>{let s=te(n,t.schema);return cg(s,e)(t,r)},bA=(n,e={})=>({state:t,dispatch:r})=>{let s=te(n,t.schema);return ug(s,e)(t,r)},xA=class{constructor(){this.callbacks={}}on(n,e){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(e),this}emit(n,...e){let t=this.callbacks[n];return t&&t.forEach(r=>r.apply(this,e)),this}off(n,e){let t=this.callbacks[n];return t&&(e?this.callbacks[n]=t.filter(r=>r!==e):delete this.callbacks[n]),this}once(n,e){let t=(...r)=>{this.off(n,t),e.apply(this,r)};return this.on(n,t)}removeAllListeners(){this.callbacks={}}},vl=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!=null?e:!0}},SA=(n,e)=>{if(Ad(e))return e.exec(n);let t=e(n);if(!t)return null;let r=[t.text];return r.index=t.index,r.input=n,r.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(t.replaceWith)),r};function ul(n){var e;let{editor:t,from:r,to:s,text:i,rules:o,plugin:l}=n,{view:a}=t;if(a.composing)return!1;let c=a.state.doc.resolve(r);if(c.parent.type.spec.code||(e=c.nodeBefore||c.nodeAfter)!=null&&e.marks.find(h=>h.type.spec.code))return!1;let u=!1,d=GT(c)+i;return o.forEach(h=>{if(u)return;let f=SA(d,h.find);if(!f)return;let p=a.state.tr,m=gl({state:a.state,transaction:p}),g={from:r-(f[0].length-i.length),to:s},{commands:y,chain:w,can:b}=new yl({editor:t,state:m});h.handler({state:m,range:g,match:f,commands:y,chain:w,can:b})===null||!p.steps.length||(h.undoable&&p.setMeta(l,{transform:p,from:r,to:s,text:i}),a.dispatch(p),u=!0)}),u}function vA(n){let{editor:e,rules:t}=n,r=new O({state:{init(){return null},apply(s,i,o){let l=s.getMeta(r);if(l)return l;let a=s.getMeta("applyInputRules");return a&&setTimeout(()=>{let{text:u}=a;typeof u=="string"?u=u:u=Id(k.from(u),o.schema);let{from:d}=a,h=d+u.length;ul({editor:e,from:d,to:h,text:u,rules:t,plugin:r})}),s.selectionSet||s.docChanged?null:i}},props:{handleTextInput(s,i,o,l){return ul({editor:e,from:i,to:o,text:l,rules:t,plugin:r})},handleDOMEvents:{compositionend:s=>(setTimeout(()=>{let{$cursor:i}=s.state.selection;i&&ul({editor:e,from:i.pos,to:i.pos,text:"",rules:t,plugin:r})}),!1)},handleKeyDown(s,i){if(i.key!=="Enter")return!1;let{$cursor:o}=s.state.selection;return o?ul({editor:e,from:o.pos,to:o.pos,text:` -`,rules:t,plugin:r}):!1}},isInputRules:!0});return r}function CA(n){return Object.prototype.toString.call(n).slice(8,-1)}function dl(n){return CA(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function Qy(n,e){let t={...n};return dl(n)&&dl(e)&&Object.keys(e).forEach(r=>{dl(e[r])&&dl(n[r])?t[r]=Qy(n[r],e[r]):t[r]=e[r]}),t}var Ld=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...W(N(this,"addOptions",{name:this.name}))}}get storage(){return{...W(N(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){let e=this.extend({...this.config,addOptions:()=>Qy(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){let e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},lt=class Zy extends Ld{constructor(){super(...arguments),this.type="mark"}static create(e={}){let t=typeof e=="function"?e():e;return new Zy(t)}static handleExit({editor:e,mark:t}){let{tr:r}=e.state,s=e.state.selection.$from;if(s.pos===s.end()){let o=s.marks();if(!!!o.find(c=>c?.type.name===t.name))return!1;let a=o.find(c=>c?.type.name===t.name);return a&&r.removeStoredMark(a),r.insertText(" ",s.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){let t=typeof e=="function"?e():e;return super.extend(t)}};function TA(n){return typeof n=="number"}var AA=class{constructor(n){this.find=n.find,this.handler=n.handler}},EA=(n,e,t)=>{if(Ad(e))return[...n.matchAll(e)];let r=e(n,t);return r?r.map(s=>{let i=[s.text];return i.index=s.index,i.input=n,i.data=s.data,s.replaceWith&&(s.text.includes(s.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),i.push(s.replaceWith)),i}):[]};function MA(n){let{editor:e,state:t,from:r,to:s,rule:i,pasteEvent:o,dropEvent:l}=n,{commands:a,chain:c,can:u}=new yl({editor:e,state:t}),d=[];return t.doc.nodesBetween(r,s,(f,p)=>{var m,g,y,w,b;if((g=(m=f.type)==null?void 0:m.spec)!=null&&g.code||!(f.isText||f.isTextblock||f.isInline))return;let v=(b=(w=(y=f.content)==null?void 0:y.size)!=null?w:f.nodeSize)!=null?b:0,C=Math.max(r,p),R=Math.min(s,p+v);if(C>=R)return;let A=f.isText?f.text||"":f.textBetween(C-p,R-p,void 0,"\uFFFC");EA(A,i.find,o).forEach(U=>{if(U.index===void 0)return;let ae=C+U.index+1,ce=ae+U[0].length,xe={from:t.tr.mapping.map(ae),to:t.tr.mapping.map(ce)},ge=i.handler({state:t,range:xe,match:U,commands:a,chain:c,can:u,pasteEvent:o,dropEvent:l});d.push(ge)})}),d.every(f=>f!==null)}var hl=null,RA=n=>{var e;let t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)==null||e.setData("text/html",n),t};function NA(n){let{editor:e,rules:t}=n,r=null,s=!1,i=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}let a=({state:u,from:d,to:h,rule:f,pasteEvt:p})=>{let m=u.tr,g=gl({state:u,transaction:m});if(!(!MA({editor:e,state:g,from:Math.max(d-1,0),to:h.b-1,rule:f,pasteEvent:p,dropEvent:l})||!m.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,m}};return t.map(u=>new O({view(d){let h=p=>{var m;r=(m=d.dom.parentElement)!=null&&m.contains(p.target)?d.dom.parentElement:null,r&&(hl=e)},f=()=>{hl&&(hl=null)};return window.addEventListener("dragstart",h),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",h),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(d,h)=>{if(i=r===d.dom.parentElement,l=h,!i){let f=hl;f?.isEditable&&setTimeout(()=>{let p=f.state.selection;p&&f.commands.deleteRange({from:p.from,to:p.to})},10)}return!1},paste:(d,h)=>{var f;let p=(f=h.clipboardData)==null?void 0:f.getData("text/html");return o=h,s=!!p?.includes("data-pm-slice"),!1}}},appendTransaction:(d,h,f)=>{let p=d[0],m=p.getMeta("uiEvent")==="paste"&&!s,g=p.getMeta("uiEvent")==="drop"&&!i,y=p.getMeta("applyPasteRules"),w=!!y;if(!m&&!g&&!w)return;if(w){let{text:C}=y;typeof C=="string"?C=C:C=Id(k.from(C),f.schema);let{from:R}=y,A=R+C.length,_=RA(C);return a({rule:u,state:f,from:R,to:{b:A},pasteEvt:_})}let b=h.doc.content.findDiffStart(f.doc.content),v=h.doc.content.findDiffEnd(f.doc.content);if(!(!TA(b)||!v||b===v.b))return a({rule:u,state:f,from:b,to:v,pasteEvt:o})}}))}var Cl=class{constructor(n,e){this.splittableMarks=[],this.nonClearableMarks=[],this.editor=e,this.baseExtensions=n,this.extensions=jy(n),this.schema=WT(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((n,e)=>{let t={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:di(e.name,this.schema)},r=N(e,"addCommands",t);return r?{...n,...r()}:n},{})}get plugins(){let{editor:n}=this;return fi([...this.extensions].reverse()).flatMap(r=>{let s={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:n,type:di(r.name,this.schema)},i=[],o=N(r,"addKeyboardShortcuts",s),l={};if(r.type==="mark"&&N(r,"exitable",s)&&(l.ArrowRight=()=>lt.handleExit({editor:n,mark:r})),o){let h=Object.fromEntries(Object.entries(o()).map(([f,p])=>[f,()=>p({editor:n})]));l={...l,...h}}let a=Cy(l);i.push(a);let c=N(r,"addInputRules",s);if(Oy(r,n.options.enableInputRules)&&c){let h=c();if(h&&h.length){let f=vA({editor:n,rules:h}),p=Array.isArray(f)?f:[f];i.push(...p)}}let u=N(r,"addPasteRules",s);if(Oy(r,n.options.enablePasteRules)&&u){let h=u();if(h&&h.length){let f=NA({editor:n,rules:h});i.push(...f)}}let d=N(r,"addProseMirrorPlugins",s);if(d){let h=d();i.push(...h)}return i})}get attributes(){return Wy(this.extensions)}get nodeViews(){let{editor:n}=this,{nodeExtensions:e}=Qr(this.extensions);return Object.fromEntries(e.filter(t=>!!N(t,"addNodeView")).map(t=>{let r=this.attributes.filter(a=>a.type===t.name),s={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:te(t.name,this.schema)},i=N(t,"addNodeView",s);if(!i)return[];let o=i();if(!o)return[];let l=(a,c,u,d,h)=>{let f=Zr(a,r);return o({node:a,view:c,getPos:u,decorations:d,innerDecorations:h,editor:n,extension:t,HTMLAttributes:f})};return[t.name,l]}))}dispatchTransaction(n){let{editor:e}=this;return fi([...this.extensions].reverse()).reduceRight((r,s)=>{let i={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:e,type:di(s.name,this.schema)},o=N(s,"dispatchTransaction",i);return o?l=>{o.call(i,{transaction:l,next:r})}:r},n)}transformPastedHTML(n){let{editor:e}=this;return fi([...this.extensions]).reduce((r,s)=>{let i={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:e,type:di(s.name,this.schema)},o=N(s,"transformPastedHTML",i);return o?(l,a)=>{let c=r(l,a);return o.call(i,c)}:r},n||(r=>r))}get markViews(){let{editor:n}=this,{markExtensions:e}=Qr(this.extensions);return Object.fromEntries(e.filter(t=>!!N(t,"addMarkView")).map(t=>{let r=this.attributes.filter(l=>l.type===t.name),s={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:ln(t.name,this.schema)},i=N(t,"addMarkView",s);if(!i)return[];let o=(l,a,c)=>{let u=Zr(l,r);return i()({mark:l,view:a,inline:c,editor:n,extension:t,HTMLAttributes:u,updateAttributes:d=>{UA(l,n,d)}})};return[t.name,o]}))}destroy(){this.extensions.forEach(n=>{let e=n;for(;e.parent;){let t=e.parent;t.child===e&&(t.child=null),e=t}}),this.extensions=[],this.baseExtensions=[],this.schema=null,this.editor=null}setupExtensions(){let n=this.extensions;this.editor.extensionStorage=Object.fromEntries(n.map(e=>[e.name,e.storage])),n.forEach(e=>{var t,r;let s={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:di(e.name,this.schema)};e.type==="mark"&&(((t=W(N(e,"keepOnSplit",s)))==null||t)&&this.splittableMarks.push(e.name),(r=W(N(e,"clearable",s)))==null||r||this.nonClearableMarks.push(e.name));let i=N(e,"onBeforeCreate",s),o=N(e,"onCreate",s),l=N(e,"onUpdate",s),a=N(e,"onSelectionUpdate",s),c=N(e,"onTransaction",s),u=N(e,"onFocus",s),d=N(e,"onBlur",s),h=N(e,"onDestroy",s);i&&this.editor.on("beforeCreate",i),o&&this.editor.on("create",o),l&&this.editor.on("update",l),a&&this.editor.on("selectionUpdate",a),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),h&&this.editor.on("destroy",h)})}};Cl.resolve=jy;Cl.sort=fi;Cl.flatten=Nd;var IA={};Td(IA,{ClipboardTextSerializer:()=>tw,Commands:()=>nw,Delete:()=>rw,Drop:()=>sw,Editable:()=>iw,FocusEvents:()=>lw,Keymap:()=>aw,Paste:()=>cw,Tabindex:()=>uw,TextDirection:()=>dw,focusEventsPluginKey:()=>ow});var F=class ew extends Ld{constructor(){super(...arguments),this.type="extension"}static create(e={}){let t=typeof e=="function"?e():e;return new ew(t)}configure(e){return super.configure(e)}extend(e){let t=typeof e=="function"?e():e;return super.extend(t)}},tw=F.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new O({key:new P("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{let{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:s}=e,i=Jy(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:i};return[...s.ranges].sort((c,u)=>c.$from.pos-u.$from.pos).map(({$from:c,$to:u})=>qy(r,{from:c.pos,to:u.pos},l)).join(o??` +`,textSerializers:o={}}=t||{},l="";return n.nodesBetween(r,s,(a,c,u,d)=>{var h;a.isBlock&&c>r&&(l+=i);let f=o?.[a.type.name];if(f)return u&&(l+=f({node:a,pos:c,parent:u,index:d,range:e})),!1;a.isText&&(l+=(h=a?.text)==null?void 0:h.slice(Math.max(r,c)-c,s-c))}),l}function YT(n,e){let t={from:0,to:n.content.size};return Gy(n,t,e)}function Xy(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function GT(n,e){let t=te(e,n.schema),{from:r,to:s}=n.selection,i=[];n.doc.nodesBetween(r,s,l=>{i.push(l)});let o=i.reverse().find(l=>l.type.name===t.name);return o?{...o.attrs}:{}}function Pd(n,e){let t=kl(typeof e=="string"?e:e.name,n.schema);return t==="node"?GT(n,e):t==="mark"?jy(n,e):{}}function XT(n,e=JSON.stringify){let t={};return n.filter(r=>{let s=e(r);return Object.prototype.hasOwnProperty.call(t,s)?!1:t[s]=!0})}function QT(n){let e=XT(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,o)=>o!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Ld(n){let{mapping:e,steps:t}=n,r=[];return e.maps.forEach((s,i)=>{let o=[];if(s.ranges.length)s.forEach((l,a)=>{o.push({from:l,to:a})});else{let{from:l,to:a}=t[i];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{let c=e.slice(i).map(l,-1),u=e.slice(i).map(a),d=e.invert().map(c,-1),h=e.invert().map(u);r.push({oldRange:{from:d,to:h},newRange:{from:c,to:u}})})}),QT(r)}function xl(n,e,t){let r=[];return n===e?t.resolve(n).marks().forEach(s=>{let i=t.resolve(n),o=Rd(i,s.type);o&&r.push({mark:s,...o})}):t.nodesBetween(n,e,(s,i)=>{!s||s?.nodeSize===void 0||r.push(...s.marks.map(o=>({from:i,to:i+s.nodeSize,mark:o})))}),r}var Qy=(n,e,t,r=20)=>{let s=n.doc.resolve(t),i=r,o=null;for(;i>0&&o===null;){let l=s.node(i);l?.type.name===e?o=l:i-=1}return[o,i]};function fi(n,e){return e.nodes[n]||e.marks[n]||null}function pl(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{let s=n.find(i=>i.type===e&&i.name===r);return s?s.attribute.keepOnSplit:!1}))}var ZT=(n,e=500)=>{let t="",r=n.parentOffset;return n.parent.nodesBetween(Math.max(0,r-e),r,(s,i,o,l)=>{var a,c;let u=((c=(a=s.type.spec).toText)==null?void 0:c.call(a,{node:s,pos:i,parent:o,index:l}))||s.textContent||"%leaf%";t+=s.isAtom&&!s.isText?u:u.slice(0,Math.max(0,r-i))}),t};function Ad(n,e,t={}){let{empty:r,ranges:s}=n.selection,i=e?an(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(d=>i?i.name===d.type.name:!0).find(d=>ml(d.attrs,t,{strict:!1}));let o=0,l=[];if(s.forEach(({$from:d,$to:h})=>{let f=d.pos,p=h.pos;n.doc.nodesBetween(f,p,(m,g)=>{if(i&&m.inlineContent&&!m.type.allowsMarkType(i))return!1;if(!m.isText&&!m.marks.length)return;let y=Math.max(f,g),w=Math.min(p,g+m.nodeSize),b=w-y;o+=b,l.push(...m.marks.map(v=>({mark:v,from:y,to:w})))})}),o===0)return!1;let a=l.filter(d=>i?i.name===d.mark.type.name:!0).filter(d=>ml(d.mark.attrs,t,{strict:!1})).reduce((d,h)=>d+h.to-h.from,0),c=l.filter(d=>i?d.mark.type!==i&&d.mark.type.excludes(i):!0).reduce((d,h)=>d+h.to-h.from,0);return(a>0?a+c:a)>=o}function eA(n,e,t={}){if(!e)return _t(n,null,t)||Ad(n,null,t);let r=kl(e,n.schema);return r==="node"?_t(n,e,t):r==="mark"?Ad(n,e,t):!1}var Zy=(n,e)=>{let{$from:t,$to:r,$anchor:s}=n.selection;if(e){let i=bl(l=>l.type.name===e)(n.selection);if(!i)return!1;let o=n.doc.resolve(i.pos+1);return s.pos+1===o.end()}return!(r.parentOffset{let{$from:e,$to:t}=n.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function By(n,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===n.name):e}function Sd(n,e){let{nodeExtensions:t}=Qr(e),r=t.find(o=>o.name===n);if(!r)return!1;let s={name:r.name,options:r.options,storage:r.storage},i=W(I(r,"group",s));return typeof i!="string"?!1:i.split(" ").includes("list")}function es(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){var r;if(t){if(n.type.name==="hardBreak")return!0;if(n.isText)return!/\S/.test((r=n.text)!=null?r:"")}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let s=!0;return n.content.forEach(i=>{s!==!1&&(es(i,{ignoreWhitespace:t,checkChildren:e})||(s=!1))}),s}return!1}function Sl(n){return n instanceof M}var vl=class tw{constructor(e){this.position=e}static fromJSON(e){return new tw(e.position)}toJSON(){return{position:this.position}}};function _d(n,e){let t=e.mapping.mapResult(n.position);return{position:new vl(t.pos),mapResult:t}}function tA(n){return new vl(n)}function nA(n,e,t){var r;let{selection:s}=e,i=null;if(Fy(s)&&(i=s.$cursor),i){let l=(r=n.storedMarks)!=null?r:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(c=>c.type.excludes(t)))}let{ranges:o}=s;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(u,d,h)=>{if(c)return!1;if(u.isInline){let f=!h||h.type.allowsMarkType(t),p=!!t.isInSet(u.marks)||!u.marks.some(m=>m.type.excludes(t));c=f&&p}return!c}),c})}var rA=(n,e={})=>({tr:t,state:r,dispatch:s})=>{let{selection:i}=t,{empty:o,ranges:l}=i,a=an(n,r.schema);if(s)if(o){let c=jy(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{let u=c.$from.pos,d=c.$to.pos;r.doc.nodesBetween(u,d,(h,f)=>{let p=Math.max(f,u),m=Math.min(f+h.nodeSize,d);h.marks.find(y=>y.type===a)?h.marks.forEach(y=>{a===y.type&&t.addMark(p,m,a.create({...y.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return nA(r,t,a)},sA=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),iA=(n,e={})=>({state:t,dispatch:r,chain:s})=>{let i=te(n,t.schema),o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),i.isTextblock?s().command(({commands:l})=>Fu(i,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Fu(i,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},oA=n=>({tr:e,dispatch:t})=>{if(t){let{doc:r}=e,s=sr(n,0,r.content.size),i=M.create(r,s);e.setSelection(i)}return!0},lA=(n,e)=>({tr:t,state:r,dispatch:s})=>{let{selection:i}=r,o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=i.from,l=i.to),s&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},aA=n=>({tr:e,dispatch:t})=>{if(t){let{doc:r}=e,{from:s,to:i}=typeof n=="number"?{from:n,to:n}:n,o=A.atStart(r).from,l=A.atEnd(r).to,a=sr(s,o,l),c=sr(i,o,l),u=A.create(r,a,c);e.setSelection(u)}return!0},cA=n=>({state:e,dispatch:t})=>{let r=te(n,e.schema);return gg(r)(e,t)};function zy(n,e){let t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){let r=t.filter(s=>e?.includes(s.type.name));n.tr.ensureMarks(r)}}var uA=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:s})=>{let{selection:i,doc:o}=e,{$from:l,$to:a}=i,c=s.extensionManager.attributes,u=pl(c,l.node().type.name,l.node().attrs);if(i instanceof M&&i.node.isBlock)return!l.parentOffset||!ot(o,l.pos)?!1:(r&&(n&&zy(t,s.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;let d=a.parentOffset===a.parent.content.size,h=l.depth===0?void 0:HT(l.node(-1).contentMatchAt(l.indexAfter(-1))),f=d&&h?[{type:h,attrs:u}]:void 0,p=ot(e.doc,e.mapping.map(l.pos),1,f);if(!f&&!p&&ot(e.doc,e.mapping.map(l.pos),1,h?[{type:h}]:void 0)&&(p=!0,f=h?[{type:h,attrs:u}]:void 0),r){if(p&&(i instanceof A&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,f),h&&!d&&!l.parentOffset&&l.parent.type!==h)){let m=e.mapping.map(l.before()),g=e.doc.resolve(m);l.node(-1).canReplaceWith(g.index(),g.index()+1,h)&&e.setNodeMarkup(e.mapping.map(l.before()),h)}n&&zy(t,s.extensionManager.splittableMarks),e.scrollIntoView()}return p},dA=(n,e={})=>({tr:t,state:r,dispatch:s,editor:i})=>{var o;let l=te(n,r.schema),{$from:a,$to:c}=r.selection,u=r.selection.node;if(u&&u.isBlock||a.depth<2||!a.sameParent(c))return!1;let d=a.node(-1);if(d.type!==l)return!1;let h=i.extensionManager.attributes;if(a.parent.content.size===0&&a.node(-1).childCount===a.indexAfter(-1)){if(a.depth===2||a.node(-3).type!==l||a.index(-2)!==a.node(-2).childCount-1)return!1;if(s){let y=k.empty,w=a.index(-1)?1:a.index(-2)?2:3;for(let _=a.depth-w;_>=a.depth-3;_-=1)y=k.from(a.node(_).copy(y));let b=a.indexAfter(-1){if(E>-1)return!1;_.isTextblock&&_.content.size===0&&(E=U+1)}),E>-1&&t.setSelection(A.near(t.doc.resolve(E))),t.scrollIntoView()}return!0}let f=c.pos===a.end()?d.contentMatchAt(0).defaultType:null,p={...pl(h,d.type.name,d.attrs),...e},m={...pl(h,a.node().type.name,a.node().attrs),...e};t.delete(a.pos,c.pos);let g=f?[{type:l,attrs:p},{type:f,attrs:m}]:[{type:l,attrs:p}];if(!ot(t.doc,a.pos,2))return!1;if(s){let{selection:y,storedMarks:w}=r,{splittableMarks:b}=i.extensionManager,v=w||y.$to.parentOffset&&y.$from.marks();if(t.split(a.pos,2,g).scrollIntoView(),!v||!s)return!0;let C=v.filter(R=>b.includes(R.type.name));t.ensureMarks(C)}return!0},vd=(n,e)=>{let t=bl(o=>o.type===e)(n.selection);if(!t)return!0;let r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;let s=n.doc.nodeAt(r);return t.node.type===s?.type&&ft(n.doc,t.pos)&&n.join(t.pos),!0},Cd=(n,e)=>{let t=bl(o=>o.type===e)(n.selection);if(!t)return!0;let r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;let s=n.doc.nodeAt(r);return t.node.type===s?.type&&ft(n.doc,r)&&n.join(r),!0};function hA(n){let e=n.doc,t=e.firstChild;if(!t)return null;let r=e.resolve(1),s=e.resolve(t.nodeSize-1);return A.between(r,s)}var fA=(n,e,t,r={})=>({editor:s,tr:i,state:o,dispatch:l,chain:a,commands:c,can:u})=>{let{extensions:d,splittableMarks:h}=s.extensionManager,f=te(n,o.schema),p=te(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:w}=m,b=y.blockRange(w),v=g||m.$to.parentOffset&&m.$from.marks();if(!b)return!1;let C=bl(ge=>Sd(ge.type.name,d))(m),R=m.from===0&&m.to===o.doc.content.size,E=o.doc.content.content,_=E.length===1?E[0]:null,U=R&&_&&Sd(_.type.name,d)?{node:_,pos:0,depth:0}:null,ae=C??U,ce=!!C&&b.depth>=1&&b.depth-C.depth<=1,xe=!!U;if((ce||xe)&&ae){if(ae.node.type===f)return R&&xe?a().command(({tr:ge,dispatch:Se})=>{let ie=hA(ge);return ie?(ge.setSelection(ie),Se&&Se(ge),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(Sd(ae.node.type.name,d)&&f.validContent(ae.node.content))return a().command(()=>(i.setNodeMarkup(ae.pos,f),!0)).command(()=>vd(i,f)).command(()=>Cd(i,f)).run()}return!t||!v||!l?a().command(()=>u().wrapInList(f,r)?!0:c.clearNodes()).wrapInList(f,r).command(()=>vd(i,f)).command(()=>Cd(i,f)).run():a().command(()=>{let ge=u().wrapInList(f,r),Se=v.filter(ie=>h.includes(ie.type.name));return i.ensureMarks(Se),ge?!0:c.clearNodes()}).wrapInList(f,r).command(()=>vd(i,f)).command(()=>Cd(i,f)).run()},pA=(n,e={},t={})=>({state:r,commands:s})=>{let{extendEmptyMarkRange:i=!1}=t,o=an(n,r.schema);return Ad(r,o,e)?s.unsetMark(o,{extendEmptyMarkRange:i}):s.setMark(o,e)},mA=(n,e,t={})=>({state:r,commands:s})=>{let i=te(n,r.schema),o=te(e,r.schema),l=_t(r,i,t),a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?s.setNode(o,a):s.setNode(i,{...a,...t})},gA=(n,e={})=>({state:t,commands:r})=>{let s=te(n,t.schema);return _t(t,s,e)?r.lift(s):r.wrapIn(s,e)},yA=()=>({state:n,dispatch:e})=>{let t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(i.text){let a=o.doc.resolve(i.from).marks();o.replaceWith(i.from,i.to,n.schema.text(i.text,a))}else o.delete(i.from,i.to)}return!0}}return!1},wA=(n={})=>({tr:e,dispatch:t,editor:r})=>{let{ignoreClearable:s=!1}=n,{selection:i}=e,{empty:o,ranges:l}=i;if(o)return!0;let{nonClearableMarks:a}=r.extensionManager;if(t){let c=Object.values(r.schema.marks).filter(u=>s||!a.includes(u.name));l.forEach(u=>{for(let d of c)e.removeMark(u.$from.pos,u.$to.pos,d)})}return!0},kA=(n,e={})=>({tr:t,state:r,dispatch:s})=>{var i;let{extendEmptyMarkRange:o=!1}=e,{selection:l}=t,a=an(n,r.schema),{$from:c,empty:u,ranges:d}=l;if(!s)return!0;if(u&&o){let{from:h,to:f}=l,p=(i=c.marks().find(g=>g.type===a))==null?void 0:i.attrs,m=Rd(c,a,p);m&&(h=m.from,f=m.to),t.removeMark(h,f,a)}else d.forEach(h=>{t.removeMark(h.$from.pos,h.$to.pos,a)});return t.removeStoredMark(a),!0},bA=n=>({tr:e,state:t,dispatch:r})=>{let{selection:s}=t,i,o;return typeof n=="number"?(i=n,o=n):n&&"from"in n&&"to"in n?(i=n.from,o=n.to):(i=s.from,o=s.to),r&&e.doc.nodesBetween(i,o,(l,a)=>{if(l.isText)return;let c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},xA=(n,e={})=>({tr:t,state:r,dispatch:s})=>{let i=null,o=null,l=kl(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(i=te(n,r.schema)),l==="mark"&&(o=an(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{let u=c.$from.pos,d=c.$to.pos,h,f,p,m;t.selection.empty?r.doc.nodesBetween(u,d,(g,y)=>{i&&i===g.type&&(a=!0,p=Math.max(y,u),m=Math.min(y+g.nodeSize,d),h=y,f=g)}):r.doc.nodesBetween(u,d,(g,y)=>{y=u&&y<=d&&(i&&i===g.type&&(a=!0,s&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(w=>{if(o===w.type&&(a=!0,s)){let b=Math.max(y,u),v=Math.min(y+g.nodeSize,d);t.addMark(b,v,o.create({...w.attrs,...e}))}}))}),f&&(h!==void 0&&s&&t.setNodeMarkup(h,void 0,{...f.attrs,...e}),o&&f.marks.length&&f.marks.forEach(g=>{o===g.type&&s&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},SA=(n,e={})=>({state:t,dispatch:r})=>{let s=te(n,t.schema);return fg(s,e)(t,r)},vA=(n,e={})=>({state:t,dispatch:r})=>{let s=te(n,t.schema);return pg(s,e)(t,r)},CA=class{constructor(){this.callbacks={}}on(n,e){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(e),this}emit(n,...e){let t=this.callbacks[n];return t&&t.forEach(r=>r.apply(this,e)),this}off(n,e){let t=this.callbacks[n];return t&&(e?this.callbacks[n]=t.filter(r=>r!==e):delete this.callbacks[n]),this}once(n,e){let t=(...r)=>{this.off(n,t),e.apply(this,r)};return this.on(n,t)}removeAllListeners(){this.callbacks={}}},Cl=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!=null?e:!0}},TA=(n,e)=>{if(Md(e))return e.exec(n);let t=e(n);if(!t)return null;let r=[t.text];return r.index=t.index,r.input=n,r.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(t.replaceWith)),r};function dl(n){var e;let{editor:t,from:r,to:s,text:i,rules:o,plugin:l}=n,{view:a}=t;if(a.composing)return!1;let c=a.state.doc.resolve(r);if(c.parent.type.spec.code||(e=c.nodeBefore||c.nodeAfter)!=null&&e.marks.find(h=>h.type.spec.code))return!1;let u=!1,d=ZT(c)+i;return o.forEach(h=>{if(u)return;let f=TA(d,h.find);if(!f)return;let p=a.state.tr,m=yl({state:a.state,transaction:p}),g={from:r-(f[0].length-i.length),to:s},{commands:y,chain:w,can:b}=new wl({editor:t,state:m});h.handler({state:m,range:g,match:f,commands:y,chain:w,can:b})===null||!p.steps.length||(h.undoable&&p.setMeta(l,{transform:p,from:r,to:s,text:i}),a.dispatch(p),u=!0)}),u}function AA(n){let{editor:e,rules:t}=n,r=new O({state:{init(){return null},apply(s,i,o){let l=s.getMeta(r);if(l)return l;let a=s.getMeta("applyInputRules");return a&&setTimeout(()=>{let{text:u}=a;typeof u=="string"?u=u:u=Od(k.from(u),o.schema);let{from:d}=a,h=d+u.length;dl({editor:e,from:d,to:h,text:u,rules:t,plugin:r})}),s.selectionSet||s.docChanged?null:i}},props:{handleTextInput(s,i,o,l){return dl({editor:e,from:i,to:o,text:l,rules:t,plugin:r})},handleDOMEvents:{compositionend:s=>(setTimeout(()=>{let{$cursor:i}=s.state.selection;i&&dl({editor:e,from:i.pos,to:i.pos,text:"",rules:t,plugin:r})}),!1)},handleKeyDown(s,i){if(i.key!=="Enter")return!1;let{$cursor:o}=s.state.selection;return o?dl({editor:e,from:o.pos,to:o.pos,text:` +`,rules:t,plugin:r}):!1}},isInputRules:!0});return r}function EA(n){return Object.prototype.toString.call(n).slice(8,-1)}function hl(n){return EA(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function nw(n,e){let t={...n};return hl(n)&&hl(e)&&Object.keys(e).forEach(r=>{hl(e[r])&&hl(n[r])?t[r]=nw(n[r],e[r]):t[r]=e[r]}),t}var Bd=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...W(I(this,"addOptions",{name:this.name}))}}get storage(){return{...W(I(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){let e=this.extend({...this.config,addOptions:()=>nw(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){let e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},lt=class rw extends Bd{constructor(){super(...arguments),this.type="mark"}static create(e={}){let t=typeof e=="function"?e():e;return new rw(t)}static handleExit({editor:e,mark:t}){let{tr:r}=e.state,s=e.state.selection.$from;if(s.pos===s.end()){let o=s.marks();if(!!!o.find(c=>c?.type.name===t.name))return!1;let a=o.find(c=>c?.type.name===t.name);return a&&r.removeStoredMark(a),r.insertText(" ",s.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){let t=typeof e=="function"?e():e;return super.extend(t)}};function MA(n){return typeof n=="number"}var RA=class{constructor(n){this.find=n.find,this.handler=n.handler}},NA=(n,e,t)=>{if(Md(e))return[...n.matchAll(e)];let r=e(n,t);return r?r.map(s=>{let i=[s.text];return i.index=s.index,i.input=n,i.data=s.data,s.replaceWith&&(s.text.includes(s.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),i.push(s.replaceWith)),i}):[]};function IA(n){let{editor:e,state:t,from:r,to:s,rule:i,pasteEvent:o,dropEvent:l}=n,{commands:a,chain:c,can:u}=new wl({editor:e,state:t}),d=[];return t.doc.nodesBetween(r,s,(f,p)=>{var m,g,y,w,b;if((g=(m=f.type)==null?void 0:m.spec)!=null&&g.code||!(f.isText||f.isTextblock||f.isInline))return;let v=(b=(w=(y=f.content)==null?void 0:y.size)!=null?w:f.nodeSize)!=null?b:0,C=Math.max(r,p),R=Math.min(s,p+v);if(C>=R)return;let E=f.isText?f.text||"":f.textBetween(C-p,R-p,void 0,"\uFFFC");NA(E,i.find,o).forEach(U=>{if(U.index===void 0)return;let ae=C+U.index+1,ce=ae+U[0].length,xe={from:t.tr.mapping.map(ae),to:t.tr.mapping.map(ce)},ge=i.handler({state:t,range:xe,match:U,commands:a,chain:c,can:u,pasteEvent:o,dropEvent:l});d.push(ge)})}),d.every(f=>f!==null)}var fl=null,DA=n=>{var e;let t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)==null||e.setData("text/html",n),t};function OA(n){let{editor:e,rules:t}=n,r=null,s=!1,i=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}let a=({state:u,from:d,to:h,rule:f,pasteEvt:p})=>{let m=u.tr,g=yl({state:u,transaction:m});if(!(!IA({editor:e,state:g,from:Math.max(d-1,0),to:h.b-1,rule:f,pasteEvent:p,dropEvent:l})||!m.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,m}};return t.map(u=>new O({view(d){let h=p=>{var m;r=(m=d.dom.parentElement)!=null&&m.contains(p.target)?d.dom.parentElement:null,r&&(fl=e)},f=()=>{fl&&(fl=null)};return window.addEventListener("dragstart",h),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",h),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(d,h)=>{if(i=r===d.dom.parentElement,l=h,!i){let f=fl;f?.isEditable&&setTimeout(()=>{let p=f.state.selection;p&&f.commands.deleteRange({from:p.from,to:p.to})},10)}return!1},paste:(d,h)=>{var f;let p=(f=h.clipboardData)==null?void 0:f.getData("text/html");return o=h,s=!!p?.includes("data-pm-slice"),!1}}},appendTransaction:(d,h,f)=>{let p=d[0],m=p.getMeta("uiEvent")==="paste"&&!s,g=p.getMeta("uiEvent")==="drop"&&!i,y=p.getMeta("applyPasteRules"),w=!!y;if(!m&&!g&&!w)return;if(w){let{text:C}=y;typeof C=="string"?C=C:C=Od(k.from(C),f.schema);let{from:R}=y,E=R+C.length,_=DA(C);return a({rule:u,state:f,from:R,to:{b:E},pasteEvt:_})}let b=h.doc.content.findDiffStart(f.doc.content),v=h.doc.content.findDiffEnd(f.doc.content);if(!(!MA(b)||!v||b===v.b))return a({rule:u,state:f,from:b,to:v,pasteEvt:o})}}))}var Tl=class{constructor(n,e){this.splittableMarks=[],this.nonClearableMarks=[],this.editor=e,this.baseExtensions=n,this.extensions=Yy(n),this.schema=JT(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((n,e)=>{let t={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:fi(e.name,this.schema)},r=I(e,"addCommands",t);return r?{...n,...r()}:n},{})}get plugins(){let{editor:n}=this;return mi([...this.extensions].reverse()).flatMap(r=>{let s={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:n,type:fi(r.name,this.schema)},i=[],o=I(r,"addKeyboardShortcuts",s),l={};if(r.type==="mark"&&I(r,"exitable",s)&&(l.ArrowRight=()=>lt.handleExit({editor:n,mark:r})),o){let h=Object.fromEntries(Object.entries(o()).map(([f,p])=>[f,()=>p({editor:n})]));l={...l,...h}}let a=My(l);i.push(a);let c=I(r,"addInputRules",s);if(By(r,n.options.enableInputRules)&&c){let h=c();if(h&&h.length){let f=AA({editor:n,rules:h}),p=Array.isArray(f)?f:[f];i.push(...p)}}let u=I(r,"addPasteRules",s);if(By(r,n.options.enablePasteRules)&&u){let h=u();if(h&&h.length){let f=OA({editor:n,rules:h});i.push(...f)}}let d=I(r,"addProseMirrorPlugins",s);if(d){let h=d();i.push(...h)}return i})}get attributes(){return Ky(this.extensions)}get nodeViews(){let{editor:n}=this,{nodeExtensions:e}=Qr(this.extensions);return Object.fromEntries(e.filter(t=>!!I(t,"addNodeView")).map(t=>{let r=this.attributes.filter(a=>a.type===t.name),s={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:te(t.name,this.schema)},i=I(t,"addNodeView",s);if(!i)return[];let o=i();if(!o)return[];let l=(a,c,u,d,h)=>{let f=Zr(a,r);return o({node:a,view:c,getPos:u,decorations:d,innerDecorations:h,editor:n,extension:t,HTMLAttributes:f})};return[t.name,l]}))}dispatchTransaction(n){let{editor:e}=this;return mi([...this.extensions].reverse()).reduceRight((r,s)=>{let i={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:e,type:fi(s.name,this.schema)},o=I(s,"dispatchTransaction",i);return o?l=>{o.call(i,{transaction:l,next:r})}:r},n)}transformPastedHTML(n){let{editor:e}=this;return mi([...this.extensions]).reduce((r,s)=>{let i={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:e,type:fi(s.name,this.schema)},o=I(s,"transformPastedHTML",i);return o?(l,a)=>{let c=r(l,a);return o.call(i,c)}:r},n||(r=>r))}get markViews(){let{editor:n}=this,{markExtensions:e}=Qr(this.extensions);return Object.fromEntries(e.filter(t=>!!I(t,"addMarkView")).map(t=>{let r=this.attributes.filter(l=>l.type===t.name),s={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:an(t.name,this.schema)},i=I(t,"addMarkView",s);if(!i)return[];let o=(l,a,c)=>{let u=Zr(l,r);return i()({mark:l,view:a,inline:c,editor:n,extension:t,HTMLAttributes:u,updateAttributes:d=>{HA(l,n,d)}})};return[t.name,o]}))}destroy(){this.extensions.forEach(n=>{let e=n;for(;e.parent;){let t=e.parent;t.child===e&&(t.child=null),e=t}}),this.extensions=[],this.baseExtensions=[],this.schema=null,this.editor=null}setupExtensions(){let n=this.extensions;this.editor.extensionStorage=Object.fromEntries(n.map(e=>[e.name,e.storage])),n.forEach(e=>{var t,r;let s={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:fi(e.name,this.schema)};e.type==="mark"&&(((t=W(I(e,"keepOnSplit",s)))==null||t)&&this.splittableMarks.push(e.name),(r=W(I(e,"clearable",s)))==null||r||this.nonClearableMarks.push(e.name));let i=I(e,"onBeforeCreate",s),o=I(e,"onCreate",s),l=I(e,"onUpdate",s),a=I(e,"onSelectionUpdate",s),c=I(e,"onTransaction",s),u=I(e,"onFocus",s),d=I(e,"onBlur",s),h=I(e,"onDestroy",s);i&&this.editor.on("beforeCreate",i),o&&this.editor.on("create",o),l&&this.editor.on("update",l),a&&this.editor.on("selectionUpdate",a),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),h&&this.editor.on("destroy",h)})}};Tl.resolve=Yy;Tl.sort=mi;Tl.flatten=Dd;var PA={};Ed(PA,{ClipboardTextSerializer:()=>iw,Commands:()=>ow,Delete:()=>lw,Drop:()=>aw,Editable:()=>cw,FocusEvents:()=>dw,Keymap:()=>hw,Paste:()=>fw,Tabindex:()=>pw,TextDirection:()=>mw,focusEventsPluginKey:()=>uw});var F=class sw extends Bd{constructor(){super(...arguments),this.type="extension"}static create(e={}){let t=typeof e=="function"?e():e;return new sw(t)}configure(e){return super.configure(e)}extend(e){let t=typeof e=="function"?e():e;return super.extend(t)}},iw=F.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new O({key:new P("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{let{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:s}=e,i=Xy(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:i};return[...s.ranges].sort((c,u)=>c.$from.pos-u.$from.pos).map(({$from:c,$to:u})=>Gy(r,{from:c.pos,to:u.pos},l)).join(o??` -`)}}})]}}),nw=F.create({name:"commands",addCommands(){return{...Ly}}}),rw=F.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r,s;let i=()=>{var o,l,a,c;if((c=(a=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:a.call(l,n))!=null?c:n.getMeta("y-sync$"))return;let u=Md(n.before,[n,...e]);Od(u).forEach(f=>{u.mapping.mapResult(f.oldRange.from).deletedAfter&&u.mapping.mapResult(f.oldRange.to).deletedBefore&&u.before.nodesBetween(f.oldRange.from,f.oldRange.to,(p,m)=>{let g=m+p.nodeSize-2,y=f.oldRange.from<=m&&g<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:p,from:m,to:g,newFrom:u.mapping.map(m),newTo:u.mapping.map(g),deletedRange:f.oldRange,newRange:f.newRange,partial:!y,editor:this.editor,transaction:n,combinedTransform:u})})});let h=u.mapping;u.steps.forEach((f,p)=>{var m,g;if(f instanceof Zt){let y=h.slice(p).map(f.from,-1),w=h.slice(p).map(f.to),b=h.invert().map(y,-1),v=h.invert().map(w),C=y>0?(m=u.doc.nodeAt(y-1))==null?void 0:m.marks.some(A=>A.eq(f.mark)):!1,R=(g=u.doc.nodeAt(w))==null?void 0:g.marks.some(A=>A.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:b,to:v},newRange:{from:y,to:w},partial:!!(R||C),editor:this.editor,transaction:n,combinedTransform:u})}})};(s=(r=(t=this.editor.options.coreExtensionOptions)==null?void 0:t.delete)==null?void 0:r.async)==null||s?setTimeout(i,0):i()}}),sw=F.create({name:"drop",addProseMirrorPlugins(){return[new O({key:new P("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),iw=F.create({name:"editable",addProseMirrorPlugins(){return[new O({key:new P("editable"),props:{editable:()=>this.editor.options.editable}})]}}),ow=new P("focusEvents"),lw=F.create({name:"focusEvents",addProseMirrorPlugins(){let{editor:n}=this;return[new O({key:ow,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;let r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;let r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),aw=F.create({name:"keymap",addKeyboardShortcuts(){let n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{let{selection:a,doc:c}=l,{empty:u,$anchor:d}=a,{pos:h,parent:f}=d,p=d.parent.isTextblock&&h>0?l.doc.resolve(h-1):d,m=p.parent.type.spec.isolating,g=d.pos-d.parentOffset,y=m&&p.parent.childCount===1?g===d.pos:I.atStart(c).from===h;return!u||!f.type.isTextblock||f.textContent.length||!y||y&&d.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},s={...r},i={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return ml()||Uy()?i:s},addProseMirrorPlugins(){return[new O({key:new P("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(m=>m.getMeta("composition")))return;let r=n.some(m=>m.docChanged)&&!e.doc.eq(t.doc),s=n.some(m=>m.getMeta("preventClearDocument"));if(!r||s)return;let{empty:i,from:o,to:l}=e.selection,a=I.atStart(e.doc).from,c=I.atEnd(e.doc).to;if(i||!(o===a&&l===c)||!es(t.doc))return;let h=t.tr,f=gl({state:t,transaction:h}),{commands:p}=new yl({editor:this.editor,state:f});if(p.clearNodes(),!!h.steps.length)return h}})]}}),cw=F.create({name:"paste",addProseMirrorPlugins(){return[new O({key:new P("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),uw=F.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new O({key:new P("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!=null?n:"0"}}}})]}}),dw=F.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];let{nodeExtensions:n}=Qr(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{let t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new O({key:new P("textDirection"),props:{attributes:()=>{let n=this.options.direction;return n?{dir:n}:{}}}})]}}),DA=class hi{constructor(e,t,r=!1,s=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=t,this.currentNode=s}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can\u2019t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:t,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;let e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new hi(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new hi(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new hi(e,this.editor)}get children(){let e=[];return this.node.content.forEach((t,r)=>{let s=t.isBlock&&!t.isTextblock,i=t.isAtom&&!t.isText,o=t.isInline,l=this.pos+r+(i?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;let a=this.resolvedPos.doc.resolve(l);if(!s&&!o&&a.depth<=this.depth)return;let c=new hi(a,this.editor,s,s||o?t:null);s&&(c.actualDepth=this.depth+1),e.push(c)}),e}get firstChild(){return this.children[0]||null}get lastChild(){let e=this.children;return e[e.length-1]||null}closest(e,t={}){let r=null,s=this.parent;for(;s&&!r;){if(s.node.type.name===e)if(Object.keys(t).length>0){let i=s.node.attrs,o=Object.keys(t);for(let l=0;l{r&&s.length>0||(o.node.type.name===e&&i.every(a=>t[a]===o.node.attrs[a])&&s.push(o),!(r&&s.length>0)&&(s=s.concat(o.querySelectorAll(e,t,r))))}),s}setAttribute(e){let{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}},OA=`.ProseMirror { +`)}}})]}}),ow=F.create({name:"commands",addCommands(){return{...$y}}}),lw=F.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r,s;let i=()=>{var o,l,a,c;if((c=(a=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:a.call(l,n))!=null?c:n.getMeta("y-sync$"))return;let u=Nd(n.before,[n,...e]);Ld(u).forEach(f=>{u.mapping.mapResult(f.oldRange.from).deletedAfter&&u.mapping.mapResult(f.oldRange.to).deletedBefore&&u.before.nodesBetween(f.oldRange.from,f.oldRange.to,(p,m)=>{let g=m+p.nodeSize-2,y=f.oldRange.from<=m&&g<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:p,from:m,to:g,newFrom:u.mapping.map(m),newTo:u.mapping.map(g),deletedRange:f.oldRange,newRange:f.newRange,partial:!y,editor:this.editor,transaction:n,combinedTransform:u})})});let h=u.mapping;u.steps.forEach((f,p)=>{var m,g;if(f instanceof Zt){let y=h.slice(p).map(f.from,-1),w=h.slice(p).map(f.to),b=h.invert().map(y,-1),v=h.invert().map(w),C=y>0?(m=u.doc.nodeAt(y-1))==null?void 0:m.marks.some(E=>E.eq(f.mark)):!1,R=(g=u.doc.nodeAt(w))==null?void 0:g.marks.some(E=>E.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:b,to:v},newRange:{from:y,to:w},partial:!!(R||C),editor:this.editor,transaction:n,combinedTransform:u})}})};(s=(r=(t=this.editor.options.coreExtensionOptions)==null?void 0:t.delete)==null?void 0:r.async)==null||s?setTimeout(i,0):i()}}),aw=F.create({name:"drop",addProseMirrorPlugins(){return[new O({key:new P("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),cw=F.create({name:"editable",addProseMirrorPlugins(){return[new O({key:new P("editable"),props:{editable:()=>this.editor.options.editable}})]}}),uw=new P("focusEvents"),dw=F.create({name:"focusEvents",addProseMirrorPlugins(){let{editor:n}=this;return[new O({key:uw,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;let r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;let r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),hw=F.create({name:"keymap",addKeyboardShortcuts(){let n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{let{selection:a,doc:c}=l,{empty:u,$anchor:d}=a,{pos:h,parent:f}=d,p=d.parent.isTextblock&&h>0?l.doc.resolve(h-1):d,m=p.parent.type.spec.isolating,g=d.pos-d.parentOffset,y=m&&p.parent.childCount===1?g===d.pos:N.atStart(c).from===h;return!u||!f.type.isTextblock||f.textContent.length||!y||y&&d.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},s={...r},i={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return gl()||Wy()?i:s},addProseMirrorPlugins(){return[new O({key:new P("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(m=>m.getMeta("composition")))return;let r=n.some(m=>m.docChanged)&&!e.doc.eq(t.doc),s=n.some(m=>m.getMeta("preventClearDocument"));if(!r||s)return;let{empty:i,from:o,to:l}=e.selection,a=N.atStart(e.doc).from,c=N.atEnd(e.doc).to;if(i||!(o===a&&l===c)||!es(t.doc))return;let h=t.tr,f=yl({state:t,transaction:h}),{commands:p}=new wl({editor:this.editor,state:f});if(p.clearNodes(),!!h.steps.length)return h}})]}}),fw=F.create({name:"paste",addProseMirrorPlugins(){return[new O({key:new P("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),pw=F.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new O({key:new P("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!=null?n:"0"}}}})]}}),mw=F.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];let{nodeExtensions:n}=Qr(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{let t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new O({key:new P("textDirection"),props:{attributes:()=>{let n=this.options.direction;return n?{dir:n}:{}}}})]}}),LA=class pi{constructor(e,t,r=!1,s=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=t,this.currentNode=s}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can\u2019t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:t,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;let e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new pi(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new pi(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new pi(e,this.editor)}get children(){let e=[];return this.node.content.forEach((t,r)=>{let s=t.isBlock&&!t.isTextblock,i=t.isAtom&&!t.isText,o=t.isInline,l=this.pos+r+(i?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;let a=this.resolvedPos.doc.resolve(l);if(!s&&!o&&a.depth<=this.depth)return;let c=new pi(a,this.editor,s,s||o?t:null);s&&(c.actualDepth=this.depth+1),e.push(c)}),e}get firstChild(){return this.children[0]||null}get lastChild(){let e=this.children;return e[e.length-1]||null}closest(e,t={}){let r=null,s=this.parent;for(;s&&!r;){if(s.node.type.name===e)if(Object.keys(t).length>0){let i=s.node.attrs,o=Object.keys(t);for(let l=0;l{r&&s.length>0||(o.node.type.name===e&&i.every(a=>t[a]===o.node.attrs[a])&&s.push(o),!(r&&s.length>0)&&(s=s.concat(o.querySelectorAll(e,t,r))))}),s}setAttribute(e){let{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}},_A=`.ProseMirror { position: relative; } @@ -82,85 +82,85 @@ img.ProseMirror-separator { .ProseMirror-focused .ProseMirror-gapcursor { display: block; -}`;function _d(n,e,t){let r=document.querySelector(`style[data-tiptap-style${t?`-${t}`:""}]`);if(r!==null)return r;let s=document.createElement("style");return e&&s.setAttribute("nonce",e),s.setAttribute(`data-tiptap-style${t?`-${t}`:""}`,""),s.innerHTML=n,document.getElementsByTagName("head")[0].appendChild(s),s}var hw=class extends xA{constructor(n={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:Pd,createMappablePosition:QT},this.setOptions(n),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:s,moved:i})=>this.options.onDrop(r,s,i)),this.on("paste",({event:r,slice:s})=>this.options.onPaste(r,s)),this.on("delete",this.options.onDelete);let e=this.createDoc(),t=zy(e,this.options.autofocus);this.editorState=Ko.create({doc:e,schema:this.schema,selection:t||void 0}),this.options.element&&this.mount(this.options.element)}mount(n){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(n),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){let n=this.editorView.dom;n?.editor&&delete n.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(n){console.warn("Failed to remove CSS element:",n)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=_d(OA,this.options.injectNonce))}setOptions(n={}){this.options={...this.options,...n},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(n,e=!0){this.setOptions({editable:n}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:n=>{this.editorState=n},dispatch:n=>{this.dispatchTransaction(n)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(n,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in n)return Reflect.get(n,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(n,e){let t=Hy(e)?e(n,[...this.state.plugins]):[...this.state.plugins,n],r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}unregisterPlugin(n){if(this.isDestroyed)return;let e=this.state.plugins,t=e;if([].concat(n).forEach(s=>{let i=typeof s=="string"?`${s}$`:s.key;t=t.filter(o=>!o.key.startsWith(i))}),e.length===t.length)return;let r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}createExtensionManager(){var n,e,t,r;let i=[...this.options.enableCoreExtensions?[iw,tw.configure({blockSeparator:(e=(n=this.options.coreExtensionOptions)==null?void 0:n.clipboardTextSerializer)==null?void 0:e.blockSeparator}),nw,lw,aw,uw.configure({value:(r=(t=this.options.coreExtensionOptions)==null?void 0:t.tabindex)==null?void 0:r.value}),sw,cw,rw,dw.configure({direction:this.options.textDirection})].filter(o=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[o.name]!==!1:!0):[],...this.options.extensions].filter(o=>["extension","node","mark"].includes(o?.type));this.extensionManager=new Cl(i,this)}createCommandManager(){this.commandManager=new yl({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let n;try{n=vd(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(t=>t.name!=="collaboration"),this.createExtensionManager()}}),n=vd(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return n}createView(n){let{editorProps:e,enableExtensionDispatchTransaction:t}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),s=t?this.extensionManager.dispatchTransaction(r):r,i=e.transformPastedHTML,o=this.extensionManager.transformPastedHTML(i);this.editorView=new li(n,{...e,attributes:{role:"textbox",...e?.attributes},dispatchTransaction:s,transformPastedHTML:o,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});let l=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(l),this.prependClass(),this.injectCSS();let a=this.view.dom;a.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(n){this.isCapturingTransaction=!0,n(),this.isCapturingTransaction=!1;let e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(n){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=n;return}n.steps.forEach(c=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(c)});return}let{state:e,transactions:t}=this.state.applyTransaction(n),r=!this.state.selection.eq(e.selection),s=t.includes(n),i=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:n,nextState:e}),!s)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:n,appendedTransactions:t.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:n});let o=t.findLast(c=>c.getMeta("focus")||c.getMeta("blur")),l=o?.getMeta("focus"),a=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),a&&this.emit("blur",{editor:this,event:a.event,transaction:o}),!(n.getMeta("preventUpdate")||!t.some(c=>c.docChanged)||i.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:n,appendedTransactions:t.slice(1)})}getAttributes(n){return Dd(this.state,n)}isActive(n,e){let t=typeof n=="string"?n:null,r=typeof n=="string"?e:n;return XT(this.state,t,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Id(this.state.doc.content,this.schema)}getText(n){let{blockSeparator:e=` +}`;function zd(n,e,t){let r=document.querySelector(`style[data-tiptap-style${t?`-${t}`:""}]`);if(r!==null)return r;let s=document.createElement("style");return e&&s.setAttribute("nonce",e),s.setAttribute(`data-tiptap-style${t?`-${t}`:""}`,""),s.innerHTML=n,document.getElementsByTagName("head")[0].appendChild(s),s}var gw=class extends CA{constructor(n={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:_d,createMappablePosition:tA},this.setOptions(n),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:s,moved:i})=>this.options.onDrop(r,s,i)),this.on("paste",({event:r,slice:s})=>this.options.onPaste(r,s)),this.on("delete",this.options.onDelete);let e=this.createDoc(),t=Vy(e,this.options.autofocus);this.editorState=Yo.create({doc:e,schema:this.schema,selection:t||void 0}),this.options.element&&this.mount(this.options.element)}mount(n){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(n),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){let n=this.editorView.dom;n?.editor&&delete n.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(n){console.warn("Failed to remove CSS element:",n)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=zd(_A,this.options.injectNonce))}setOptions(n={}){this.options={...this.options,...n},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(n,e=!0){this.setOptions({editable:n}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:n=>{this.editorState=n},dispatch:n=>{this.dispatchTransaction(n)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(n,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in n)return Reflect.get(n,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(n,e){let t=Jy(e)?e(n,[...this.state.plugins]):[...this.state.plugins,n],r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}unregisterPlugin(n){if(this.isDestroyed)return;let e=this.state.plugins,t=e;if([].concat(n).forEach(s=>{let i=typeof s=="string"?`${s}$`:s.key;t=t.filter(o=>!o.key.startsWith(i))}),e.length===t.length)return;let r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}createExtensionManager(){var n,e,t,r;let i=[...this.options.enableCoreExtensions?[cw,iw.configure({blockSeparator:(e=(n=this.options.coreExtensionOptions)==null?void 0:n.clipboardTextSerializer)==null?void 0:e.blockSeparator}),ow,dw,hw,pw.configure({value:(r=(t=this.options.coreExtensionOptions)==null?void 0:t.tabindex)==null?void 0:r.value}),aw,fw,lw,mw.configure({direction:this.options.textDirection})].filter(o=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[o.name]!==!1:!0):[],...this.options.extensions].filter(o=>["extension","node","mark"].includes(o?.type));this.extensionManager=new Tl(i,this)}createCommandManager(){this.commandManager=new wl({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let n;try{n=Td(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(t=>t.name!=="collaboration"),this.createExtensionManager()}}),n=Td(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return n}createView(n){let{editorProps:e,enableExtensionDispatchTransaction:t}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),s=t?this.extensionManager.dispatchTransaction(r):r,i=e.transformPastedHTML,o=this.extensionManager.transformPastedHTML(i);this.editorView=new li(n,{...e,attributes:{role:"textbox",...e?.attributes},dispatchTransaction:s,transformPastedHTML:o,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});let l=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(l),this.prependClass(),this.injectCSS();let a=this.view.dom;a.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(n){this.isCapturingTransaction=!0,n(),this.isCapturingTransaction=!1;let e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(n){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=n;return}n.steps.forEach(c=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(c)});return}let{state:e,transactions:t}=this.state.applyTransaction(n),r=!this.state.selection.eq(e.selection),s=t.includes(n),i=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:n,nextState:e}),!s)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:n,appendedTransactions:t.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:n});let o=t.findLast(c=>c.getMeta("focus")||c.getMeta("blur")),l=o?.getMeta("focus"),a=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),a&&this.emit("blur",{editor:this,event:a.event,transaction:o}),!(n.getMeta("preventUpdate")||!t.some(c=>c.docChanged)||i.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:n,appendedTransactions:t.slice(1)})}getAttributes(n){return Pd(this.state,n)}isActive(n,e){let t=typeof n=="string"?n:null,r=typeof n=="string"?e:n;return eA(this.state,t,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Od(this.state.doc.content,this.schema)}getText(n){let{blockSeparator:e=` -`,textSerializers:t={}}=n||{};return qT(this.state.doc,{blockSeparator:e,textSerializers:{...Jy(this.schema),...t}})}get isEmpty(){return es(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var n,e;return(e=(n=this.editorView)==null?void 0:n.isDestroyed)!=null?e:!0}$node(n,e){var t;return((t=this.$doc)==null?void 0:t.querySelector(n,e))||null}$nodes(n,e){var t;return((t=this.$doc)==null?void 0:t.querySelectorAll(n,e))||null}$pos(n){let e=this.state.doc.resolve(n),t=n>0&&e.nodeAfter&&!e.nodeAfter.isText?e.nodeAfter:null;return new DA(e,this,!1,t)}get $doc(){return this.$pos(0)}};function Bt(n){return new vl({find:n.find,handler:({state:e,range:t,match:r})=>{let s=W(n.getAttributes,void 0,r);if(s===!1||s===null)return null;let{tr:i}=e,o=r[r.length-1],l=r[0];if(o){let a=l.search(/\S/),c=t.from+l.indexOf(o),u=c+o.length;if(bl(t.from,t.to,e.doc).filter(f=>f.mark.type.excluded.find(m=>m===n.type&&m!==f.mark.type)).filter(f=>f.to>c).length)return null;ut.from&&i.delete(t.from+a,c);let h=t.from+a+o.length;i.addMark(t.from+a,h,n.type.create(s||{})),i.removeStoredMark(n.type)}},undoable:n.undoable})}function fw(n){return new vl({find:n.find,handler:({state:e,range:t,match:r})=>{let s=W(n.getAttributes,void 0,r)||{},{tr:i}=e,o=t.from,l=t.to,a=n.type.create(s);if(r[1]){let c=r[0].lastIndexOf(r[1]),u=o+c;u>l?u=l:l=u+r[1].length;let d=r[0][r[0].length-1];i.insertText(d,o+r[0].length-1),i.replaceWith(u,l,a)}else if(r[0]){let c=n.type.isInline?o:o-1;i.insert(c,n.type.create(s)).delete(i.mapping.map(o),i.mapping.map(l))}i.scrollIntoView()},undoable:n.undoable})}function mi(n){return new vl({find:n.find,handler:({state:e,range:t,match:r})=>{let s=e.doc.resolve(t.from),i=W(n.getAttributes,void 0,r)||{};if(!s.node(-1).canReplaceWith(s.index(-1),s.indexAfter(-1),n.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,n.type,i)},undoable:n.undoable})}function zt(n){return new vl({find:n.find,handler:({state:e,range:t,match:r,chain:s})=>{let i=W(n.getAttributes,void 0,r)||{},o=e.tr.delete(t.from,t.to),a=o.doc.resolve(t.from).blockRange(),c=a&&Fr(a,n.type,i);if(!c)return null;if(o.wrap(a,c),n.keepMarks&&n.editor){let{selection:d,storedMarks:h}=e,{splittableMarks:f}=n.editor.extensionManager,p=h||d.$to.parentOffset&&d.$from.marks();if(p){let m=p.filter(g=>f.includes(g.type.name));o.ensureMarks(m)}}if(n.keepAttributes){let d=n.type.name==="bulletList"||n.type.name==="orderedList"?"listItem":"taskList";s().updateAttributes(d,i).run()}let u=o.doc.resolve(t.from-1).nodeBefore;u&&u.type===n.type&&ft(o.doc,t.from-1)&&(!n.joinPredicate||n.joinPredicate(r,u))&&o.join(t.from-1)},undoable:n.undoable})}function pw(n,e){let{selection:t}=n,{$from:r}=t;if(t instanceof M){let i=r.index();return r.parent.canReplaceWith(i,i+1,e)}let s=r.depth;for(;s>=0;){let i=r.index(s);if(r.node(s).contentMatchAt(i).matchType(e))return!0;s-=1}return!1}var PA={};Td(PA,{createAtomBlockMarkdownSpec:()=>LA,createBlockMarkdownSpec:()=>_A,createInlineMarkdownSpec:()=>$A,parseAttributes:()=>Bd,parseIndentedBlocks:()=>Tl,renderNestedMarkdownContent:()=>gi,serializeAttributes:()=>zd});function Bd(n){if(!n?.trim())return{};let e={},t=[],r=n.replace(/["']([^"']*)["']/g,c=>(t.push(c),`__QUOTED_${t.length-1}__`)),s=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(s){let c=s.map(u=>u.trim().slice(1));e.class=c.join(" ")}let i=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);i&&(e.id=i[1]);let o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,c,u])=>{var d;let h=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),f=t[h];f&&(e[c]=f.slice(1,-1))});let a=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return a&&a.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function zd(n){if(!n||Object.keys(n).length===0)return"";let e=[];return n.class&&String(n.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),n.id&&e.push(`#${n.id}`),Object.entries(n).forEach(([t,r])=>{t==="class"||t==="id"||(r===!0?e.push(t):r!==!1&&r!=null&&e.push(`${t}="${String(r)}"`))}),e.join(" ")}function LA(n){let{nodeName:e,name:t,parseAttributes:r=Bd,serializeAttributes:s=zd,defaultAttributes:i={},requiredAttributes:o=[],allowedAttributes:l}=n,a=t||e,c=u=>{if(!l)return u;let d={};return l.forEach(h=>{h in u&&(d[h]=u[h])}),d};return{parseMarkdown:(u,d)=>{let h={...i,...u.attributes};return d.createNode(e,h,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;let h=new RegExp(`^:::${a}(?:\\s|$)`,"m"),f=(d=u.match(h))==null?void 0:d.index;return f!==void 0?f:-1},tokenize(u,d,h){let f=new RegExp(`^:::${a}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),p=u.match(f);if(!p)return;let m=p[1]||"",g=r(m);if(!o.find(w=>!(w in g)))return{type:e,raw:p[0],attributes:g}}},renderMarkdown:u=>{let d=c(u.attrs||{}),h=s(d),f=h?` {${h}}`:"";return`:::${a}${f} :::`}}}function _A(n){let{nodeName:e,name:t,getContent:r,parseAttributes:s=Bd,serializeAttributes:i=zd,defaultAttributes:o={},content:l="block",allowedAttributes:a}=n,c=t||e,u=d=>{if(!a)return d;let h={};return a.forEach(f=>{f in d&&(h[f]=d[f])}),h};return{parseMarkdown:(d,h)=>{let f;if(r){let m=r(d);f=typeof m=="string"?[{type:"text",text:m}]:m}else l==="block"?f=h.parseChildren(d.tokens||[]):f=h.parseInline(d.tokens||[]);let p={...o,...d.attributes};return h.createNode(e,p,f)},markdownTokenizer:{name:e,level:"block",start(d){var h;let f=new RegExp(`^:::${c}`,"m"),p=(h=d.match(f))==null?void 0:h.index;return p!==void 0?p:-1},tokenize(d,h,f){var p;let m=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),g=d.match(m);if(!g)return;let[y,w=""]=g,b=s(w),v=1,C=y.length,R="",A=/^:::([\w-]*)(\s.*)?/gm,_=d.slice(C);for(A.lastIndex=0;;){let U=A.exec(_);if(U===null)break;let ae=U.index,ce=U[1];if(!((p=U[2])!=null&&p.endsWith(":::"))){if(ce)v+=1;else if(v-=1,v===0){let xe=_.slice(0,ae);R=xe.trim();let ge=d.slice(0,C+ae+U[0].length),Se=[];if(R)if(l==="block")for(Se=f.blockTokens(xe),Se.forEach(ie=>{ie.text&&(!ie.tokens||ie.tokens.length===0)&&(ie.tokens=f.inlineTokens(ie.text))});Se.length>0;){let ie=Se[Se.length-1];if(ie.type==="paragraph"&&(!ie.text||ie.text.trim()===""))Se.pop();else break}else Se=f.inlineTokens(R);return{type:e,raw:ge,attributes:b,content:R,tokens:Se}}}}}},renderMarkdown:(d,h)=>{let f=u(d.attrs||{}),p=i(f),m=p?` {${p}}`:"",g=h.renderChildren(d.content||[],` +`,textSerializers:t={}}=n||{};return YT(this.state.doc,{blockSeparator:e,textSerializers:{...Xy(this.schema),...t}})}get isEmpty(){return es(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var n,e;return(e=(n=this.editorView)==null?void 0:n.isDestroyed)!=null?e:!0}$node(n,e){var t;return((t=this.$doc)==null?void 0:t.querySelector(n,e))||null}$nodes(n,e){var t;return((t=this.$doc)==null?void 0:t.querySelectorAll(n,e))||null}$pos(n){let e=this.state.doc.resolve(n),t=n>0&&e.nodeAfter&&!e.nodeAfter.isText?e.nodeAfter:null;return new LA(e,this,!1,t)}get $doc(){return this.$pos(0)}};function Bt(n){return new Cl({find:n.find,handler:({state:e,range:t,match:r})=>{let s=W(n.getAttributes,void 0,r);if(s===!1||s===null)return null;let{tr:i}=e,o=r[r.length-1],l=r[0];if(o){let a=l.search(/\S/),c=t.from+l.indexOf(o),u=c+o.length;if(xl(t.from,t.to,e.doc).filter(f=>f.mark.type.excluded.find(m=>m===n.type&&m!==f.mark.type)).filter(f=>f.to>c).length)return null;ut.from&&i.delete(t.from+a,c);let h=t.from+a+o.length;i.addMark(t.from+a,h,n.type.create(s||{})),i.removeStoredMark(n.type)}},undoable:n.undoable})}function yw(n){return new Cl({find:n.find,handler:({state:e,range:t,match:r})=>{let s=W(n.getAttributes,void 0,r)||{},{tr:i}=e,o=t.from,l=t.to,a=n.type.create(s);if(r[1]){let c=r[0].lastIndexOf(r[1]),u=o+c;u>l?u=l:l=u+r[1].length;let d=r[0][r[0].length-1];i.insertText(d,o+r[0].length-1),i.replaceWith(u,l,a)}else if(r[0]){let c=n.type.isInline?o:o-1;i.insert(c,n.type.create(s)).delete(i.mapping.map(o),i.mapping.map(l))}i.scrollIntoView()},undoable:n.undoable})}function yi(n){return new Cl({find:n.find,handler:({state:e,range:t,match:r})=>{let s=e.doc.resolve(t.from),i=W(n.getAttributes,void 0,r)||{};if(!s.node(-1).canReplaceWith(s.index(-1),s.indexAfter(-1),n.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,n.type,i)},undoable:n.undoable})}function zt(n){return new Cl({find:n.find,handler:({state:e,range:t,match:r,chain:s})=>{let i=W(n.getAttributes,void 0,r)||{},o=e.tr.delete(t.from,t.to),a=o.doc.resolve(t.from).blockRange(),c=a&&Vr(a,n.type,i);if(!c)return null;if(o.wrap(a,c),n.keepMarks&&n.editor){let{selection:d,storedMarks:h}=e,{splittableMarks:f}=n.editor.extensionManager,p=h||d.$to.parentOffset&&d.$from.marks();if(p){let m=p.filter(g=>f.includes(g.type.name));o.ensureMarks(m)}}if(n.keepAttributes){let d=n.type.name==="bulletList"||n.type.name==="orderedList"?"listItem":"taskList";s().updateAttributes(d,i).run()}let u=o.doc.resolve(t.from-1).nodeBefore;u&&u.type===n.type&&ft(o.doc,t.from-1)&&(!n.joinPredicate||n.joinPredicate(r,u))&&o.join(t.from-1)},undoable:n.undoable})}function ww(n,e){let{selection:t}=n,{$from:r}=t;if(t instanceof M){let i=r.index();return r.parent.canReplaceWith(i,i+1,e)}let s=r.depth;for(;s>=0;){let i=r.index(s);if(r.node(s).contentMatchAt(i).matchType(e))return!0;s-=1}return!1}var BA={};Ed(BA,{createAtomBlockMarkdownSpec:()=>zA,createBlockMarkdownSpec:()=>$A,createInlineMarkdownSpec:()=>VA,parseAttributes:()=>$d,parseIndentedBlocks:()=>Al,renderNestedMarkdownContent:()=>wi,serializeAttributes:()=>Ud});function $d(n){if(!n?.trim())return{};let e={},t=[],r=n.replace(/["']([^"']*)["']/g,c=>(t.push(c),`__QUOTED_${t.length-1}__`)),s=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(s){let c=s.map(u=>u.trim().slice(1));e.class=c.join(" ")}let i=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);i&&(e.id=i[1]);let o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,c,u])=>{var d;let h=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),f=t[h];f&&(e[c]=f.slice(1,-1))});let a=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return a&&a.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function Ud(n){if(!n||Object.keys(n).length===0)return"";let e=[];return n.class&&String(n.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),n.id&&e.push(`#${n.id}`),Object.entries(n).forEach(([t,r])=>{t==="class"||t==="id"||(r===!0?e.push(t):r!==!1&&r!=null&&e.push(`${t}="${String(r)}"`))}),e.join(" ")}function zA(n){let{nodeName:e,name:t,parseAttributes:r=$d,serializeAttributes:s=Ud,defaultAttributes:i={},requiredAttributes:o=[],allowedAttributes:l}=n,a=t||e,c=u=>{if(!l)return u;let d={};return l.forEach(h=>{h in u&&(d[h]=u[h])}),d};return{parseMarkdown:(u,d)=>{let h={...i,...u.attributes};return d.createNode(e,h,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;let h=new RegExp(`^:::${a}(?:\\s|$)`,"m"),f=(d=u.match(h))==null?void 0:d.index;return f!==void 0?f:-1},tokenize(u,d,h){let f=new RegExp(`^:::${a}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),p=u.match(f);if(!p)return;let m=p[1]||"",g=r(m);if(!o.find(w=>!(w in g)))return{type:e,raw:p[0],attributes:g}}},renderMarkdown:u=>{let d=c(u.attrs||{}),h=s(d),f=h?` {${h}}`:"";return`:::${a}${f} :::`}}}function $A(n){let{nodeName:e,name:t,getContent:r,parseAttributes:s=$d,serializeAttributes:i=Ud,defaultAttributes:o={},content:l="block",allowedAttributes:a}=n,c=t||e,u=d=>{if(!a)return d;let h={};return a.forEach(f=>{f in d&&(h[f]=d[f])}),h};return{parseMarkdown:(d,h)=>{let f;if(r){let m=r(d);f=typeof m=="string"?[{type:"text",text:m}]:m}else l==="block"?f=h.parseChildren(d.tokens||[]):f=h.parseInline(d.tokens||[]);let p={...o,...d.attributes};return h.createNode(e,p,f)},markdownTokenizer:{name:e,level:"block",start(d){var h;let f=new RegExp(`^:::${c}`,"m"),p=(h=d.match(f))==null?void 0:h.index;return p!==void 0?p:-1},tokenize(d,h,f){var p;let m=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),g=d.match(m);if(!g)return;let[y,w=""]=g,b=s(w),v=1,C=y.length,R="",E=/^:::([\w-]*)(\s.*)?/gm,_=d.slice(C);for(E.lastIndex=0;;){let U=E.exec(_);if(U===null)break;let ae=U.index,ce=U[1];if(!((p=U[2])!=null&&p.endsWith(":::"))){if(ce)v+=1;else if(v-=1,v===0){let xe=_.slice(0,ae);R=xe.trim();let ge=d.slice(0,C+ae+U[0].length),Se=[];if(R)if(l==="block")for(Se=f.blockTokens(xe),Se.forEach(ie=>{ie.text&&(!ie.tokens||ie.tokens.length===0)&&(ie.tokens=f.inlineTokens(ie.text))});Se.length>0;){let ie=Se[Se.length-1];if(ie.type==="paragraph"&&(!ie.text||ie.text.trim()===""))Se.pop();else break}else Se=f.inlineTokens(R);return{type:e,raw:ge,attributes:b,content:R,tokens:Se}}}}}},renderMarkdown:(d,h)=>{let f=u(d.attrs||{}),p=i(f),m=p?` {${p}}`:"",g=h.renderChildren(d.content||[],` `);return`:::${c}${m} ${g} -:::`}}}function BA(n){if(!n.trim())return{};let e={},t=/(\w+)=(?:"([^"]*)"|'([^']*)')/g,r=t.exec(n);for(;r!==null;){let[,s,i,o]=r;e[s]=i||o,r=t.exec(n)}return e}function zA(n){return Object.entries(n).filter(([,e])=>e!=null).map(([e,t])=>`${e}="${t}"`).join(" ")}function $A(n){let{nodeName:e,name:t,getContent:r,parseAttributes:s=BA,serializeAttributes:i=zA,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:a}=n,c=t||e,u=h=>{if(!a)return h;let f={};return a.forEach(p=>{let m=typeof p=="string"?p:p.name,g=typeof p=="string"?void 0:p.skipIfDefault;if(m in h){let y=h[m];if(g!==void 0&&y===g)return;f[m]=y}}),f},d=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,f)=>{let p={...o,...h.attributes};if(l)return f.createNode(e,p);let m=r?r(h):h.content||"";return m?f.createNode(e,p,[f.createTextNode(m)]):f.createNode(e,p,[])},markdownTokenizer:{name:e,level:"inline",start(h){let f=l?new RegExp(`\\[${d}\\s*[^\\]]*\\]`):new RegExp(`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),p=h.match(f),m=p?.index;return m!==void 0?m:-1},tokenize(h,f,p){let m=l?new RegExp(`^\\[${d}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),g=h.match(m);if(!g)return;let y="",w="";if(l){let[,v]=g;w=v}else{let[,v,C]=g;w=v,y=C||""}let b=s(w.trim());return{type:e,raw:g[0],content:y.trim(),attributes:b}}},renderMarkdown:h=>{let f="";r?f=r(h):h.content&&h.content.length>0&&(f=h.content.filter(y=>y.type==="text").map(y=>y.text).join(""));let p=u(h.attrs||{}),m=i(p),g=m?` ${m}`:"";return l?`[${c}${g}]`:`[${c}${g}]${f}[/${c}]`}}}function Tl(n,e,t){var r,s,i,o;let l=n.split(` +:::`}}}function UA(n){if(!n.trim())return{};let e={},t=/(\w+)=(?:"([^"]*)"|'([^']*)')/g,r=t.exec(n);for(;r!==null;){let[,s,i,o]=r;e[s]=i||o,r=t.exec(n)}return e}function FA(n){return Object.entries(n).filter(([,e])=>e!=null).map(([e,t])=>`${e}="${t}"`).join(" ")}function VA(n){let{nodeName:e,name:t,getContent:r,parseAttributes:s=UA,serializeAttributes:i=FA,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:a}=n,c=t||e,u=h=>{if(!a)return h;let f={};return a.forEach(p=>{let m=typeof p=="string"?p:p.name,g=typeof p=="string"?void 0:p.skipIfDefault;if(m in h){let y=h[m];if(g!==void 0&&y===g)return;f[m]=y}}),f},d=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,f)=>{let p={...o,...h.attributes};if(l)return f.createNode(e,p);let m=r?r(h):h.content||"";return m?f.createNode(e,p,[f.createTextNode(m)]):f.createNode(e,p,[])},markdownTokenizer:{name:e,level:"inline",start(h){let f=l?new RegExp(`\\[${d}\\s*[^\\]]*\\]`):new RegExp(`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),p=h.match(f),m=p?.index;return m!==void 0?m:-1},tokenize(h,f,p){let m=l?new RegExp(`^\\[${d}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),g=h.match(m);if(!g)return;let y="",w="";if(l){let[,v]=g;w=v}else{let[,v,C]=g;w=v,y=C||""}let b=s(w.trim());return{type:e,raw:g[0],content:y.trim(),attributes:b}}},renderMarkdown:h=>{let f="";r?f=r(h):h.content&&h.content.length>0&&(f=h.content.filter(y=>y.type==="text").map(y=>y.text).join(""));let p=u(h.attrs||{}),m=i(p),g=m?` ${m}`:"";return l?`[${c}${g}]`:`[${c}${g}]${f}[/${c}]`}}}function Al(n,e,t){var r,s,i,o;let l=n.split(` `),a=[],c="",u=0,d=e.baseIndentSize||2;for(;u0)break;if(h.trim()===""){u+=1,c=`${c}${h} `;continue}else return}let p=e.extractItemData(f),{indentLevel:m,mainContent:g}=p;c=`${c}${h} -`;let y=[g];for(u+=1;uae.trim()!=="");if(A===-1)break;if((((s=(r=l[u+1+A].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:s.length)||0)>m){y.push(C),c=`${c}${C} +`;let y=[g];for(u+=1;uae.trim()!=="");if(E===-1)break;if((((s=(r=l[u+1+E].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:s.length)||0)>m){y.push(C),c=`${c}${C} `,u+=1;continue}else break}if((((o=(i=C.match(/^(\s*)/))==null?void 0:i[1])==null?void 0:o.length)||0)>m)y.push(C),c=`${c}${C} `,u+=1;else break}let w,b=y.slice(1);if(b.length>0){let C=b.map(R=>R.slice(m+d)).join(` -`);C.trim()&&(e.customNestedParser?w=e.customNestedParser(C):w=t.blockTokens(C))}let v=e.createToken(p,w);a.push(v)}if(a.length!==0)return{items:a,raw:c}}function gi(n,e,t,r){if(!n||!Array.isArray(n.content))return"";let s=typeof t=="function"?t(r):t,[i,...o]=n.content,l=e.renderChildren([i]),a=`${s}${l}`;return o&&o.length>0&&o.forEach((c,u)=>{var d,h;let f=(h=(d=e.renderChild)==null?void 0:d.call(e,c,u+1))!=null?h:e.renderChildren([c]);if(f!=null){let p=f.split(` +`);C.trim()&&(e.customNestedParser?w=e.customNestedParser(C):w=t.blockTokens(C))}let v=e.createToken(p,w);a.push(v)}if(a.length!==0)return{items:a,raw:c}}function wi(n,e,t,r){if(!n||!Array.isArray(n.content))return"";let s=typeof t=="function"?t(r):t,[i,...o]=n.content,l=e.renderChildren([i]),a=`${s}${l}`;return o&&o.length>0&&o.forEach((c,u)=>{var d,h;let f=(h=(d=e.renderChild)==null?void 0:d.call(e,c,u+1))!=null?h:e.renderChildren([c]);if(f!=null){let p=f.split(` `).map(m=>m?e.indent(m):e.indent("")).join(` `);a+=c.type==="paragraph"?` ${p}`:` -${p}`}}),a}function UA(n,e,t={}){let{state:r}=e,{doc:s,tr:i}=r,o=n;s.descendants((l,a)=>{let c=i.mapping.map(a),u=i.mapping.map(a)+l.nodeSize,d=null;if(l.marks.forEach(f=>{if(f!==o)return!1;d=f}),!d)return;let h=!1;if(Object.keys(t).forEach(f=>{t[f]!==d.attrs[f]&&(h=!0)}),h){let f=n.type.create({...n.attrs,...t});i.removeMark(c,u,n.type),i.addMark(c,u,f)}}),i.docChanged&&e.view.dispatch(i)}var V=class mw extends Ld{constructor(){super(...arguments),this.type="node"}static create(e={}){let t=typeof e=="function"?e():e;return new mw(t)}configure(e){return super.configure(e)}extend(e){let t=typeof e=="function"?e():e;return super.extend(t)}};function wt(n){return new AA({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:s})=>{let i=W(n.getAttributes,void 0,r,s);if(i===!1||i===null)return null;let{tr:o}=e,l=r[r.length-1],a=r[0],c=t.to;if(l){let u=a.search(/\S/),d=t.from+a.indexOf(l),h=d+l.length;if(bl(t.from,t.to,e.doc).filter(m=>m.mark.type.excluded.find(y=>y===n.type&&y!==m.mark.type)).filter(m=>m.to>d).length)return null;ht.from&&o.delete(t.from+u,d),c=t.from+u+l.length,o.addMark(t.from+u,c,n.type.create(i||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var ts=(n,e)=>{if(n==="slot")return 0;if(n instanceof Function)return n(e);let{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[n,r,t]};function Aw(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let s=n.child(r),i=e.child(r);if(s==i){t+=s.nodeSize;continue}if(!s.sameMarkup(i))return t;if(s.isText&&s.text!=i.text){for(let o=0;s.text[o]==i.text[o];o++)t++;return t}if(s.content.size||i.content.size){let o=Aw(s.content,i.content,t+1);if(o!=null)return o}t+=s.nodeSize}}function Ew(n,e,t,r){for(let s=n.childCount,i=e.childCount;;){if(s==0||i==0)return s==i?null:{a:t,b:r};let o=n.child(--s),l=e.child(--i),a=o.nodeSize;if(o==l){t-=a,r-=a;continue}if(!o.sameMarkup(l))return{a:t,b:r};if(o.isText&&o.text!=l.text){let c=0,u=Math.min(o.text.length,l.text.length);for(;ce&&r(a,s+l,i||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,s+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,s){let i="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?s?typeof s=="function"?s(l):s:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:i+=r),i+=c},0),i}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,s=this.content.slice(),i=0;for(t.isText&&t.sameMarkup(r)&&(s[s.length-1]=t.withText(t.text+r.text),i=1);ie)for(let i=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),s+=l.nodeSize),o=a}return new Ke(r,s)}cutByIndex(e,t){return e==t?Ke.empty:e==0&&t==this.content.length?this:new Ke(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let s=this.content.slice(),i=this.size+t.nodeSize-r.nodeSize;return s[e]=t,new Ke(s,i)}addToStart(e){return new Ke([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Ke(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let s=this.child(t),i=r+s.nodeSize;if(i>=e)return i==e?Al(t+1,i):Al(t,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return Ke.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return Ke.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Ke.empty;let t,r=0;for(let s=0;sthis.type.rank&&(t||(t=e.slice(0,s)),t.push(this),r=!0),t&&t.push(i)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-s.type.rank),t}};ir.none=[];var Ol=class extends Error{},ne=class ns{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Rw(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new ns(r,this.openStart,this.openEnd)}removeBetween(e,t){return new ns(Mw(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return ns.empty;let r=t.openStart||0,s=t.openEnd||0;if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ns(Be.fromJSON(e,t.content),r,s)}static maxOpen(e,t=!0){let r=0,s=0;for(let i=e.firstChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=e.lastChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.lastChild)s++;return new ns(e,r,s)}};ne.empty=new ne(Be.empty,0,0);function Mw(n,e,t){let{index:r,offset:s}=n.findIndex(e),i=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(s==e||i.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,i.copy(Mw(i.content,e-s-1,t-s-1)))}function Rw(n,e,t,r,s,i){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return i&&r<=0&&s<=0&&!i.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Rw(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?s-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function FA(n,e,t){if(t.openStart>n.depth)throw new Ol("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new Ol("Inconsistent open depths");return Nw(n,e,t,0)}function Nw(n,e,t,r){let s=n.index(r),i=n.node(r);if(s==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function vi(n,e,t,r){let s=(e||n).node(t),i=0,o=e?e.index(t):s.childCount;n&&(i=n.index(t),n.depth>t?i++:n.textOffset&&(or(n.nodeAfter,r),i++));for(let l=i;ls&&Hd(n,e,s+1),o=r.depth>s&&Hd(t,r,s+1),l=[];return vi(null,n,s,l),i&&o&&e.index(s)==t.index(s)?(Iw(i,o),or(lr(i,Dw(n,e,t,r,s+1)),l)):(i&&or(lr(i,Pl(n,e,s+1)),l),vi(e,t,s,l),o&&or(lr(o,Pl(t,r,s+1)),l)),vi(r,null,s,l),new Be(l)}function Pl(n,e,t){let r=[];if(vi(null,n,t,r),n.depth>t){let s=Hd(n,e,t+1);or(lr(s,Pl(n,e,t+1)),r)}return vi(e,null,t,r),new Be(r)}function VA(n,e){let t=e.depth-n.openStart,s=e.node(t).copy(n.content);for(let i=t-1;i>=0;i--)s=e.node(i).copy(Be.from(s));return{start:s.resolveNoCache(n.openStart+t),end:s.resolveNoCache(s.content.size-n.openEnd-t)}}var gw=class Wd{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],s=e.child(t);return r?e.child(t).cut(r):s}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],s=t==0?0:this.path[t*3-1]+1;for(let i=0;i0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new jA(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],s=0,i=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(i),c=i-a;if(r.push(o,l,s+a),!c||(o=o.child(l),o.isText))break;i=c-1,s+=a+1}return new Wd(t,r,i)}static resolveCached(e,t){let r=yw.get(e);if(r)for(let i=0;ie&&this.nodesBetween(e,t,i=>(r.isInSet(i.marks)&&(s=!0),!s)),s}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),KA(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=Be.empty,s=0,i=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,s,i),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=s;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let s=Be.fromJSON(e,t.content),i=e.nodeType(t.type).create(t.attrs,s,r);return i.type.checkAttrs(i.attrs),i}};JA.prototype.text=void 0;function KA(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var qd=class Ow{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new YA(e,t);if(r.next==null)return Ow.empty;let s=Pw(r);r.next&&r.err("Unexpected trailing text");let i=nE(tE(s));return rE(i,r),i}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let s=0;s{let i=s+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return i}).join(` -`)}};qd.empty=new qd(!0);var YA=class{constructor(n,e){this.string=n,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=n.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(n){return this.next==n&&(this.pos++||!0)}err(n){throw new SyntaxError(n+" (in content expression '"+this.string+"')")}};function Pw(n){let e=[];do e.push(GA(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function GA(n){let e=[];do e.push(XA(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function XA(n){let e=eE(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=QA(n,e);else break;return e}function ww(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function QA(n,e){let t=ww(n),r=t;return n.eat(",")&&(n.next!="}"?r=ww(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function ZA(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let s=[];for(let i in t){let o=t[i];o.isInGroup(e)&&s.push(o)}return s.length==0&&n.err("No node type or group '"+e+"' found"),s}function eE(n){if(n.eat("(")){let e=Pw(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=ZA(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function tE(n){let e=[[]];return s(i(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function s(o,l){o.forEach(a=>a.to=l)}function i(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(i(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=i(o.exprs[a],l);if(a==o.exprs.length-1)return c;s(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),s(i(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return s(i(o.expr,l),a),s(i(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(i(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u{c||s.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let i=e[r.join(",")]=new qd(r.indexOf(n.length-1)>-1);for(let o=0;o0}get deletedBefore(){return(this.delInfo&(zw|Ml))>0}get deletedAfter(){return(this.delInfo&($w|Ml))>0}get deletedAcross(){return(this.delInfo&Ml)>0}},ar=class rs{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&rs.empty)return rs.empty}recover(e){let t=0,r=bw(e);if(!this.inverted)for(let s=0;se)break;let c=this.ranges[l+i],u=this.ranges[l+o],d=a+c;if(e<=d){let h=c?e==a?-1:e==d?1:t:t,f=a+s+(h<0?0:u);if(r)return f;let p=e==(t<0?a:d)?null:sE(l/3,e-a),m=e==a?$w:e==d?zw:Ml;return(t<0?e!=a:e!=d)&&(m|=Uw),new xw(f,m,p)}s+=u-c}return r?e+s:new xw(e+s,0,null)}touches(e,t){let r=0,s=bw(t),i=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+i],u=a+c;if(e<=u&&l==s*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let s=0,i=0;s!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),s),t.openStart,t.openEnd);return Ye.fromReplace(e,this.from,this.to,i)}invert(){return new Vw(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new wi(t.pos,r.pos,this.mark)}merge(e){return e instanceof wi&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new wi(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new wi(t.from,t.to,e.markFromJSON(t.mark))}};ze.jsonID("addMark",Fw);var Vw=class ki extends ze{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new ne(Gd(t.content,s=>s.mark(this.mark.removeFromSet(s.marks)),e),t.openStart,t.openEnd);return Ye.fromReplace(e,this.from,this.to,r)}invert(){return new Fw(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new ki(t.pos,r.pos,this.mark)}merge(e){return e instanceof ki&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ki(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ki(t.from,t.to,e.markFromJSON(t.mark))}};ze.jsonID("removeMark",Vw);var Hw=class bi extends ze{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ye.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Ye.fromReplace(e,this.pos,this.pos+1,new ne(Be.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let s=0;sr.pos?null:new Rl(t.pos,r.pos,s,i,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Rl(t.from,t.to,t.gapFrom,t.gapTo,ne.fromJSON(e,t.slice),t.insert,!!t.structure)}};ze.jsonID("replaceAround",jw);function Kd(n,e,t){let r=n.resolve(e),s=t-e,i=r.depth;for(;s>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,s--;if(s>0){let o=r.node(i).maybeChild(r.indexAfter(i));for(;s>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,s--}}return!1}var oE=class Nl extends ze{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ye.fail("No node at attribute step's position");let r=Object.create(null);for(let i in t.attrs)r[i]=t.attrs[i];r[this.attr]=this.value;let s=t.type.create(r,null,t.marks);return Ye.fromReplace(e,this.pos,this.pos+1,new ne(Be.from(s),0,t.isLeaf?0:1))}getMap(){return ar.empty}invert(e){return new Nl(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Nl(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Nl(t.pos,t.attr,t.value)}};ze.jsonID("attr",oE);var lE=class Yd extends ze{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let s in e.attrs)t[s]=e.attrs[s];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return Ye.ok(r)}getMap(){return ar.empty}invert(e){return new Yd(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Yd(t.attr,t.value)}};ze.jsonID("docAttr",lE);var Ti=class extends Error{};Ti=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Ti.prototype=Object.create(Error.prototype);Ti.prototype.constructor=Ti;Ti.prototype.name="TransformError";var Fd=Object.create(null),Ce=class{constructor(n,e,t){this.$anchor=n,this.$head=e,this.ranges=t||[new aE(n.min(e),n.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let n=this.ranges;for(let e=0;e=0;s--){let i=e<0?ss(n.node(0),n.node(s),n.before(s+1),n.index(s),e,t):ss(n.node(0),n.node(s),n.after(s+1),n.index(s)+1,e,t);if(i)return i}return null}static near(n,e=1){return this.findFrom(n,e)||this.findFrom(n,-e)||new Ci(n.node(0))}static atStart(n){return ss(n,n,0,0,1)||new Ci(n)}static atEnd(n){return ss(n,n,n.content.size,n.childCount,-1)||new Ci(n)}static fromJSON(n,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let t=Fd[e.type];if(!t)throw new RangeError(`No selection type ${e.type} defined`);return t.fromJSON(n,e)}static jsonID(n,e){if(n in Fd)throw new RangeError("Duplicate use of selection JSON ID "+n);return Fd[n]=e,e.prototype.jsonID=n,e}getBookmark(){return is.between(this.$anchor,this.$head).getBookmark()}};Ce.prototype.visible=!0;var aE=class{constructor(n,e){this.$from=n,this.$to=e}},Sw=!1;function vw(n){!Sw&&!n.parent.inlineContent&&(Sw=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var is=class xi extends Ce{constructor(e,t=e){vw(e),vw(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return Ce.near(r);let s=e.resolve(t.map(this.anchor));return new xi(s.parent.inlineContent?s:r,r)}replace(e,t=ne.empty){if(super.replace(e,t),t==ne.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof xi&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new qw(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new xi(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let s=e.resolve(t);return new this(s,r==t?s:e.resolve(r))}static between(e,t,r){let s=e.pos-t.pos;if((!r||s)&&(r=s>=0?1:-1),!t.parent.inlineContent){let i=Ce.findFrom(t,r,!0)||Ce.findFrom(t,-r,!0);if(i)t=i.$head;else return Ce.near(t,r)}return e.parent.inlineContent||(s==0?e=t:(e=(Ce.findFrom(e,-r,!0)||Ce.findFrom(e,r,!0)).$anchor,e.pos0?0:1);s>0?o=0;o+=s){let l=e.child(o);if(l.isAtom){if(!i&&ls.isSelectable(l))return ls.create(n,t-(s<0?l.nodeSize:0))}else{let a=ss(n,l,t+s,s<0?l.childCount:0,s,i);if(a)return a}t+=l.nodeSize*s}return null}function Cw(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=u)}),n.setSelection(Ce.near(n.doc.resolve(o),t))}function Tw(n,e){return!e||!n?n:n.bind(e)}var El=class{constructor(n,e,t){this.name=n,this.init=Tw(e.init,t),this.apply=Tw(e.apply,t)}},K_=[new El("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new El("selection",{init(n,e){return n.selection||Ce.atStart(e.doc)},apply(n){return n.selection}}),new El("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new El("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})],dE=(n,e)=>{var t;let{state:r,view:s}=n,{selection:i}=r;if(!i.empty)return!1;let{$from:o}=i;if(o.parentOffset!==0)return!1;let l=o.depth-1,a=o.node(l),c=o.index(l);if(c===0)return!1;if(a.type===e)return n.commands.lift(e.name);let u=a.child(c-1);if(u.type!==e||!((t=u.lastChild)!=null&&t.isTextblock))return!1;let d=o.before(),f=d-1-1,{tr:p}=r;return p.delete(d,o.after()).insert(f,o.parent.content),p.setSelection(is.create(p.doc,f)),s.dispatch(p.scrollIntoView()),!0},hE=/^\s*>\s$/,Yw=V.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:n}){return ts("blockquote",{...B(this.options.HTMLAttributes,n),children:ts("slot",{})})},parseMarkdown:(n,e)=>{var t;let r=(t=e.parseBlockChildren)!=null?t:e.parseChildren;return e.createNode("blockquote",void 0,r(n.tokens||[]))},renderMarkdown:(n,e)=>{if(!n.content)return"";let t=">",r=[];return n.content.forEach((s,i)=>{var o,l;let u=((l=(o=e.renderChild)==null?void 0:o.call(e,s,i))!=null?l:e.renderChildren([s])).split(` +${p}`}}),a}function HA(n,e,t={}){let{state:r}=e,{doc:s,tr:i}=r,o=n;s.descendants((l,a)=>{let c=i.mapping.map(a),u=i.mapping.map(a)+l.nodeSize,d=null;if(l.marks.forEach(f=>{if(f!==o)return!1;d=f}),!d)return;let h=!1;if(Object.keys(t).forEach(f=>{t[f]!==d.attrs[f]&&(h=!0)}),h){let f=n.type.create({...n.attrs,...t});i.removeMark(c,u,n.type),i.addMark(c,u,f)}}),i.docChanged&&e.view.dispatch(i)}var V=class kw extends Bd{constructor(){super(...arguments),this.type="node"}static create(e={}){let t=typeof e=="function"?e():e;return new kw(t)}configure(e){return super.configure(e)}extend(e){let t=typeof e=="function"?e():e;return super.extend(t)}};function wt(n){return new RA({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:s})=>{let i=W(n.getAttributes,void 0,r,s);if(i===!1||i===null)return null;let{tr:o}=e,l=r[r.length-1],a=r[0],c=t.to;if(l){let u=a.search(/\S/),d=t.from+a.indexOf(l),h=d+l.length;if(xl(t.from,t.to,e.doc).filter(m=>m.mark.type.excluded.find(y=>y===n.type&&y!==m.mark.type)).filter(m=>m.to>d).length)return null;ht.from&&o.delete(t.from+u,d),c=t.from+u+l.length,o.addMark(t.from+u,c,n.type.create(i||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}var ts=(n,e)=>{if(n==="slot")return 0;if(n instanceof Function)return n(e);let{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[n,r,t]};function Nw(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let s=n.child(r),i=e.child(r);if(s==i){t+=s.nodeSize;continue}if(!s.sameMarkup(i))return t;if(s.isText&&s.text!=i.text){for(let o=0;s.text[o]==i.text[o];o++)t++;return t}if(s.content.size||i.content.size){let o=Nw(s.content,i.content,t+1);if(o!=null)return o}t+=s.nodeSize}}function Iw(n,e,t,r){for(let s=n.childCount,i=e.childCount;;){if(s==0||i==0)return s==i?null:{a:t,b:r};let o=n.child(--s),l=e.child(--i),a=o.nodeSize;if(o==l){t-=a,r-=a;continue}if(!o.sameMarkup(l))return{a:t,b:r};if(o.isText&&o.text!=l.text){let c=0,u=Math.min(o.text.length,l.text.length);for(;ce&&r(a,s+l,i||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,s+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,s){let i="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?s?typeof s=="function"?s(l):s:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:i+=r),i+=c},0),i}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,s=this.content.slice(),i=0;for(t.isText&&t.sameMarkup(r)&&(s[s.length-1]=t.withText(t.text+r.text),i=1);ie)for(let i=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),s+=l.nodeSize),o=a}return new Ke(r,s)}cutByIndex(e,t){return e==t?Ke.empty:e==0&&t==this.content.length?this:new Ke(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let s=this.content.slice(),i=this.size+t.nodeSize-r.nodeSize;return s[e]=t,new Ke(s,i)}addToStart(e){return new Ke([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Ke(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let s=this.child(t),i=r+s.nodeSize;if(i>=e)return i==e?El(t+1,i):El(t,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return Ke.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return Ke.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Ke.empty;let t,r=0;for(let s=0;sthis.type.rank&&(t||(t=e.slice(0,s)),t.push(this),r=!0),t&&t.push(i)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-s.type.rank),t}};ir.none=[];var Pl=class extends Error{},ne=class ns{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Ow(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new ns(r,this.openStart,this.openEnd)}removeBetween(e,t){return new ns(Dw(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return ns.empty;let r=t.openStart||0,s=t.openEnd||0;if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ns(Be.fromJSON(e,t.content),r,s)}static maxOpen(e,t=!0){let r=0,s=0;for(let i=e.firstChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=e.lastChild;i&&!i.isLeaf&&(t||!i.type.spec.isolating);i=i.lastChild)s++;return new ns(e,r,s)}};ne.empty=new ne(Be.empty,0,0);function Dw(n,e,t){let{index:r,offset:s}=n.findIndex(e),i=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(s==e||i.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,i.copy(Dw(i.content,e-s-1,t-s-1)))}function Ow(n,e,t,r,s,i){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return i&&r<=0&&s<=0&&!i.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Ow(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?s-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function WA(n,e,t){if(t.openStart>n.depth)throw new Pl("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new Pl("Inconsistent open depths");return Pw(n,e,t,0)}function Pw(n,e,t,r){let s=n.index(r),i=n.node(r);if(s==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function Ti(n,e,t,r){let s=(e||n).node(t),i=0,o=e?e.index(t):s.childCount;n&&(i=n.index(t),n.depth>t?i++:n.textOffset&&(or(n.nodeAfter,r),i++));for(let l=i;ls&&jd(n,e,s+1),o=r.depth>s&&jd(t,r,s+1),l=[];return Ti(null,n,s,l),i&&o&&e.index(s)==t.index(s)?(Lw(i,o),or(lr(i,_w(n,e,t,r,s+1)),l)):(i&&or(lr(i,Ll(n,e,s+1)),l),Ti(e,t,s,l),o&&or(lr(o,Ll(t,r,s+1)),l)),Ti(r,null,s,l),new Be(l)}function Ll(n,e,t){let r=[];if(Ti(null,n,t,r),n.depth>t){let s=jd(n,e,t+1);or(lr(s,Ll(n,e,t+1)),r)}return Ti(e,null,t,r),new Be(r)}function jA(n,e){let t=e.depth-n.openStart,s=e.node(t).copy(n.content);for(let i=t-1;i>=0;i--)s=e.node(i).copy(Be.from(s));return{start:s.resolveNoCache(n.openStart+t),end:s.resolveNoCache(s.content.size-n.openEnd-t)}}var bw=class qd{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],s=e.child(t);return r?e.child(t).cut(r):s}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],s=t==0?0:this.path[t*3-1]+1;for(let i=0;i0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new KA(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],s=0,i=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(i),c=i-a;if(r.push(o,l,s+a),!c||(o=o.child(l),o.isText))break;i=c-1,s+=a+1}return new qd(t,r,i)}static resolveCached(e,t){let r=xw.get(e);if(r)for(let i=0;ie&&this.nodesBetween(e,t,i=>(r.isInSet(i.marks)&&(s=!0),!s)),s}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),XA(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=Be.empty,s=0,i=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,s,i),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=s;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let s=Be.fromJSON(e,t.content),i=e.nodeType(t.type).create(t.attrs,s,r);return i.type.checkAttrs(i.attrs),i}};GA.prototype.text=void 0;function XA(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}var Kd=class Bw{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new QA(e,t);if(r.next==null)return Bw.empty;let s=zw(r);r.next&&r.err("Unexpected trailing text");let i=iE(sE(s));return oE(i,r),i}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let s=0;s{let i=s+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return i}).join(` +`)}};Kd.empty=new Kd(!0);var QA=class{constructor(n,e){this.string=n,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=n.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(n){return this.next==n&&(this.pos++||!0)}err(n){throw new SyntaxError(n+" (in content expression '"+this.string+"')")}};function zw(n){let e=[];do e.push(ZA(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function ZA(n){let e=[];do e.push(eE(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function eE(n){let e=rE(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=tE(n,e);else break;return e}function Sw(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function tE(n,e){let t=Sw(n),r=t;return n.eat(",")&&(n.next!="}"?r=Sw(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function nE(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let s=[];for(let i in t){let o=t[i];o.isInGroup(e)&&s.push(o)}return s.length==0&&n.err("No node type or group '"+e+"' found"),s}function rE(n){if(n.eat("(")){let e=zw(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=nE(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function sE(n){let e=[[]];return s(i(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function s(o,l){o.forEach(a=>a.to=l)}function i(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(i(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=i(o.exprs[a],l);if(a==o.exprs.length-1)return c;s(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),s(i(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return s(i(o.expr,l),a),s(i(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(i(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u{c||s.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let i=e[r.join(",")]=new Kd(r.indexOf(n.length-1)>-1);for(let o=0;o0}get deletedBefore(){return(this.delInfo&(Vw|Rl))>0}get deletedAfter(){return(this.delInfo&(Hw|Rl))>0}get deletedAcross(){return(this.delInfo&Rl)>0}},ar=class rs{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&rs.empty)return rs.empty}recover(e){let t=0,r=Cw(e);if(!this.inverted)for(let s=0;se)break;let c=this.ranges[l+i],u=this.ranges[l+o],d=a+c;if(e<=d){let h=c?e==a?-1:e==d?1:t:t,f=a+s+(h<0?0:u);if(r)return f;let p=e==(t<0?a:d)?null:lE(l/3,e-a),m=e==a?Hw:e==d?Vw:Rl;return(t<0?e!=a:e!=d)&&(m|=Ww),new Tw(f,m,p)}s+=u-c}return r?e+s:new Tw(e+s,0,null)}touches(e,t){let r=0,s=Cw(t),i=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+i],u=a+c;if(e<=u&&l==s*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let s=0,i=0;s!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),s),t.openStart,t.openEnd);return Ye.fromReplace(e,this.from,this.to,i)}invert(){return new qw(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new bi(t.pos,r.pos,this.mark)}merge(e){return e instanceof bi&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new bi(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new bi(t.from,t.to,e.markFromJSON(t.mark))}};ze.jsonID("addMark",jw);var qw=class xi extends ze{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new ne(Qd(t.content,s=>s.mark(this.mark.removeFromSet(s.marks)),e),t.openStart,t.openEnd);return Ye.fromReplace(e,this.from,this.to,r)}invert(){return new jw(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new xi(t.pos,r.pos,this.mark)}merge(e){return e instanceof xi&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xi(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new xi(t.from,t.to,e.markFromJSON(t.mark))}};ze.jsonID("removeMark",qw);var Jw=class Si extends ze{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ye.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Ye.fromReplace(e,this.pos,this.pos+1,new ne(Be.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let s=0;sr.pos?null:new Nl(t.pos,r.pos,s,i,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Nl(t.from,t.to,t.gapFrom,t.gapTo,ne.fromJSON(e,t.slice),t.insert,!!t.structure)}};ze.jsonID("replaceAround",Yw);function Gd(n,e,t){let r=n.resolve(e),s=t-e,i=r.depth;for(;s>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,s--;if(s>0){let o=r.node(i).maybeChild(r.indexAfter(i));for(;s>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,s--}}return!1}var cE=class Il extends ze{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return Ye.fail("No node at attribute step's position");let r=Object.create(null);for(let i in t.attrs)r[i]=t.attrs[i];r[this.attr]=this.value;let s=t.type.create(r,null,t.marks);return Ye.fromReplace(e,this.pos,this.pos+1,new ne(Be.from(s),0,t.isLeaf?0:1))}getMap(){return ar.empty}invert(e){return new Il(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Il(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Il(t.pos,t.attr,t.value)}};ze.jsonID("attr",cE);var uE=class Xd extends ze{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let s in e.attrs)t[s]=e.attrs[s];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return Ye.ok(r)}getMap(){return ar.empty}invert(e){return new Xd(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Xd(t.attr,t.value)}};ze.jsonID("docAttr",uE);var Ei=class extends Error{};Ei=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Ei.prototype=Object.create(Error.prototype);Ei.prototype.constructor=Ei;Ei.prototype.name="TransformError";var Hd=Object.create(null),Te=class{constructor(n,e,t){this.$anchor=n,this.$head=e,this.ranges=t||[new dE(n.min(e),n.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let n=this.ranges;for(let e=0;e=0;s--){let i=e<0?ss(n.node(0),n.node(s),n.before(s+1),n.index(s),e,t):ss(n.node(0),n.node(s),n.after(s+1),n.index(s)+1,e,t);if(i)return i}return null}static near(n,e=1){return this.findFrom(n,e)||this.findFrom(n,-e)||new Ai(n.node(0))}static atStart(n){return ss(n,n,0,0,1)||new Ai(n)}static atEnd(n){return ss(n,n,n.content.size,n.childCount,-1)||new Ai(n)}static fromJSON(n,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let t=Hd[e.type];if(!t)throw new RangeError(`No selection type ${e.type} defined`);return t.fromJSON(n,e)}static jsonID(n,e){if(n in Hd)throw new RangeError("Duplicate use of selection JSON ID "+n);return Hd[n]=e,e.prototype.jsonID=n,e}getBookmark(){return is.between(this.$anchor,this.$head).getBookmark()}};Te.prototype.visible=!0;var dE=class{constructor(n,e){this.$from=n,this.$to=e}},Aw=!1;function Ew(n){!Aw&&!n.parent.inlineContent&&(Aw=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}var is=class vi extends Te{constructor(e,t=e){Ew(e),Ew(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return Te.near(r);let s=e.resolve(t.map(this.anchor));return new vi(s.parent.inlineContent?s:r,r)}replace(e,t=ne.empty){if(super.replace(e,t),t==ne.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof vi&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Gw(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new vi(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let s=e.resolve(t);return new this(s,r==t?s:e.resolve(r))}static between(e,t,r){let s=e.pos-t.pos;if((!r||s)&&(r=s>=0?1:-1),!t.parent.inlineContent){let i=Te.findFrom(t,r,!0)||Te.findFrom(t,-r,!0);if(i)t=i.$head;else return Te.near(t,r)}return e.parent.inlineContent||(s==0?e=t:(e=(Te.findFrom(e,-r,!0)||Te.findFrom(e,r,!0)).$anchor,e.pos0?0:1);s>0?o=0;o+=s){let l=e.child(o);if(l.isAtom){if(!i&&ls.isSelectable(l))return ls.create(n,t-(s<0?l.nodeSize:0))}else{let a=ss(n,l,t+s,s<0?l.childCount:0,s,i);if(a)return a}t+=l.nodeSize*s}return null}function Mw(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=u)}),n.setSelection(Te.near(n.doc.resolve(o),t))}function Rw(n,e){return!e||!n?n:n.bind(e)}var Ml=class{constructor(n,e,t){this.name=n,this.init=Rw(e.init,t),this.apply=Rw(e.apply,t)}},Q_=[new Ml("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Ml("selection",{init(n,e){return n.selection||Te.atStart(e.doc)},apply(n){return n.selection}}),new Ml("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Ml("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})],pE=(n,e)=>{var t;let{state:r,view:s}=n,{selection:i}=r;if(!i.empty)return!1;let{$from:o}=i;if(o.parentOffset!==0)return!1;let l=o.depth-1,a=o.node(l),c=o.index(l);if(c===0)return!1;if(a.type===e)return n.commands.lift(e.name);let u=a.child(c-1);if(u.type!==e||!((t=u.lastChild)!=null&&t.isTextblock))return!1;let d=o.before(),f=d-1-1,{tr:p}=r;return p.delete(d,o.after()).insert(f,o.parent.content),p.setSelection(is.create(p.doc,f)),s.dispatch(p.scrollIntoView()),!0},mE=/^\s*>\s$/,Zw=V.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:n}){return ts("blockquote",{...B(this.options.HTMLAttributes,n),children:ts("slot",{})})},parseMarkdown:(n,e)=>{var t;let r=(t=e.parseBlockChildren)!=null?t:e.parseChildren;return e.createNode("blockquote",void 0,r(n.tokens||[]))},renderMarkdown:(n,e)=>{if(!n.content)return"";let t=">",r=[];return n.content.forEach((s,i)=>{var o,l;let u=((l=(o=e.renderChild)==null?void 0:o.call(e,s,i))!=null?l:e.renderChildren([s])).split(` `).map(d=>d.trim()===""?t:`${t} ${d}`);r.push(u.join(` `))}),r.join(` ${t} -`)},addCommands(){return{setBlockquote:()=>({commands:n})=>n.wrapIn(this.name),toggleBlockquote:()=>({commands:n})=>n.toggleWrap(this.name),unsetBlockquote:()=>({commands:n})=>n.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>dE(this.editor,this.type)}},addInputRules(){return[zt({find:hE,type:this.type})]}});var fE=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,pE=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,mE=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,gE=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Gw=lt.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return ts("strong",{...B(this.options.HTMLAttributes,n),children:ts("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:fE,type:this.type}),Bt({find:mE,type:this.type})]},addPasteRules(){return[wt({find:pE,type:this.type}),wt({find:gE,type:this.type})]}});var yE=n=>{let e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},wE=n=>{let e=/`([^`]+)`(?!`)/g,t=[],r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t},Xw=lt.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:yE,type:this.type})]},addPasteRules(){return[wt({find:wE,type:this.type})]}});var Qd=4,kE=/^```([a-z]+)?[\s\n]$/,bE=/^~~~([a-z]+)?[\s\n]$/,Qw=V.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:Qd,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:n=>{var e;let{languageClassPrefix:t}=this.options;if(!t)return null;let i=[...((e=n.firstElementChild)==null?void 0:e.classList)||[]].filter(o=>o.startsWith(t)).map(o=>o.replace(t,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:n,HTMLAttributes:e}){return["pre",B(this.options.HTMLAttributes,e),["code",{class:n.attrs.language?this.options.languageClassPrefix+n.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(n,e)=>{var t,r;return((t=n.raw)==null?void 0:t.startsWith("```"))===!1&&((r=n.raw)==null?void 0:r.startsWith("~~~"))===!1&&n.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:n.lang||null},n.text?[e.createTextNode(n.text)]:[])},renderMarkdown:(n,e)=>{var t;let r="",s=((t=n.attrs)==null?void 0:t.language)||"";return n.content?r=[`\`\`\`${s}`,e.renderChildren(n.content),"```"].join(` +`)},addCommands(){return{setBlockquote:()=>({commands:n})=>n.wrapIn(this.name),toggleBlockquote:()=>({commands:n})=>n.toggleWrap(this.name),unsetBlockquote:()=>({commands:n})=>n.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>pE(this.editor,this.type)}},addInputRules(){return[zt({find:mE,type:this.type})]}});var gE=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,yE=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,wE=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,kE=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,e0=lt.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return ts("strong",{...B(this.options.HTMLAttributes,n),children:ts("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Bt({find:gE,type:this.type}),Bt({find:wE,type:this.type})]},addPasteRules(){return[wt({find:yE,type:this.type}),wt({find:kE,type:this.type})]}});var bE=n=>{let e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},xE=n=>{let e=/`([^`]+)`(?!`)/g,t=[],r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t},t0=lt.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Bt({find:bE,type:this.type})]},addPasteRules(){return[wt({find:xE,type:this.type})]}});var eh=4,SE=/^```([a-z]+)?[\s\n]$/,vE=/^~~~([a-z]+)?[\s\n]$/,n0=V.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:eh,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:n=>{var e;let{languageClassPrefix:t}=this.options;if(!t)return null;let i=[...((e=n.firstElementChild)==null?void 0:e.classList)||[]].filter(o=>o.startsWith(t)).map(o=>o.replace(t,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:n,HTMLAttributes:e}){return["pre",B(this.options.HTMLAttributes,e),["code",{class:n.attrs.language?this.options.languageClassPrefix+n.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(n,e)=>{var t,r;return((t=n.raw)==null?void 0:t.startsWith("```"))===!1&&((r=n.raw)==null?void 0:r.startsWith("~~~"))===!1&&n.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:n.lang||null},n.text?[e.createTextNode(n.text)]:[])},renderMarkdown:(n,e)=>{var t;let r="",s=((t=n.attrs)==null?void 0:t.language)||"";return n.content?r=[`\`\`\`${s}`,e.renderChildren(n.content),"```"].join(` `):r=`\`\`\`${s} -\`\`\``,r},addCommands(){return{setCodeBlock:n=>({commands:e})=>e.setNode(this.name,n),toggleCodeBlock:n=>({commands:e})=>e.toggleNode(this.name,"paragraph",n)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{let{empty:n,$anchor:e}=this.editor.state.selection,t=e.pos===1;return!n||e.parent.type.name!==this.name?!1:t||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;let t=(e=this.options.tabSize)!=null?e:Qd,{state:r}=n,{selection:s}=r,{$from:i,empty:o}=s;if(i.parent.type!==this.type)return!1;let l=" ".repeat(t);return o?n.commands.insertContent(l):n.commands.command(({tr:a})=>{let{from:c,to:u}=s,f=r.doc.textBetween(c,u,` +\`\`\``,r},addCommands(){return{setCodeBlock:n=>({commands:e})=>e.setNode(this.name,n),toggleCodeBlock:n=>({commands:e})=>e.toggleNode(this.name,"paragraph",n)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{let{empty:n,$anchor:e}=this.editor.state.selection,t=e.pos===1;return!n||e.parent.type.name!==this.name?!1:t||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;let t=(e=this.options.tabSize)!=null?e:eh,{state:r}=n,{selection:s}=r,{$from:i,empty:o}=s;if(i.parent.type!==this.type)return!1;let l=" ".repeat(t);return o?n.commands.insertContent(l):n.commands.command(({tr:a})=>{let{from:c,to:u}=s,f=r.doc.textBetween(c,u,` `,` `).split(` `).map(p=>l+p).join(` -`);return a.replaceWith(c,u,r.schema.text(f)),!0})},"Shift-Tab":({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;let t=(e=this.options.tabSize)!=null?e:Qd,{state:r}=n,{selection:s}=r,{$from:i,empty:o}=s;return i.parent.type!==this.type?!1:o?n.commands.command(({tr:l})=>{var a;let{pos:c}=i,u=i.start(),d=i.end(),f=r.doc.textBetween(u,d,` +`);return a.replaceWith(c,u,r.schema.text(f)),!0})},"Shift-Tab":({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;let t=(e=this.options.tabSize)!=null?e:eh,{state:r}=n,{selection:s}=r,{$from:i,empty:o}=s;return i.parent.type!==this.type?!1:o?n.commands.command(({tr:l})=>{var a;let{pos:c}=i,u=i.start(),d=i.end(),f=r.doc.textBetween(u,d,` `,` `).split(` -`),p=0,m=0,g=c-u;for(let R=0;R=g){p=R;break}m+=f[R].length+1}let w=((a=f[p].match(/^ */))==null?void 0:a[0])||"",b=Math.min(w.length,t);if(b===0)return!0;let v=u;for(let R=0;R{let{from:a,to:c}=s,h=r.doc.textBetween(a,c,` +`),p=0,m=0,g=c-u;for(let R=0;R=g){p=R;break}m+=f[R].length+1}let w=((a=f[p].match(/^ */))==null?void 0:a[0])||"",b=Math.min(w.length,t);if(b===0)return!0;let v=u;for(let R=0;R{let{from:a,to:c}=s,h=r.doc.textBetween(a,c,` `,` `).split(` `).map(f=>{var p;let m=((p=f.match(/^ */))==null?void 0:p[0])||"",g=Math.min(m.length,t);return f.slice(g)}).join(` `);return l.replaceWith(a,c,r.schema.text(h)),!0})},Enter:({editor:n})=>{if(!this.options.exitOnTripleEnter)return!1;let{state:e}=n,{selection:t}=e,{$from:r,empty:s}=t;if(!s||r.parent.type!==this.type)return!1;let i=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(` -`);return!i||!o?!1:n.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:n})=>{if(!this.options.exitOnArrowDown)return!1;let{state:e}=n,{selection:t,doc:r}=e,{$from:s,empty:i}=t;if(!i||s.parent.type!==this.type||!(s.parentOffset===s.parent.nodeSize-2))return!1;let l=s.after();return l===void 0?!1:r.nodeAt(l)?n.commands.command(({tr:c})=>(c.setSelection(I.near(r.resolve(l))),!0)):n.commands.exitCode()}}},addInputRules(){return[mi({find:kE,type:this.type,getAttributes:n=>({language:n[1]})}),mi({find:bE,type:this.type,getAttributes:n=>({language:n[1]})})]},addProseMirrorPlugins(){return[new O({key:new P("codeBlockVSCodeHandler"),props:{handlePaste:(n,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;let t=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,i=s?.mode;if(!t||!i)return!1;let{tr:o,schema:l}=n.state,a=l.text(t.replace(/\r\n?/g,` -`));return o.replaceSelectionWith(this.type.create({language:i},a)),o.selection.$from.parent.type!==this.type&&o.setSelection(E.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),n.dispatch(o),!0}}})]}});var Zw=V.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`);return!i||!o?!1:n.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:n})=>{if(!this.options.exitOnArrowDown)return!1;let{state:e}=n,{selection:t,doc:r}=e,{$from:s,empty:i}=t;if(!i||s.parent.type!==this.type||!(s.parentOffset===s.parent.nodeSize-2))return!1;let l=s.after();return l===void 0?!1:r.nodeAt(l)?n.commands.command(({tr:c})=>(c.setSelection(N.near(r.resolve(l))),!0)):n.commands.exitCode()}}},addInputRules(){return[yi({find:SE,type:this.type,getAttributes:n=>({language:n[1]})}),yi({find:vE,type:this.type,getAttributes:n=>({language:n[1]})})]},addProseMirrorPlugins(){return[new O({key:new P("codeBlockVSCodeHandler"),props:{handlePaste:(n,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;let t=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,i=s?.mode;if(!t||!i)return!1;let{tr:o,schema:l}=n.state,a=l.text(t.replace(/\r\n?/g,` +`));return o.replaceSelectionWith(this.type.create({language:i},a)),o.selection.$from.parent.type!==this.type&&o.setSelection(A.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),n.dispatch(o),!0}}})]}});var r0=V.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):""});var e0=V.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:n}){return["br",B(this.options.HTMLAttributes,n)]},renderText(){return` +`):""});var s0=V.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:n}){return["br",B(this.options.HTMLAttributes,n)]},renderText(){return` `},renderMarkdown:()=>` -`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:n,chain:e,state:t,editor:r})=>n.first([()=>n.exitCode(),()=>n.command(()=>{let{selection:s,storedMarks:i}=t;if(s.$from.parent.type.spec.isolating)return!1;let{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,a=i||s.$to.parentOffset&&s.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&a&&o){let d=a.filter(h=>l.includes(h.type.name));c.ensureMarks(d)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}});var t0=V.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(n=>({tag:`h${n}`,attrs:{level:n}}))},renderHTML({node:n,HTMLAttributes:e}){return[`h${this.options.levels.includes(n.attrs.level)?n.attrs.level:this.options.levels[0]}`,B(this.options.HTMLAttributes,e),0]},parseMarkdown:(n,e)=>e.createNode("heading",{level:n.depth||1},e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>{var t;let r=(t=n.attrs)!=null&&t.level?parseInt(n.attrs.level,10):1,s="#".repeat(r);return n.content?`${s} ${e.renderChildren(n.content)}`:""},addCommands(){return{setHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.setNode(this.name,n):!1,toggleHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.toggleNode(this.name,"paragraph",n):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((n,e)=>({...n,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(n=>mi({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${n}})\\s$`),type:this.type,getAttributes:{level:n}}))}});var n0=V.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:n}){return["hr",B(this.options.HTMLAttributes,n)]},markdownTokenName:"hr",parseMarkdown:(n,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:n,state:e})=>{if(!pw(e,e.schema.nodes[this.name]))return!1;let{selection:t}=e,{$to:r}=t,s=n();return xl(t)?s.insertContentAt(r.pos,{type:this.name}):s.insertContent({type:this.name}),s.command(({state:i,tr:o,dispatch:l})=>{if(l){let{$to:a}=o.selection,c=a.end();if(a.nodeAfter)a.nodeAfter.isTextblock?o.setSelection(E.create(o.doc,a.pos+1)):a.nodeAfter.isBlock?o.setSelection(M.create(o.doc,a.pos)):o.setSelection(E.create(o.doc,a.pos));else{let u=i.schema.nodes[this.options.nextNodeType]||a.parent.type.contentMatch.defaultType,d=u?.create();d&&(o.insert(c,d),o.setSelection(E.create(o.doc,c+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[fw({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}});var xE=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,SE=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,vE=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,CE=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,r0=lt.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",B(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:xE,type:this.type}),Bt({find:vE,type:this.type})]},addPasteRules(){return[wt({find:SE,type:this.type}),wt({find:CE,type:this.type})]}});var TE="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5m\xF6gensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",AE="\u03B5\u03BB1\u03C52\u0431\u04331\u0435\u043B3\u0434\u0435\u0442\u04384\u0435\u044E2\u043A\u0430\u0442\u043E\u043B\u0438\u043A6\u043E\u043C3\u043C\u043A\u04342\u043E\u043D1\u0441\u043A\u0432\u04306\u043E\u043D\u043B\u0430\u0439\u043D5\u0440\u04333\u0440\u0443\u04412\u04442\u0441\u0430\u0439\u04423\u0440\u04313\u0443\u043A\u04403\u049B\u0430\u04373\u0570\u0561\u05753\u05D9\u05E9\u05E8\u05D0\u05DC5\u05E7\u05D5\u05DD3\u0627\u0628\u0648\u0638\u0628\u064A5\u0631\u0627\u0645\u0643\u06485\u0644\u0627\u0631\u062F\u06464\u0628\u062D\u0631\u064A\u06465\u062C\u0632\u0627\u0626\u06315\u0633\u0639\u0648\u062F\u064A\u06296\u0639\u0644\u064A\u0627\u06465\u0645\u063A\u0631\u06285\u0645\u0627\u0631\u0627\u062A5\u06CC\u0631\u0627\u06465\u0628\u0627\u0631\u062A2\u0632\u0627\u06314\u064A\u062A\u06433\u06BE\u0627\u0631\u062A5\u062A\u0648\u0646\u06334\u0633\u0648\u062F\u0627\u06463\u0631\u064A\u06295\u0634\u0628\u0643\u06294\u0639\u0631\u0627\u06422\u06282\u0645\u0627\u06464\u0641\u0644\u0633\u0637\u064A\u06466\u0642\u0637\u06313\u0643\u0627\u062B\u0648\u0644\u064A\u06436\u0648\u06453\u0645\u0635\u06312\u0644\u064A\u0633\u064A\u06275\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u06277\u0642\u06394\u0647\u0645\u0631\u0627\u06475\u067E\u0627\u06A9\u0633\u062A\u0627\u06467\u0680\u0627\u0631\u062A4\u0915\u0949\u092E3\u0928\u0947\u091F3\u092D\u093E\u0930\u09240\u092E\u094D3\u094B\u09245\u0938\u0902\u0917\u0920\u09285\u09AC\u09BE\u0982\u09B2\u09BE5\u09AD\u09BE\u09B0\u09A42\u09F0\u09A44\u0A2D\u0A3E\u0A30\u0A244\u0AAD\u0ABE\u0AB0\u0AA44\u0B2D\u0B3E\u0B30\u0B244\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE6\u0BB2\u0B99\u0BCD\u0B95\u0BC86\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD11\u0C2D\u0C3E\u0C30\u0C24\u0C4D5\u0CAD\u0CBE\u0CB0\u0CA44\u0D2D\u0D3E\u0D30\u0D24\u0D025\u0DBD\u0D82\u0D9A\u0DCF4\u0E04\u0E2D\u0E213\u0E44\u0E17\u0E223\u0EA5\u0EB2\u0EA73\u10D2\u10D42\u307F\u3093\u306A3\u30A2\u30DE\u30BE\u30F34\u30AF\u30E9\u30A6\u30C94\u30B0\u30FC\u30B0\u30EB4\u30B3\u30E02\u30B9\u30C8\u30A23\u30BB\u30FC\u30EB3\u30D5\u30A1\u30C3\u30B7\u30E7\u30F36\u30DD\u30A4\u30F3\u30C84\u4E16\u754C2\u4E2D\u4FE11\u56FD1\u570B1\u6587\u7F513\u4E9A\u9A6C\u900A3\u4F01\u4E1A2\u4F5B\u5C712\u4FE1\u606F2\u5065\u5EB72\u516B\u53662\u516C\u53F81\u76CA2\u53F0\u6E7E1\u70632\u5546\u57CE1\u5E971\u68072\u5609\u91CC0\u5927\u9152\u5E975\u5728\u7EBF2\u5927\u62FF2\u5929\u4E3B\u65593\u5A31\u4E502\u5BB6\u96FB2\u5E7F\u4E1C2\u5FAE\u535A2\u6148\u55842\u6211\u7231\u4F603\u624B\u673A2\u62DB\u80582\u653F\u52A11\u5E9C2\u65B0\u52A0\u57612\u95FB2\u65F6\u5C1A2\u66F8\u7C4D2\u673A\u67842\u6DE1\u9A6C\u95213\u6E38\u620F2\u6FB3\u95802\u70B9\u770B2\u79FB\u52A82\u7EC4\u7EC7\u673A\u67844\u7F51\u57401\u5E971\u7AD91\u7EDC2\u8054\u901A2\u8C37\u6B4C2\u8D2D\u72692\u901A\u8CA92\u96C6\u56E22\u96FB\u8A0A\u76C8\u79D14\u98DE\u5229\u6D663\u98DF\u54C12\u9910\u53852\u9999\u683C\u91CC\u62C93\u6E2F2\uB2F7\uB1371\uCEF42\uC0BC\uC1312\uD55C\uAD6D2",ih="numeric",oh="ascii",lh="alpha",Mi="asciinumeric",Ei="alphanumeric",ah="domain",c0="emoji",EE="scheme",ME="slashscheme",Zd="whitespace";function RE(n,e){return n in e||(e[n]=[]),e[n]}function cr(n,e,t){e[ih]&&(e[Mi]=!0,e[Ei]=!0),e[oh]&&(e[Mi]=!0,e[lh]=!0),e[Mi]&&(e[Ei]=!0),e[lh]&&(e[Ei]=!0),e[Ei]&&(e[ah]=!0),e[c0]&&(e[ah]=!0);for(let r in e){let s=RE(r,t);s.indexOf(n)<0&&s.push(n)}}function NE(n,e){let t={};for(let r in e)e[r].indexOf(n)>=0&&(t[r]=!0);return t}function et(n=null){this.j={},this.jr=[],this.jd=null,this.t=n}et.groups={};et.prototype={accepts(){return!!this.t},go(n){let e=this,t=e.j[n];if(t)return t;for(let r=0;rn.ta(e,t,r,s),re=(n,e,t,r,s)=>n.tr(e,t,r,s),s0=(n,e,t,r,s)=>n.ts(e,t,r,s),x=(n,e,t,r,s)=>n.tt(e,t,r,s),un="WORD",ch="UWORD",u0="ASCIINUMERICAL",d0="ALPHANUMERICAL",Pi="LOCALHOST",uh="TLD",dh="UTLD",zl="SCHEME",as="SLASH_SCHEME",fh="NUM",hh="WS",ph="NL",Ri="OPENBRACE",Ni="CLOSEBRACE",$l="OPENBRACKET",Ul="CLOSEBRACKET",Fl="OPENPAREN",Vl="CLOSEPAREN",Hl="OPENANGLEBRACKET",Wl="CLOSEANGLEBRACKET",jl="FULLWIDTHLEFTPAREN",ql="FULLWIDTHRIGHTPAREN",Jl="LEFTCORNERBRACKET",Kl="RIGHTCORNERBRACKET",Yl="LEFTWHITECORNERBRACKET",Gl="RIGHTWHITECORNERBRACKET",Xl="FULLWIDTHLESSTHAN",Ql="FULLWIDTHGREATERTHAN",Zl="AMPERSAND",ea="APOSTROPHE",ta="ASTERISK",In="AT",na="BACKSLASH",ra="BACKTICK",sa="CARET",ur="COLON",mh="COMMA",ia="DOLLAR",$t="DOT",oa="EQUALS",gh="EXCLAMATION",bt="HYPHEN",Ii="PERCENT",la="PIPE",aa="PLUS",ca="POUND",Di="QUERY",yh="QUOTE",h0="FULLWIDTHMIDDLEDOT",wh="SEMI",Ut="SLASH",Oi="TILDE",ua="UNDERSCORE",f0="EMOJI",da="SYM",p0=Object.freeze({__proto__:null,ALPHANUMERICAL:d0,AMPERSAND:Zl,APOSTROPHE:ea,ASCIINUMERICAL:u0,ASTERISK:ta,AT:In,BACKSLASH:na,BACKTICK:ra,CARET:sa,CLOSEANGLEBRACKET:Wl,CLOSEBRACE:Ni,CLOSEBRACKET:Ul,CLOSEPAREN:Vl,COLON:ur,COMMA:mh,DOLLAR:ia,DOT:$t,EMOJI:f0,EQUALS:oa,EXCLAMATION:gh,FULLWIDTHGREATERTHAN:Ql,FULLWIDTHLEFTPAREN:jl,FULLWIDTHLESSTHAN:Xl,FULLWIDTHMIDDLEDOT:h0,FULLWIDTHRIGHTPAREN:ql,HYPHEN:bt,LEFTCORNERBRACKET:Jl,LEFTWHITECORNERBRACKET:Yl,LOCALHOST:Pi,NL:ph,NUM:fh,OPENANGLEBRACKET:Hl,OPENBRACE:Ri,OPENBRACKET:$l,OPENPAREN:Fl,PERCENT:Ii,PIPE:la,PLUS:aa,POUND:ca,QUERY:Di,QUOTE:yh,RIGHTCORNERBRACKET:Kl,RIGHTWHITECORNERBRACKET:Gl,SCHEME:zl,SEMI:wh,SLASH:Ut,SLASH_SCHEME:as,SYM:da,TILDE:Oi,TLD:uh,UNDERSCORE:ua,UTLD:dh,UWORD:ch,WORD:un,WS:hh}),an=/[a-z]/,Ai=/\p{L}/u,eh=/\p{Emoji}/u;var cn=/\d/,th=/\s/;var i0="\r",nh=` -`,IE="\uFE0F",DE="\u200D",rh="\uFFFC",Ll=null,_l=null;function OE(n=[]){let e={};et.groups=e;let t=new et;Ll==null&&(Ll=o0(TE)),_l==null&&(_l=o0(AE)),x(t,"'",ea),x(t,"{",Ri),x(t,"}",Ni),x(t,"[",$l),x(t,"]",Ul),x(t,"(",Fl),x(t,")",Vl),x(t,"<",Hl),x(t,">",Wl),x(t,"\uFF08",jl),x(t,"\uFF09",ql),x(t,"\u300C",Jl),x(t,"\u300D",Kl),x(t,"\u300E",Yl),x(t,"\u300F",Gl),x(t,"\uFF1C",Xl),x(t,"\uFF1E",Ql),x(t,"&",Zl),x(t,"*",ta),x(t,"@",In),x(t,"`",ra),x(t,"^",sa),x(t,":",ur),x(t,",",mh),x(t,"$",ia),x(t,".",$t),x(t,"=",oa),x(t,"!",gh),x(t,"-",bt),x(t,"%",Ii),x(t,"|",la),x(t,"+",aa),x(t,"#",ca),x(t,"?",Di),x(t,'"',yh),x(t,"/",Ut),x(t,";",wh),x(t,"~",Oi),x(t,"_",ua),x(t,"\\",na),x(t,"\u30FB",h0);let r=re(t,cn,fh,{[ih]:!0});re(r,cn,r);let s=re(r,an,u0,{[Mi]:!0}),i=re(r,Ai,d0,{[Ei]:!0}),o=re(t,an,un,{[oh]:!0});re(o,cn,s),re(o,an,o),re(s,cn,s),re(s,an,s);let l=re(t,Ai,ch,{[lh]:!0});re(l,an),re(l,cn,i),re(l,Ai,l),re(i,cn,i),re(i,an),re(i,Ai,i);let a=x(t,nh,ph,{[Zd]:!0}),c=x(t,i0,hh,{[Zd]:!0}),u=re(t,th,hh,{[Zd]:!0});x(t,rh,u),x(c,nh,a),x(c,rh,u),re(c,th,u),x(u,i0),x(u,nh),re(u,th,u),x(u,rh,u);let d=re(t,eh,f0,{[c0]:!0});x(d,"#"),re(d,eh,d),x(d,IE,d);let h=x(d,DE);x(h,"#"),re(h,eh,d);let f=[[an,o],[cn,s]],p=[[an,null],[Ai,l],[cn,i]];for(let m=0;mm[0]>g[0]?1:-1);for(let m=0;m=0?w[ah]=!0:an.test(g)?cn.test(g)?w[Mi]=!0:w[oh]=!0:w[ih]=!0,s0(t,g,g,w)}return s0(t,"localhost",Pi,{ascii:!0}),t.jd=new et(da),{start:t,tokens:Object.assign({groups:e},p0)}}function m0(n,e){let t=PE(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=t.length,s=[],i=0,o=0;for(;o=0&&(d+=t[o].length,h++),c+=t[o].length,i+=t[o].length,o++;i-=d,o-=h,c-=d,s.push({t:u.t,v:e.slice(i-c,i),s:i-c,e:i})}return s}function PE(n){let e=[],t=n.length,r=0;for(;r56319||r+1===t||(i=n.charCodeAt(r+1))<56320||i>57343?n[r]:n.slice(r,r+2);e.push(o),r+=o.length}return e}function Nn(n,e,t,r,s){let i,o=e.length;for(let l=0;l=0;)i++;if(i>0){e.push(t.join(""));for(let o=parseInt(n.substring(r,r+i),10);o>0;o--)t.pop();r+=i}else t.push(n[r]),r++}return e}var Li={defaultProtocol:"http",events:null,format:l0,formatHref:l0,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function kh(n,e=null){let t=Object.assign({},Li);n&&(t=Object.assign(t,n instanceof kh?n.o:n));let r=t.ignoreTags,s=[];for(let i=0;it?r.substring(0,t)+"\u2026":r},toFormattedHref(n){return n.get("formatHref",this.toHref(n.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(n=Li.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(n),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(n){return{type:this.t,value:this.toFormattedString(n),isLink:this.isLink,href:this.toFormattedHref(n),start:this.startIndex(),end:this.endIndex()}},validate(n){return n.get("validate",this.toString(),this)},render(n){let e=this,t=this.toHref(n.get("defaultProtocol")),r=n.get("formatHref",t,this),s=n.get("tagName",t,e),i=this.toFormattedString(n),o={},l=n.get("className",t,e),a=n.get("target",t,e),c=n.get("rel",t,e),u=n.getObj("attributes",t,e),d=n.getObj("events",t,e);return o.href=r,l&&(o.class=l),a&&(o.target=a),c&&(o.rel=c),u&&Object.assign(o,u),{tagName:s,attributes:o,content:i,eventListeners:d}}};function ha(n,e){class t extends g0{constructor(s,i){super(s,i),this.t=n}}for(let r in e)t.prototype[r]=e[r];return t.t=n,t}var LE=ha("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),a0=ha("text"),_E=ha("nl"),Bl=ha("url",{isLink:!0,toHref(n=Li.defaultProtocol){return this.hasProtocol()?this.v:`${n}://${this.v}`},hasProtocol(){let n=this.tk;return n.length>=2&&n[0].t!==Pi&&n[1].t===ur}});var kt=n=>new et(n);function BE({groups:n}){let e=n.domain.concat([Zl,ta,In,na,ra,sa,ia,oa,bt,fh,Ii,la,aa,ca,Ut,da,Oi,ua]),t=[ea,ur,mh,$t,gh,Ii,Di,yh,wh,Hl,Wl,Ri,Ni,Ul,$l,Fl,Vl,jl,ql,Jl,Kl,Yl,Gl,Xl,Ql],r=[Zl,ea,ta,na,ra,sa,ia,oa,bt,Ri,Ni,Ii,la,aa,ca,Di,Ut,da,Oi,ua],s=kt(),i=x(s,Oi);$(i,r,i),$(i,n.domain,i);let o=kt(),l=kt(),a=kt();$(s,n.domain,o),$(s,n.scheme,l),$(s,n.slashscheme,a),$(o,r,i),$(o,n.domain,o);let c=x(o,In);x(i,In,c),x(l,In,c),x(a,In,c);let u=x(i,$t);$(u,r,i),$(u,n.domain,i);let d=kt();$(c,n.domain,d),$(d,n.domain,d);let h=x(d,$t);$(h,n.domain,d);let f=kt(LE);$(h,n.tld,f),$(h,n.utld,f),x(c,Pi,f);let p=x(d,bt);x(p,bt,p),$(p,n.domain,d),$(f,n.domain,d),x(f,$t,h),x(f,bt,p);let m=x(o,bt),g=x(o,$t);x(m,bt,m),$(m,n.domain,o),$(g,r,i),$(g,n.domain,o);let y=kt(Bl);$(g,n.tld,y),$(g,n.utld,y),$(y,n.domain,o),$(y,r,i),x(y,$t,g),x(y,bt,m),x(y,In,c);let w=x(y,ur),b=kt(Bl);$(w,n.numeric,b);let v=kt(Bl),C=kt();$(v,e,v),$(v,t,C),$(C,e,v),$(C,t,C),x(y,Ut,v),x(b,Ut,v);let R=x(l,ur),A=x(a,ur),_=x(A,Ut),U=x(_,Ut);$(l,n.domain,o),x(l,$t,g),x(l,bt,m),$(a,n.domain,o),x(a,$t,g),x(a,bt,m),$(R,n.domain,v),x(R,Ut,v),x(R,Di,v),$(U,n.domain,v),$(U,e,v),x(U,Ut,v);let ae=[[Ri,Ni],[$l,Ul],[Fl,Vl],[Hl,Wl],[jl,ql],[Jl,Kl],[Yl,Gl],[Xl,Ql]];for(let ce=0;ce=0&&h++,s++,u++;if(h<0)s-=u,s0&&(i.push(sh(a0,e,o)),o=[]),s-=h,u-=h;let f=d.t,p=t.slice(s-u,s);i.push(sh(f,e,p))}}return o.length>0&&i.push(sh(a0,e,o)),i}function sh(n,e,t){let r=t[0].s,s=t[t.length-1].e,i=e.slice(r,s);return new n(i,t)}var $E=typeof console<"u"&&console&&console.warn||(()=>{}),UE="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Q={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function y0(){return et.groups={},Q.scanner=null,Q.parser=null,Q.tokenQueue=[],Q.pluginQueue=[],Q.customSchemes=[],Q.initialized=!1,Q}function bh(n,e=!1){if(Q.initialized&&$E(`linkifyjs: already initialized - will not register custom scheme "${n}" ${UE}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(n))throw new Error(`linkifyjs: incorrect scheme format. +`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:n,chain:e,state:t,editor:r})=>n.first([()=>n.exitCode(),()=>n.command(()=>{let{selection:s,storedMarks:i}=t;if(s.$from.parent.type.spec.isolating)return!1;let{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,a=i||s.$to.parentOffset&&s.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&a&&o){let d=a.filter(h=>l.includes(h.type.name));c.ensureMarks(d)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}});var i0=V.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(n=>({tag:`h${n}`,attrs:{level:n}}))},renderHTML({node:n,HTMLAttributes:e}){return[`h${this.options.levels.includes(n.attrs.level)?n.attrs.level:this.options.levels[0]}`,B(this.options.HTMLAttributes,e),0]},parseMarkdown:(n,e)=>e.createNode("heading",{level:n.depth||1},e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>{var t;let r=(t=n.attrs)!=null&&t.level?parseInt(n.attrs.level,10):1,s="#".repeat(r);return n.content?`${s} ${e.renderChildren(n.content)}`:""},addCommands(){return{setHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.setNode(this.name,n):!1,toggleHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.toggleNode(this.name,"paragraph",n):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((n,e)=>({...n,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(n=>yi({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${n}})\\s$`),type:this.type,getAttributes:{level:n}}))}});var o0=V.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:n}){return["hr",B(this.options.HTMLAttributes,n)]},markdownTokenName:"hr",parseMarkdown:(n,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:n,state:e})=>{if(!ww(e,e.schema.nodes[this.name]))return!1;let{selection:t}=e,{$to:r}=t,s=n();return Sl(t)?s.insertContentAt(r.pos,{type:this.name}):s.insertContent({type:this.name}),s.command(({state:i,tr:o,dispatch:l})=>{if(l){let{$to:a}=o.selection,c=a.end();if(a.nodeAfter)a.nodeAfter.isTextblock?o.setSelection(A.create(o.doc,a.pos+1)):a.nodeAfter.isBlock?o.setSelection(M.create(o.doc,a.pos)):o.setSelection(A.create(o.doc,a.pos));else{let u=i.schema.nodes[this.options.nextNodeType]||a.parent.type.contentMatch.defaultType,d=u?.create();d&&(o.insert(c,d),o.setSelection(A.create(o.doc,c+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[yw({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}});var CE=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,TE=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,AE=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,EE=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,l0=lt.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",B(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Bt({find:CE,type:this.type}),Bt({find:AE,type:this.type})]},addPasteRules(){return[wt({find:TE,type:this.type}),wt({find:EE,type:this.type})]}});var ME="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5m\xF6gensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",RE="\u03B5\u03BB1\u03C52\u0431\u04331\u0435\u043B3\u0434\u0435\u0442\u04384\u0435\u044E2\u043A\u0430\u0442\u043E\u043B\u0438\u043A6\u043E\u043C3\u043C\u043A\u04342\u043E\u043D1\u0441\u043A\u0432\u04306\u043E\u043D\u043B\u0430\u0439\u043D5\u0440\u04333\u0440\u0443\u04412\u04442\u0441\u0430\u0439\u04423\u0440\u04313\u0443\u043A\u04403\u049B\u0430\u04373\u0570\u0561\u05753\u05D9\u05E9\u05E8\u05D0\u05DC5\u05E7\u05D5\u05DD3\u0627\u0628\u0648\u0638\u0628\u064A5\u0631\u0627\u0645\u0643\u06485\u0644\u0627\u0631\u062F\u06464\u0628\u062D\u0631\u064A\u06465\u062C\u0632\u0627\u0626\u06315\u0633\u0639\u0648\u062F\u064A\u06296\u0639\u0644\u064A\u0627\u06465\u0645\u063A\u0631\u06285\u0645\u0627\u0631\u0627\u062A5\u06CC\u0631\u0627\u06465\u0628\u0627\u0631\u062A2\u0632\u0627\u06314\u064A\u062A\u06433\u06BE\u0627\u0631\u062A5\u062A\u0648\u0646\u06334\u0633\u0648\u062F\u0627\u06463\u0631\u064A\u06295\u0634\u0628\u0643\u06294\u0639\u0631\u0627\u06422\u06282\u0645\u0627\u06464\u0641\u0644\u0633\u0637\u064A\u06466\u0642\u0637\u06313\u0643\u0627\u062B\u0648\u0644\u064A\u06436\u0648\u06453\u0645\u0635\u06312\u0644\u064A\u0633\u064A\u06275\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u06277\u0642\u06394\u0647\u0645\u0631\u0627\u06475\u067E\u0627\u06A9\u0633\u062A\u0627\u06467\u0680\u0627\u0631\u062A4\u0915\u0949\u092E3\u0928\u0947\u091F3\u092D\u093E\u0930\u09240\u092E\u094D3\u094B\u09245\u0938\u0902\u0917\u0920\u09285\u09AC\u09BE\u0982\u09B2\u09BE5\u09AD\u09BE\u09B0\u09A42\u09F0\u09A44\u0A2D\u0A3E\u0A30\u0A244\u0AAD\u0ABE\u0AB0\u0AA44\u0B2D\u0B3E\u0B30\u0B244\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE6\u0BB2\u0B99\u0BCD\u0B95\u0BC86\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD11\u0C2D\u0C3E\u0C30\u0C24\u0C4D5\u0CAD\u0CBE\u0CB0\u0CA44\u0D2D\u0D3E\u0D30\u0D24\u0D025\u0DBD\u0D82\u0D9A\u0DCF4\u0E04\u0E2D\u0E213\u0E44\u0E17\u0E223\u0EA5\u0EB2\u0EA73\u10D2\u10D42\u307F\u3093\u306A3\u30A2\u30DE\u30BE\u30F34\u30AF\u30E9\u30A6\u30C94\u30B0\u30FC\u30B0\u30EB4\u30B3\u30E02\u30B9\u30C8\u30A23\u30BB\u30FC\u30EB3\u30D5\u30A1\u30C3\u30B7\u30E7\u30F36\u30DD\u30A4\u30F3\u30C84\u4E16\u754C2\u4E2D\u4FE11\u56FD1\u570B1\u6587\u7F513\u4E9A\u9A6C\u900A3\u4F01\u4E1A2\u4F5B\u5C712\u4FE1\u606F2\u5065\u5EB72\u516B\u53662\u516C\u53F81\u76CA2\u53F0\u6E7E1\u70632\u5546\u57CE1\u5E971\u68072\u5609\u91CC0\u5927\u9152\u5E975\u5728\u7EBF2\u5927\u62FF2\u5929\u4E3B\u65593\u5A31\u4E502\u5BB6\u96FB2\u5E7F\u4E1C2\u5FAE\u535A2\u6148\u55842\u6211\u7231\u4F603\u624B\u673A2\u62DB\u80582\u653F\u52A11\u5E9C2\u65B0\u52A0\u57612\u95FB2\u65F6\u5C1A2\u66F8\u7C4D2\u673A\u67842\u6DE1\u9A6C\u95213\u6E38\u620F2\u6FB3\u95802\u70B9\u770B2\u79FB\u52A82\u7EC4\u7EC7\u673A\u67844\u7F51\u57401\u5E971\u7AD91\u7EDC2\u8054\u901A2\u8C37\u6B4C2\u8D2D\u72692\u901A\u8CA92\u96C6\u56E22\u96FB\u8A0A\u76C8\u79D14\u98DE\u5229\u6D663\u98DF\u54C12\u9910\u53852\u9999\u683C\u91CC\u62C93\u6E2F2\uB2F7\uB1371\uCEF42\uC0BC\uC1312\uD55C\uAD6D2",lh="numeric",ah="ascii",ch="alpha",Ni="asciinumeric",Ri="alphanumeric",uh="domain",f0="emoji",NE="scheme",IE="slashscheme",th="whitespace";function DE(n,e){return n in e||(e[n]=[]),e[n]}function cr(n,e,t){e[lh]&&(e[Ni]=!0,e[Ri]=!0),e[ah]&&(e[Ni]=!0,e[ch]=!0),e[Ni]&&(e[Ri]=!0),e[ch]&&(e[Ri]=!0),e[Ri]&&(e[uh]=!0),e[f0]&&(e[uh]=!0);for(let r in e){let s=DE(r,t);s.indexOf(n)<0&&s.push(n)}}function OE(n,e){let t={};for(let r in e)e[r].indexOf(n)>=0&&(t[r]=!0);return t}function et(n=null){this.j={},this.jr=[],this.jd=null,this.t=n}et.groups={};et.prototype={accepts(){return!!this.t},go(n){let e=this,t=e.j[n];if(t)return t;for(let r=0;rn.ta(e,t,r,s),re=(n,e,t,r,s)=>n.tr(e,t,r,s),a0=(n,e,t,r,s)=>n.ts(e,t,r,s),x=(n,e,t,r,s)=>n.tt(e,t,r,s),dn="WORD",dh="UWORD",p0="ASCIINUMERICAL",m0="ALPHANUMERICAL",_i="LOCALHOST",hh="TLD",fh="UTLD",$l="SCHEME",as="SLASH_SCHEME",mh="NUM",ph="WS",gh="NL",Ii="OPENBRACE",Di="CLOSEBRACE",Ul="OPENBRACKET",Fl="CLOSEBRACKET",Vl="OPENPAREN",Hl="CLOSEPAREN",Wl="OPENANGLEBRACKET",jl="CLOSEANGLEBRACKET",ql="FULLWIDTHLEFTPAREN",Jl="FULLWIDTHRIGHTPAREN",Kl="LEFTCORNERBRACKET",Yl="RIGHTCORNERBRACKET",Gl="LEFTWHITECORNERBRACKET",Xl="RIGHTWHITECORNERBRACKET",Ql="FULLWIDTHLESSTHAN",Zl="FULLWIDTHGREATERTHAN",ea="AMPERSAND",ta="APOSTROPHE",na="ASTERISK",In="AT",ra="BACKSLASH",sa="BACKTICK",ia="CARET",ur="COLON",yh="COMMA",oa="DOLLAR",$t="DOT",la="EQUALS",wh="EXCLAMATION",bt="HYPHEN",Oi="PERCENT",aa="PIPE",ca="PLUS",ua="POUND",Pi="QUERY",kh="QUOTE",g0="FULLWIDTHMIDDLEDOT",bh="SEMI",Ut="SLASH",Li="TILDE",da="UNDERSCORE",y0="EMOJI",ha="SYM",w0=Object.freeze({__proto__:null,ALPHANUMERICAL:m0,AMPERSAND:ea,APOSTROPHE:ta,ASCIINUMERICAL:p0,ASTERISK:na,AT:In,BACKSLASH:ra,BACKTICK:sa,CARET:ia,CLOSEANGLEBRACKET:jl,CLOSEBRACE:Di,CLOSEBRACKET:Fl,CLOSEPAREN:Hl,COLON:ur,COMMA:yh,DOLLAR:oa,DOT:$t,EMOJI:y0,EQUALS:la,EXCLAMATION:wh,FULLWIDTHGREATERTHAN:Zl,FULLWIDTHLEFTPAREN:ql,FULLWIDTHLESSTHAN:Ql,FULLWIDTHMIDDLEDOT:g0,FULLWIDTHRIGHTPAREN:Jl,HYPHEN:bt,LEFTCORNERBRACKET:Kl,LEFTWHITECORNERBRACKET:Gl,LOCALHOST:_i,NL:gh,NUM:mh,OPENANGLEBRACKET:Wl,OPENBRACE:Ii,OPENBRACKET:Ul,OPENPAREN:Vl,PERCENT:Oi,PIPE:aa,PLUS:ca,POUND:ua,QUERY:Pi,QUOTE:kh,RIGHTCORNERBRACKET:Yl,RIGHTWHITECORNERBRACKET:Xl,SCHEME:$l,SEMI:bh,SLASH:Ut,SLASH_SCHEME:as,SYM:ha,TILDE:Li,TLD:hh,UNDERSCORE:da,UTLD:fh,UWORD:dh,WORD:dn,WS:ph}),cn=/[a-z]/,Mi=/\p{L}/u,nh=/\p{Emoji}/u;var un=/\d/,rh=/\s/;var c0="\r",sh=` +`,PE="\uFE0F",LE="\u200D",ih="\uFFFC",_l=null,Bl=null;function _E(n=[]){let e={};et.groups=e;let t=new et;_l==null&&(_l=u0(ME)),Bl==null&&(Bl=u0(RE)),x(t,"'",ta),x(t,"{",Ii),x(t,"}",Di),x(t,"[",Ul),x(t,"]",Fl),x(t,"(",Vl),x(t,")",Hl),x(t,"<",Wl),x(t,">",jl),x(t,"\uFF08",ql),x(t,"\uFF09",Jl),x(t,"\u300C",Kl),x(t,"\u300D",Yl),x(t,"\u300E",Gl),x(t,"\u300F",Xl),x(t,"\uFF1C",Ql),x(t,"\uFF1E",Zl),x(t,"&",ea),x(t,"*",na),x(t,"@",In),x(t,"`",sa),x(t,"^",ia),x(t,":",ur),x(t,",",yh),x(t,"$",oa),x(t,".",$t),x(t,"=",la),x(t,"!",wh),x(t,"-",bt),x(t,"%",Oi),x(t,"|",aa),x(t,"+",ca),x(t,"#",ua),x(t,"?",Pi),x(t,'"',kh),x(t,"/",Ut),x(t,";",bh),x(t,"~",Li),x(t,"_",da),x(t,"\\",ra),x(t,"\u30FB",g0);let r=re(t,un,mh,{[lh]:!0});re(r,un,r);let s=re(r,cn,p0,{[Ni]:!0}),i=re(r,Mi,m0,{[Ri]:!0}),o=re(t,cn,dn,{[ah]:!0});re(o,un,s),re(o,cn,o),re(s,un,s),re(s,cn,s);let l=re(t,Mi,dh,{[ch]:!0});re(l,cn),re(l,un,i),re(l,Mi,l),re(i,un,i),re(i,cn),re(i,Mi,i);let a=x(t,sh,gh,{[th]:!0}),c=x(t,c0,ph,{[th]:!0}),u=re(t,rh,ph,{[th]:!0});x(t,ih,u),x(c,sh,a),x(c,ih,u),re(c,rh,u),x(u,c0),x(u,sh),re(u,rh,u),x(u,ih,u);let d=re(t,nh,y0,{[f0]:!0});x(d,"#"),re(d,nh,d),x(d,PE,d);let h=x(d,LE);x(h,"#"),re(h,nh,d);let f=[[cn,o],[un,s]],p=[[cn,null],[Mi,l],[un,i]];for(let m=0;m<_l.length;m++)Nn(t,_l[m],hh,dn,f);for(let m=0;mm[0]>g[0]?1:-1);for(let m=0;m=0?w[uh]=!0:cn.test(g)?un.test(g)?w[Ni]=!0:w[ah]=!0:w[lh]=!0,a0(t,g,g,w)}return a0(t,"localhost",_i,{ascii:!0}),t.jd=new et(ha),{start:t,tokens:Object.assign({groups:e},w0)}}function k0(n,e){let t=BE(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=t.length,s=[],i=0,o=0;for(;o=0&&(d+=t[o].length,h++),c+=t[o].length,i+=t[o].length,o++;i-=d,o-=h,c-=d,s.push({t:u.t,v:e.slice(i-c,i),s:i-c,e:i})}return s}function BE(n){let e=[],t=n.length,r=0;for(;r56319||r+1===t||(i=n.charCodeAt(r+1))<56320||i>57343?n[r]:n.slice(r,r+2);e.push(o),r+=o.length}return e}function Nn(n,e,t,r,s){let i,o=e.length;for(let l=0;l=0;)i++;if(i>0){e.push(t.join(""));for(let o=parseInt(n.substring(r,r+i),10);o>0;o--)t.pop();r+=i}else t.push(n[r]),r++}return e}var Bi={defaultProtocol:"http",events:null,format:d0,formatHref:d0,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function xh(n,e=null){let t=Object.assign({},Bi);n&&(t=Object.assign(t,n instanceof xh?n.o:n));let r=t.ignoreTags,s=[];for(let i=0;it?r.substring(0,t)+"\u2026":r},toFormattedHref(n){return n.get("formatHref",this.toHref(n.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(n=Bi.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(n),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(n){return{type:this.t,value:this.toFormattedString(n),isLink:this.isLink,href:this.toFormattedHref(n),start:this.startIndex(),end:this.endIndex()}},validate(n){return n.get("validate",this.toString(),this)},render(n){let e=this,t=this.toHref(n.get("defaultProtocol")),r=n.get("formatHref",t,this),s=n.get("tagName",t,e),i=this.toFormattedString(n),o={},l=n.get("className",t,e),a=n.get("target",t,e),c=n.get("rel",t,e),u=n.getObj("attributes",t,e),d=n.getObj("events",t,e);return o.href=r,l&&(o.class=l),a&&(o.target=a),c&&(o.rel=c),u&&Object.assign(o,u),{tagName:s,attributes:o,content:i,eventListeners:d}}};function fa(n,e){class t extends b0{constructor(s,i){super(s,i),this.t=n}}for(let r in e)t.prototype[r]=e[r];return t.t=n,t}var zE=fa("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),h0=fa("text"),$E=fa("nl"),zl=fa("url",{isLink:!0,toHref(n=Bi.defaultProtocol){return this.hasProtocol()?this.v:`${n}://${this.v}`},hasProtocol(){let n=this.tk;return n.length>=2&&n[0].t!==_i&&n[1].t===ur}});var kt=n=>new et(n);function UE({groups:n}){let e=n.domain.concat([ea,na,In,ra,sa,ia,oa,la,bt,mh,Oi,aa,ca,ua,Ut,ha,Li,da]),t=[ta,ur,yh,$t,wh,Oi,Pi,kh,bh,Wl,jl,Ii,Di,Fl,Ul,Vl,Hl,ql,Jl,Kl,Yl,Gl,Xl,Ql,Zl],r=[ea,ta,na,ra,sa,ia,oa,la,bt,Ii,Di,Oi,aa,ca,ua,Pi,Ut,ha,Li,da],s=kt(),i=x(s,Li);$(i,r,i),$(i,n.domain,i);let o=kt(),l=kt(),a=kt();$(s,n.domain,o),$(s,n.scheme,l),$(s,n.slashscheme,a),$(o,r,i),$(o,n.domain,o);let c=x(o,In);x(i,In,c),x(l,In,c),x(a,In,c);let u=x(i,$t);$(u,r,i),$(u,n.domain,i);let d=kt();$(c,n.domain,d),$(d,n.domain,d);let h=x(d,$t);$(h,n.domain,d);let f=kt(zE);$(h,n.tld,f),$(h,n.utld,f),x(c,_i,f);let p=x(d,bt);x(p,bt,p),$(p,n.domain,d),$(f,n.domain,d),x(f,$t,h),x(f,bt,p);let m=x(o,bt),g=x(o,$t);x(m,bt,m),$(m,n.domain,o),$(g,r,i),$(g,n.domain,o);let y=kt(zl);$(g,n.tld,y),$(g,n.utld,y),$(y,n.domain,o),$(y,r,i),x(y,$t,g),x(y,bt,m),x(y,In,c);let w=x(y,ur),b=kt(zl);$(w,n.numeric,b);let v=kt(zl),C=kt();$(v,e,v),$(v,t,C),$(C,e,v),$(C,t,C),x(y,Ut,v),x(b,Ut,v);let R=x(l,ur),E=x(a,ur),_=x(E,Ut),U=x(_,Ut);$(l,n.domain,o),x(l,$t,g),x(l,bt,m),$(a,n.domain,o),x(a,$t,g),x(a,bt,m),$(R,n.domain,v),x(R,Ut,v),x(R,Pi,v),$(U,n.domain,v),$(U,e,v),x(U,Ut,v);let ae=[[Ii,Di],[Ul,Fl],[Vl,Hl],[Wl,jl],[ql,Jl],[Kl,Yl],[Gl,Xl],[Ql,Zl]];for(let ce=0;ce=0&&h++,s++,u++;if(h<0)s-=u,s0&&(i.push(oh(h0,e,o)),o=[]),s-=h,u-=h;let f=d.t,p=t.slice(s-u,s);i.push(oh(f,e,p))}}return o.length>0&&i.push(oh(h0,e,o)),i}function oh(n,e,t){let r=t[0].s,s=t[t.length-1].e,i=e.slice(r,s);return new n(i,t)}var VE=typeof console<"u"&&console&&console.warn||(()=>{}),HE="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Q={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function x0(){return et.groups={},Q.scanner=null,Q.parser=null,Q.tokenQueue=[],Q.pluginQueue=[],Q.customSchemes=[],Q.initialized=!1,Q}function Sh(n,e=!1){if(Q.initialized&&VE(`linkifyjs: already initialized - will not register custom scheme "${n}" ${HE}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(n))throw new Error(`linkifyjs: incorrect scheme format. 1. Must only contain digits, lowercase ASCII letters or "-" 2. Cannot start or end with "-" -3. "-" cannot repeat`);Q.customSchemes.push([n,e])}function FE(){Q.scanner=OE(Q.customSchemes);for(let n=0;n{let s=e.some(c=>c.docChanged)&&!t.doc.eq(r.doc),i=e.some(c=>c.getMeta("preventAutolink"));if(!s||i)return;let{tr:o}=r,l=Md(t.doc,[...e]);if(Od(l).forEach(({newRange:c})=>{let u=Vy(r.doc,c,f=>f.isTextblock),d,h;if(u.length>1)d=u[0],h=r.doc.textBetween(d.pos,d.pos+d.node.nodeSize,void 0," ");else if(u.length){let f=r.doc.textBetween(c.from,c.to," "," ");if(!HE.test(f))return;d=u[0],h=r.doc.textBetween(d.pos,c.to,void 0," ")}if(d&&h){let f=h.split(VE).filter(Boolean);if(f.length<=0)return!1;let p=f[f.length-1],m=d.pos+h.lastIndexOf(p);if(!p)return!1;let g=fa(p).map(y=>y.toObject(n.defaultProtocol));if(!jE(g))return!1;g.filter(y=>y.isLink).map(y=>({...y,from:m+y.start+1,to:m+y.end+1})).filter(y=>r.schema.marks.code?!r.doc.rangeHasMark(y.from,y.to,r.schema.marks.code):!0).filter(y=>n.validate(y.value)).filter(y=>n.shouldAutoLink(y.value)).forEach(y=>{bl(y.from,y.to,r.doc).some(w=>w.mark.type===n.type)||o.addMark(y.from,y.to,n.type.create({href:y.href}))})}}),!!o.steps.length)return o}})}function JE(n){return new O({key:new P("handleClickLink"),props:{handleClick:(e,t,r)=>{var s,i;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{let a=r.target;if(!a)return!1;let c=n.editor.view.dom;o=a.closest("a"),o&&!c.contains(o)&&(o=null)}if(!o)return!1;let l=!1;if(n.enableClickSelection&&(l=n.editor.commands.extendMarkRange(n.type.name)),n.openOnClick){let a=Dd(e.state,n.type.name),c=(s=o.href)!=null?s:a.href,u=(i=o.target)!=null?i:a.target;c&&(window.open(c,u),l=!0)}return l}}})}function KE(n){return new O({key:new P("handlePasteLink"),props:{handlePaste:(e,t,r)=>{let{shouldAutoLink:s}=n,{state:i}=e,{selection:o}=i,{empty:l}=o;if(l)return!1;let a="";r.content.forEach(u=>{a+=u.textContent});let c=pa(a,{defaultProtocol:n.defaultProtocol}).find(u=>u.isLink&&u.value===a);return!a||!c||s!==void 0&&!s(c.value)?!1:n.editor.commands.setMark(n.type,{href:c.href})}}})}function dr(n,e){let t=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{let s=typeof r=="string"?r:r.scheme;s&&t.push(s)}),!n||n.replace(WE,"").match(new RegExp(`^(?:(?:${t.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var Sh=lt.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(n=>{if(typeof n=="string"){bh(n);return}bh(n.scheme,n.optionalSlashes)})},onDestroy(){y0()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(n,e)=>!!dr(n,e.protocols),validate:n=>!!n,shouldAutoLink:n=>{let e=/^[a-z][a-z0-9+.-]*:\/\//i.test(n),t=/^[a-z][a-z0-9+.-]*:/i.test(n);if(e||t&&!n.includes("@"))return!0;let s=(n.includes("@")?n.split("@").pop():n).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||!/\./.test(s))}}},addAttributes(){return{href:{default:null,parseHTML(n){return n.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:n=>{let e=n.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!dr(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:n}){return this.options.isAllowedUri(n.href,{defaultValidate:e=>!!dr(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",B(this.options.HTMLAttributes,n),0]:["a",B(this.options.HTMLAttributes,{...n,href:""}),0]},markdownTokenName:"link",parseMarkdown:(n,e)=>e.applyMark("link",e.parseInline(n.tokens||[]),{href:n.href,title:n.title||null}),renderMarkdown:(n,e)=>{var t,r,s,i;let o=(r=(t=n.attrs)==null?void 0:t.href)!=null?r:"",l=(i=(s=n.attrs)==null?void 0:s.title)!=null?i:"",a=e.renderChildren(n);return l?`[${a}](${o} "${l}")`:`[${a}](${o})`},addCommands(){return{setLink:n=>({chain:e})=>{let{href:t}=n;return this.options.isAllowedUri(t,{defaultValidate:r=>!!dr(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,n).setMeta("preventAutolink",!0).run():!1},toggleLink:n=>({chain:e})=>{let{href:t}=n||{};return t&&!this.options.isAllowedUri(t,{defaultValidate:r=>!!dr(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,n,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:n})=>n().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[wt({find:n=>{let e=[];if(n){let{protocols:t,defaultProtocol:r}=this.options,s=pa(n).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:o=>!!dr(o,t),protocols:t,defaultProtocol:r}));s.length&&s.forEach(i=>{this.options.shouldAutoLink(i.value)&&e.push({text:i.value,data:{href:i.href},index:i.start})})}return e},type:this.type,getAttributes:n=>{var e;return{href:(e=n.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){let n=[],{protocols:e,defaultProtocol:t}=this.options;return this.options.autolink&&n.push(qE({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:s=>!!dr(s,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),n.push(JE({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&n.push(KE({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),n}}),w0=Sh;var YE=Object.defineProperty,GE=(n,e)=>{for(var t in e)YE(n,t,{get:e[t],enumerable:!0})},XE="listItem",k0="textStyle",b0=/^\s*([-+*])\s$/,Th=V.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:n}){return["ul",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>n.type!=="list"||n.ordered?[]:{type:"bulletList",content:n.items?e.parseChildren(n.items):[]},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(XE,this.editor.getAttributes(k0)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let n=zt({find:b0,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(n=zt({find:b0,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(k0),editor:this.editor})),[n]}}),QE=(n,e,t)=>{let{selection:r}=n;if(!r.empty)return null;let{$from:s}=r;if(!s.parent.isTextblock||s.parentOffset!==s.parent.content.size)return null;let i=-1;for(let f=s.depth;f>0;f-=1)if(s.node(f).type.name===e){i=f;break}if(i<0)return null;let o=s.node(i),l=s.index(i);if(l+1>=o.childCount)return null;let a=o.child(l+1);if(!t.includes(a.type.name))return null;let c=n.schema.nodes[e],u=!1;if(a.forEach(f=>{f.type===c&&f.childCount>1&&(u=!0)}),!u)return null;let d=n.doc.resolve(s.after()).nodeAfter;if(!d||!t.includes(d.type.name))return null;let h=[];return d.forEach(f=>{h.push(f)}),h.length===0?null:{listItemDepth:i,nestedList:d,nestedListPos:s.after(),insertPos:s.after(i),items:h}},ZE=(n,e,t,r)=>{let s=QE(n,t,r);if(!s)return!1;let{selection:i}=n,{nestedList:o,nestedListPos:l,insertPos:a,items:c}=s,u=n.tr;u.delete(l,l+o.nodeSize);let d=u.mapping.map(a);return u.insert(d,k.from(c)),u.setSelection(i.map(u.doc,u.mapping)),e&&e(u),!0},eM=(n,e,t)=>ZE(n.state,n.view.dispatch,e,t),C0=(n,e)=>F.create({name:`${n}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let t=()=>eM(this.editor,n,e);return{Delete:t,"Mod-Delete":t}}});function tM(n){var e,t;let r=(e=n.tokens)==null?void 0:e[0];return!!(n.text&&((t=n.tokens)==null?void 0:t.length)===1&&r?.type==="list"&&r.ordered&&r.raw===n.text)}function nM(n,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(n)):e.parseInline([{type:"text",raw:n,text:n}])}var Ah=V.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:n}){return["li",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"list_item",parseMarkdown:(n,e)=>{var t;if(n.type!=="list_item")return[];let r=(t=e.parseBlockChildren)!=null?t:e.parseChildren,s=[];if(n.tokens&&n.tokens.length>0){if(tM(n))return{type:"listItem",content:[{type:"paragraph",content:nM(n.text||"",e)}]};if(n.tokens.some(o=>o.type==="paragraph"))s=r(n.tokens);else{let o=n.tokens[0];if(o&&o.type==="text"&&o.tokens&&o.tokens.length>0){if(s=[{type:"paragraph",content:e.parseInline(o.tokens)}],n.tokens.length>1){let a=n.tokens.slice(1),c=r(a);s.push(...c)}}else s=r(n.tokens)}}return s.length===0&&(s=[{type:"paragraph",content:[]}]),{type:"listItem",content:s}},renderMarkdown:(n,e,t)=>gi(n,e,r=>{var s,i;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((i=(s=r.meta)==null?void 0:s.parentAttrs)==null?void 0:i.start)||1)+r.index}. `:"- "},t),addExtensions(){return[C0(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),rM={};GE(rM,{findListItemPos:()=>ma,getNextListDepth:()=>Eh,handleBackspace:()=>vh,handleDelete:()=>Ch,hasListBefore:()=>T0,hasListItemAfter:()=>sM,hasListItemBefore:()=>iM,listItemHasSubList:()=>oM,nextListIsDeeper:()=>A0,nextListIsHigher:()=>E0});var ma=(n,e)=>{let{$from:t}=e.selection,r=te(n,e.schema),s=null,i=t.depth,o=t.pos,l=null;for(;i>0&&l===null;)s=t.node(i),s.type===r?l=i:(i-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},Eh=(n,e)=>{let t=ma(n,e);if(!t)return!1;let[,r]=Ky(e,n,t.$pos.pos+4);return r},T0=(n,e,t)=>{let{$anchor:r}=n.selection,s=Math.max(0,r.pos-2),i=n.doc.resolve(s).node();return!(!i||!t.includes(i.type.name))},vh=(n,e,t)=>{if(n.commands.undoInputRule())return!0;if(n.state.selection.from!==n.state.selection.to)return!1;if(!_t(n.state,e)&&T0(n.state,e,t)){let{$anchor:r}=n.state.selection,s=n.state.doc.resolve(r.before()-1),i=[];s.node().descendants((a,c)=>{a.type.name===e&&i.push({node:a,pos:c})});let o=i.at(-1);if(!o)return!1;let l=n.state.doc.resolve(s.start()+o.pos+1);return n.chain().cut({from:r.start()-1,to:r.end()+1},l.end()).joinForward().run()}return!_t(n.state,e)||!Gy(n.state)?!1:n.chain().liftListItem(e).run()},A0=(n,e)=>{let t=Eh(n,e),r=ma(n,e);return!r||!t?!1:t>r.depth},E0=(n,e)=>{let t=Eh(n,e),r=ma(n,e);return!r||!t?!1:t{if(!_t(n.state,e)||!Yy(n.state,e))return!1;let{selection:t}=n.state,{$from:r,$to:s}=t;return!t.empty&&r.sameParent(s)?!1:A0(e,n.state)?n.chain().focus(n.state.selection.from+4).lift(e).joinBackward().run():E0(e,n.state)?n.chain().joinForward().joinBackward().run():n.commands.joinItemForward()},sM=(n,e)=>{var t;let{$anchor:r}=e.selection,s=e.doc.resolve(r.pos-r.parentOffset-2);return!(s.index()===s.parent.childCount-1||((t=s.nodeAfter)==null?void 0:t.type.name)!==n)},iM=(n,e)=>{var t;let{$anchor:r}=e.selection,s=e.doc.resolve(r.pos-2);return!(s.index()===0||((t=s.nodeBefore)==null?void 0:t.type.name)!==n)},oM=(n,e,t)=>{if(!t)return!1;let r=te(n,e.schema),s=!1;return t.descendants(i=>{i.type===r&&(s=!0)}),s},Mh=F.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&Ch(n,t)&&(e=!0)}),e},"Mod-Delete":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&Ch(n,t)&&(e=!0)}),e},Backspace:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&vh(n,t,r)&&(e=!0)}),e},"Mod-Backspace":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&vh(n,t,r)&&(e=!0)}),e}}}}),x0=/^(\s*)(\d+)\.\s+(.*)$/,lM=/^\s/;function aM(n){let e=n.trimStart();return/^[-+*]\s+/.test(e)||/^\d+\.\s+/.test(e)||/^>\s?/.test(e)||/^```/.test(e)||/^~~~/.test(e)}function cM(n){let e=[],t=[],r=!1;return n.forEach(s=>{if(r){t.push(s);return}if(s.trim()===""){r=!0,t.push(s);return}if(e.length>0&&aM(s)){r=!0,t.push(s);return}e.push(s)}),{paragraphLines:e,blockLines:t}}function uM(n){let e=[],t=0,r=0;for(;t{let s=e.some(c=>c.docChanged)&&!t.doc.eq(r.doc),i=e.some(c=>c.getMeta("preventAutolink"));if(!s||i)return;let{tr:o}=r,l=Nd(t.doc,[...e]);if(Ld(l).forEach(({newRange:c})=>{let u=qy(r.doc,c,f=>f.isTextblock),d,h;if(u.length>1)d=u[0],h=r.doc.textBetween(d.pos,d.pos+d.node.nodeSize,void 0," ");else if(u.length){let f=r.doc.textBetween(c.from,c.to," "," ");if(!qE.test(f))return;d=u[0],h=r.doc.textBetween(d.pos,c.to,void 0," ")}if(d&&h){let f=h.split(jE).filter(Boolean);if(f.length<=0)return!1;let p=f[f.length-1],m=d.pos+h.lastIndexOf(p);if(!p)return!1;let g=pa(p).map(y=>y.toObject(n.defaultProtocol));if(!KE(g))return!1;g.filter(y=>y.isLink).map(y=>({...y,from:m+y.start+1,to:m+y.end+1})).filter(y=>r.schema.marks.code?!r.doc.rangeHasMark(y.from,y.to,r.schema.marks.code):!0).filter(y=>n.validate(y.value)).filter(y=>n.shouldAutoLink(y.value)).forEach(y=>{xl(y.from,y.to,r.doc).some(w=>w.mark.type===n.type)||o.addMark(y.from,y.to,n.type.create({href:y.href}))})}}),!!o.steps.length)return o}})}function GE(n){return new O({key:new P("handleClickLink"),props:{handleClick:(e,t,r)=>{var s,i;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{let a=r.target;if(!a)return!1;let c=n.editor.view.dom;o=a.closest("a"),o&&!c.contains(o)&&(o=null)}if(!o)return!1;let l=!1;if(n.enableClickSelection&&(l=n.editor.commands.extendMarkRange(n.type.name)),n.openOnClick){let a=Pd(e.state,n.type.name),c=(s=o.href)!=null?s:a.href,u=(i=o.target)!=null?i:a.target;c&&(window.open(c,u),l=!0)}return l}}})}function XE(n){return new O({key:new P("handlePasteLink"),props:{handlePaste:(e,t,r)=>{let{shouldAutoLink:s}=n,{state:i}=e,{selection:o}=i,{empty:l}=o;if(l)return!1;let a="";r.content.forEach(u=>{a+=u.textContent});let c=ma(a,{defaultProtocol:n.defaultProtocol}).find(u=>u.isLink&&u.value===a);return!a||!c||s!==void 0&&!s(c.value)?!1:n.editor.commands.setMark(n.type,{href:c.href})}}})}function dr(n,e){let t=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{let s=typeof r=="string"?r:r.scheme;s&&t.push(s)}),!n||n.replace(JE,"").match(new RegExp(`^(?:(?:${t.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var Ch=lt.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(n=>{if(typeof n=="string"){Sh(n);return}Sh(n.scheme,n.optionalSlashes)})},onDestroy(){x0()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(n,e)=>!!dr(n,e.protocols),validate:n=>!!n,shouldAutoLink:n=>{let e=/^[a-z][a-z0-9+.-]*:\/\//i.test(n),t=/^[a-z][a-z0-9+.-]*:/i.test(n);if(e||t&&!n.includes("@"))return!0;let s=(n.includes("@")?n.split("@").pop():n).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||!/\./.test(s))}}},addAttributes(){return{href:{default:null,parseHTML(n){return n.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:n=>{let e=n.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!dr(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:n}){return this.options.isAllowedUri(n.href,{defaultValidate:e=>!!dr(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",B(this.options.HTMLAttributes,n),0]:["a",B(this.options.HTMLAttributes,{...n,href:""}),0]},markdownTokenName:"link",parseMarkdown:(n,e)=>e.applyMark("link",e.parseInline(n.tokens||[]),{href:n.href,title:n.title||null}),renderMarkdown:(n,e)=>{var t,r,s,i;let o=(r=(t=n.attrs)==null?void 0:t.href)!=null?r:"",l=(i=(s=n.attrs)==null?void 0:s.title)!=null?i:"",a=e.renderChildren(n);return l?`[${a}](${o} "${l}")`:`[${a}](${o})`},addCommands(){return{setLink:n=>({chain:e})=>{let{href:t}=n;return this.options.isAllowedUri(t,{defaultValidate:r=>!!dr(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,n).setMeta("preventAutolink",!0).run():!1},toggleLink:n=>({chain:e})=>{let{href:t}=n||{};return t&&!this.options.isAllowedUri(t,{defaultValidate:r=>!!dr(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,n,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:n})=>n().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[wt({find:n=>{let e=[];if(n){let{protocols:t,defaultProtocol:r}=this.options,s=ma(n).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:o=>!!dr(o,t),protocols:t,defaultProtocol:r}));s.length&&s.forEach(i=>{this.options.shouldAutoLink(i.value)&&e.push({text:i.value,data:{href:i.href},index:i.start})})}return e},type:this.type,getAttributes:n=>{var e;return{href:(e=n.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){let n=[],{protocols:e,defaultProtocol:t}=this.options;return this.options.autolink&&n.push(YE({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:s=>!!dr(s,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),n.push(GE({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&n.push(XE({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),n}}),S0=Ch;var QE=Object.defineProperty,ZE=(n,e)=>{for(var t in e)QE(n,t,{get:e[t],enumerable:!0})},eM="listItem",v0="textStyle",C0=/^\s*([-+*])\s$/,Eh=V.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:n}){return["ul",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>n.type!=="list"||n.ordered?[]:{type:"bulletList",content:n.items?e.parseChildren(n.items):[]},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(eM,this.editor.getAttributes(v0)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let n=zt({find:C0,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(n=zt({find:C0,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(v0),editor:this.editor})),[n]}}),tM=(n,e,t)=>{let{selection:r}=n;if(!r.empty)return null;let{$from:s}=r;if(!s.parent.isTextblock||s.parentOffset!==s.parent.content.size)return null;let i=-1;for(let f=s.depth;f>0;f-=1)if(s.node(f).type.name===e){i=f;break}if(i<0)return null;let o=s.node(i),l=s.index(i);if(l+1>=o.childCount)return null;let a=o.child(l+1);if(!t.includes(a.type.name))return null;let c=n.schema.nodes[e],u=!1;if(a.forEach(f=>{f.type===c&&f.childCount>1&&(u=!0)}),!u)return null;let d=n.doc.resolve(s.after()).nodeAfter;if(!d||!t.includes(d.type.name))return null;let h=[];return d.forEach(f=>{h.push(f)}),h.length===0?null:{listItemDepth:i,nestedList:d,nestedListPos:s.after(),insertPos:s.after(i),items:h}},nM=(n,e,t,r)=>{let s=tM(n,t,r);if(!s)return!1;let{selection:i}=n,{nestedList:o,nestedListPos:l,insertPos:a,items:c}=s,u=n.tr;u.delete(l,l+o.nodeSize);let d=u.mapping.map(a);return u.insert(d,k.from(c)),u.setSelection(i.map(u.doc,u.mapping)),e&&e(u),!0},rM=(n,e,t)=>nM(n.state,n.view.dispatch,e,t),M0=(n,e)=>F.create({name:`${n}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let t=()=>rM(this.editor,n,e);return{Delete:t,"Mod-Delete":t}}});function sM(n){var e,t;let r=(e=n.tokens)==null?void 0:e[0];return!!(n.text&&((t=n.tokens)==null?void 0:t.length)===1&&r?.type==="list"&&r.ordered&&r.raw===n.text)}function iM(n,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(n)):e.parseInline([{type:"text",raw:n,text:n}])}var Mh=V.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:n}){return["li",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"list_item",parseMarkdown:(n,e)=>{var t;if(n.type!=="list_item")return[];let r=(t=e.parseBlockChildren)!=null?t:e.parseChildren,s=[];if(n.tokens&&n.tokens.length>0){if(sM(n))return{type:"listItem",content:[{type:"paragraph",content:iM(n.text||"",e)}]};if(n.tokens.some(o=>o.type==="paragraph"))s=r(n.tokens);else{let o=n.tokens[0];if(o&&o.type==="text"&&o.tokens&&o.tokens.length>0){if(s=[{type:"paragraph",content:e.parseInline(o.tokens)}],n.tokens.length>1){let a=n.tokens.slice(1),c=r(a);s.push(...c)}}else s=r(n.tokens)}}return s.length===0&&(s=[{type:"paragraph",content:[]}]),{type:"listItem",content:s}},renderMarkdown:(n,e,t)=>wi(n,e,r=>{var s,i;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((i=(s=r.meta)==null?void 0:s.parentAttrs)==null?void 0:i.start)||1)+r.index}. `:"- "},t),addExtensions(){return[M0(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),oM={};ZE(oM,{findListItemPos:()=>ga,getNextListDepth:()=>Rh,handleBackspace:()=>Th,handleDelete:()=>Ah,hasListBefore:()=>R0,hasListItemAfter:()=>lM,hasListItemBefore:()=>aM,listItemHasSubList:()=>cM,nextListIsDeeper:()=>N0,nextListIsHigher:()=>I0});var ga=(n,e)=>{let{$from:t}=e.selection,r=te(n,e.schema),s=null,i=t.depth,o=t.pos,l=null;for(;i>0&&l===null;)s=t.node(i),s.type===r?l=i:(i-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},Rh=(n,e)=>{let t=ga(n,e);if(!t)return!1;let[,r]=Qy(e,n,t.$pos.pos+4);return r},R0=(n,e,t)=>{let{$anchor:r}=n.selection,s=Math.max(0,r.pos-2),i=n.doc.resolve(s).node();return!(!i||!t.includes(i.type.name))},Th=(n,e,t)=>{if(n.commands.undoInputRule())return!0;if(n.state.selection.from!==n.state.selection.to)return!1;if(!_t(n.state,e)&&R0(n.state,e,t)){let{$anchor:r}=n.state.selection,s=n.state.doc.resolve(r.before()-1),i=[];s.node().descendants((a,c)=>{a.type.name===e&&i.push({node:a,pos:c})});let o=i.at(-1);if(!o)return!1;let l=n.state.doc.resolve(s.start()+o.pos+1);return n.chain().cut({from:r.start()-1,to:r.end()+1},l.end()).joinForward().run()}return!_t(n.state,e)||!ew(n.state)?!1:n.chain().liftListItem(e).run()},N0=(n,e)=>{let t=Rh(n,e),r=ga(n,e);return!r||!t?!1:t>r.depth},I0=(n,e)=>{let t=Rh(n,e),r=ga(n,e);return!r||!t?!1:t{if(!_t(n.state,e)||!Zy(n.state,e))return!1;let{selection:t}=n.state,{$from:r,$to:s}=t;return!t.empty&&r.sameParent(s)?!1:N0(e,n.state)?n.chain().focus(n.state.selection.from+4).lift(e).joinBackward().run():I0(e,n.state)?n.chain().joinForward().joinBackward().run():n.commands.joinItemForward()},lM=(n,e)=>{var t;let{$anchor:r}=e.selection,s=e.doc.resolve(r.pos-r.parentOffset-2);return!(s.index()===s.parent.childCount-1||((t=s.nodeAfter)==null?void 0:t.type.name)!==n)},aM=(n,e)=>{var t;let{$anchor:r}=e.selection,s=e.doc.resolve(r.pos-2);return!(s.index()===0||((t=s.nodeBefore)==null?void 0:t.type.name)!==n)},cM=(n,e,t)=>{if(!t)return!1;let r=te(n,e.schema),s=!1;return t.descendants(i=>{i.type===r&&(s=!0)}),s},Nh=F.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&Ah(n,t)&&(e=!0)}),e},"Mod-Delete":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&Ah(n,t)&&(e=!0)}),e},Backspace:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&Th(n,t,r)&&(e=!0)}),e},"Mod-Backspace":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&Th(n,t,r)&&(e=!0)}),e}}}}),T0=/^(\s*)(\d+)\.\s+(.*)$/,uM=/^\s/;function dM(n){let e=n.trimStart();return/^[-+*]\s+/.test(e)||/^\d+\.\s+/.test(e)||/^>\s?/.test(e)||/^```/.test(e)||/^~~~/.test(e)}function hM(n){let e=[],t=[],r=!1;return n.forEach(s=>{if(r){t.push(s);return}if(s.trim()===""){r=!0,t.push(s);return}if(e.length>0&&dM(s)){r=!0,t.push(s);return}e.push(s)}),{paragraphLines:e,blockLines:t}}function fM(n){let e=[],t=0,r=0;for(;te;)h.push(n[d]),d+=1;if(h.length>0){let f=Math.min(...h.map(m=>m.indent)),p=M0(h,f,t);c.push({type:"list",ordered:!0,start:h[0].number,items:p,raw:h.map(m=>m.raw).join(` -`)})}r.push({type:"list_item",raw:i.raw,tokens:c}),s=d}else s+=1}return r}function dM(n,e){return n.map(t=>{if(t.type!=="list_item")return e.parseChildren([t])[0];let r=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(s=>{if(s.type==="paragraph"||s.type==="list"||s.type==="blockquote"||s.type==="code")r.push(...e.parseChildren([s]));else if(s.type==="text"&&s.tokens){let i=e.parseChildren([s]);r.push({type:"paragraph",content:i})}else{let i=e.parseChildren([s]);i.length>0&&r.push(...i)}}),{type:"listItem",content:r}})}var hM="listItem",S0="textStyle",v0=/^(\d+)\.\s$/,Rh=V.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:n=>n.hasAttribute("start")?parseInt(n.getAttribute("start")||"",10):1},type:{default:null,parseHTML:n=>n.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:n}){let{start:e,...t}=n;return e===1?["ol",B(this.options.HTMLAttributes,t),0]:["ol",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>{if(n.type!=="list"||!n.ordered)return[];let t=n.start||1,r=n.items?dM(n.items,e):[];return t!==1?{type:"orderedList",attrs:{start:t},content:r}:{type:"orderedList",content:r}},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`).trim();if(u){let f=t.blockTokens(u);c.push(...f)}let d=s+1,h=[];for(;de;)h.push(n[d]),d+=1;if(h.length>0){let f=Math.min(...h.map(m=>m.indent)),p=D0(h,f,t);c.push({type:"list",ordered:!0,start:h[0].number,items:p,raw:h.map(m=>m.raw).join(` +`)})}r.push({type:"list_item",raw:i.raw,tokens:c}),s=d}else s+=1}return r}function pM(n,e){return n.map(t=>{if(t.type!=="list_item")return e.parseChildren([t])[0];let r=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(s=>{if(s.type==="paragraph"||s.type==="list"||s.type==="blockquote"||s.type==="code")r.push(...e.parseChildren([s]));else if(s.type==="text"&&s.tokens){let i=e.parseChildren([s]);r.push({type:"paragraph",content:i})}else{let i=e.parseChildren([s]);i.length>0&&r.push(...i)}}),{type:"listItem",content:r}})}var mM="listItem",A0="textStyle",E0=/^(\d+)\.\s$/,Ih=V.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:n=>n.hasAttribute("start")?parseInt(n.getAttribute("start")||"",10):1},type:{default:null,parseHTML:n=>n.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:n}){let{start:e,...t}=n;return e===1?["ol",B(this.options.HTMLAttributes,t),0]:["ol",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>{if(n.type!=="list"||!n.ordered)return[];let t=n.start||1,r=n.items?pM(n.items,e):[];return t!==1?{type:"orderedList",attrs:{start:t},content:r}:{type:"orderedList",content:r}},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` `):"",markdownTokenizer:{name:"orderedList",level:"block",start:n=>{let e=n.match(/^(\s*)(\d+)\.\s+/),t=e?.index;return t!==void 0?t:-1},tokenize:(n,e,t)=>{var r;let s=n.split(` -`),[i,o]=uM(s);if(i.length===0)return;let l=M0(i,0,t);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=i[0])==null?void 0:r.number)||1,items:l,raw:s.slice(0,o).join(` -`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(hM,this.editor.getAttributes(S0)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let n=zt({find:v0,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(n=zt({find:v0,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(S0)}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1],editor:this.editor})),[n]}}),fM=/^\s*(\[([( |x])?\])\s$/,ga=V.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:n=>{let e=n.getAttribute("data-checked");return e===""||e==="true"},renderHTML:n=>({"data-checked":n.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:n,HTMLAttributes:e}){return["li",B(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:n.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(n,e)=>{let t=[];if(n.tokens&&n.tokens.length>0?t.push(e.createNode("paragraph",{},e.parseInline(n.tokens))):n.text?t.push(e.createNode("paragraph",{},[e.createNode("text",{text:n.text})])):t.push(e.createNode("paragraph",{},[])),n.nestedTokens&&n.nestedTokens.length>0){let r=e.parseChildren(n.nestedTokens);t.push(...r)}return e.createNode("taskItem",{checked:n.checked||!1},t)},renderMarkdown:(n,e)=>{var t;let s=`- [${(t=n.attrs)!=null&&t.checked?"x":" "}] `;return gi(n,e,s)},addExtensions(){return this.options.nested?[C0(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let n={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...n,Tab:()=>this.editor.commands.sinkListItem(this.name)}:n},addNodeView(){return({node:n,HTMLAttributes:e,getPos:t,editor:r})=>{let s=document.createElement("li"),i=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),a=document.createElement("div"),c=d=>{var h,f;l.ariaLabel=((f=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:f.call(h,d,l.checked))||`Task item checkbox for ${d.textContent||"empty task item"}`};c(n),i.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}let{checked:h}=d.target;r.isEditable&&typeof t=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{let p=t();if(typeof p!="number")return!1;let m=f.doc.nodeAt(p);return f.setNodeMarkup(p,void 0,{...m?.attrs,checked:h}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(n,h)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,h])=>{s.setAttribute(d,h)}),s.dataset.checked=n.attrs.checked,l.checked=n.attrs.checked,i.append(l,o),s.append(i,a),Object.entries(e).forEach(([d,h])=>{s.setAttribute(d,h)});let u=new Set(Object.keys(e));return{dom:s,contentDOM:a,update:d=>{if(d.type!==this.type)return!1;s.dataset.checked=d.attrs.checked,l.checked=d.attrs.checked,c(d);let h=r.extensionManager.attributes,f=Zr(d,h),p=new Set(Object.keys(f)),m=this.options.HTMLAttributes;return u.forEach(g=>{p.has(g)||(g in m?s.setAttribute(g,m[g]):s.removeAttribute(g))}),Object.entries(f).forEach(([g,y])=>{y==null?g in m?s.setAttribute(g,m[g]):s.removeAttribute(g):s.setAttribute(g,y)}),u=p,!0}}}},addInputRules(){return[zt({find:fM,type:this.type,getAttributes:n=>({checked:n[n.length-1]==="x"})})]}}),ya=V.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:n}){return["ul",B(this.options.HTMLAttributes,n,{"data-type":this.name}),0]},parseMarkdown:(n,e)=>e.createNode("taskList",{},e.parseChildren(n.items||[])),renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):"",markdownTokenizer:{name:"taskList",level:"block",start(n){var e;let t=(e=n.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return t!==void 0?t:-1},tokenize(n,e,t){let r=i=>{let o=Tl(i,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,a)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:t.inlineTokens(l.mainContent),nestedTokens:a}),customNestedParser:r},t);return o?[{type:"taskList",raw:o.raw,items:o.items}]:t.blockTokens(i)},s=Tl(n,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:i=>({indentLevel:i[1].length,mainContent:i[4],checked:i[3].toLowerCase()==="x"}),createToken:(i,o)=>({type:"taskItem",raw:"",mainContent:i.mainContent,indentLevel:i.indentLevel,checked:i.checked,text:i.mainContent,tokens:t.inlineTokens(i.mainContent),nestedTokens:o}),customNestedParser:r},t);if(s)return{type:"taskList",raw:s.raw,items:s.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:n})=>n.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),XB=F.create({name:"listKit",addExtensions(){let n=[];return this.options.bulletList!==!1&&n.push(Th.configure(this.options.bulletList)),this.options.listItem!==!1&&n.push(Ah.configure(this.options.listItem)),this.options.listKeymap!==!1&&n.push(Mh.configure(this.options.listKeymap)),this.options.orderedList!==!1&&n.push(Rh.configure(this.options.orderedList)),this.options.taskItem!==!1&&n.push(ga.configure(this.options.taskItem)),this.options.taskList!==!1&&n.push(ya.configure(this.options.taskList)),n}});var wa=" ",Nh="\xA0",R0=V.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:n}){return["p",B(this.options.HTMLAttributes,n),0]},parseMarkdown:(n,e)=>{let t=n.tokens||[];if(t.length===1&&t[0].type==="image")return e.parseChildren([t[0]]);let r=e.parseInline(t);return t.length===1&&t[0].type==="text"&&(t[0].raw===wa||t[0].text===wa||t[0].raw===Nh||t[0].text===Nh)&&r.length===1&&r[0].type==="text"&&(r[0].text===wa||r[0].text===Nh)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(n,e,t)=>{var r,s;if(!n)return"";let i=Array.isArray(n.content)?n.content:[];if(i.length===0){let o=Array.isArray((r=t?.previousNode)==null?void 0:r.content)?t.previousNode.content:[];return((s=t?.previousNode)==null?void 0:s.type)==="paragraph"&&o.length===0?wa:""}return e.renderChildren(i)},addCommands(){return{setParagraph:()=>({commands:n})=>n.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}});var pM=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,mM=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,N0=lt.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["s",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"del",parseMarkdown:(n,e)=>e.applyMark("strike",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`~~${e.renderChildren(n)}~~`,addCommands(){return{setStrike:()=>({commands:n})=>n.setMark(this.name),toggleStrike:()=>({commands:n})=>n.toggleMark(this.name),unsetStrike:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Bt({find:pM,type:this.type})]},addPasteRules(){return[wt({find:mM,type:this.type})]}});var I0=V.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});var D0=lt.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["u",B(this.options.HTMLAttributes,n),0]},parseMarkdown(n,e){return e.applyMark(this.name||"underline",e.parseInline(n.tokens||[]))},renderMarkdown(n,e){return`++${e.renderChildren(n)}++`},markdownTokenizer:{name:"underline",level:"inline",start(n){return n.indexOf("++")},tokenize(n,e,t){let s=/^(\+\+)([\s\S]+?)(\+\+)/.exec(n);if(!s)return;let i=s[2].trim();return{type:"underline",raw:s[0],text:i,tokens:t.inlineTokens(i)}}},addCommands(){return{setUnderline:()=>({commands:n})=>n.setMark(this.name),toggleUnderline:()=>({commands:n})=>n.toggleMark(this.name),unsetUnderline:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function O0(n={}){return new O({view(e){return new Ih(e,n)}})}var Ih=class{constructor(e,t){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=t.width)!==null&&r!==void 0?r:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(s=>{let i=o=>{this[s](o)};return e.dom.addEventListener(s,i),{name:s,handler:i}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,r,s=this.editorView.dom,i=s.getBoundingClientRect(),o=i.width/s.offsetWidth,l=i.height/s.offsetHeight;if(t){let d=e.nodeBefore,h=e.nodeAfter;if(d||h){let f=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(f){let p=f.getBoundingClientRect(),m=d?p.bottom:p.top;d&&h&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*o;r={left:d.left-h,right:d.left+h,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),h=d.width/a.offsetWidth,f=d.height/a.offsetHeight;c=d.left-a.scrollLeft*h,u=d.top-a.scrollTop*f}this.element.style.left=(r.left-c)/o+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),s=r&&r.type.spec.disableDropCursor,i=typeof s=="function"?s(this.editorView,t,e):s;if(t&&!i){let o=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=jo(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var $e=class n extends I{constructor(e){super(e,e)}map(e,t){let r=e.resolve(t.map(this.head));return n.valid(r)?new n(r):I.near(r)}content(){return S.empty}eq(e){return e instanceof n&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new n(e.resolve(t.pos))}getBookmark(){return new Dh(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!gM(e)||!yM(e))return!1;let r=t.type.spec.allowGapCursor;if(r!=null)return r;let s=t.contentMatchAt(e.index()).defaultType;return s&&s.isTextblock}static findGapCursorFrom(e,t,r=!1){e:for(;;){if(!r&&n.valid(e))return e;let s=e.pos,i=null;for(let o=e.depth;;o--){let l=e.node(o);if(t>0?e.indexAfter(o)0){i=l.child(t>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;s+=t;let a=e.doc.resolve(s);if(n.valid(a))return a}for(;;){let o=t>0?i.firstChild:i.lastChild;if(!o){if(i.isAtom&&!i.isText&&!M.isSelectable(i)){e=e.doc.resolve(s+i.nodeSize*t),r=!1;continue e}break}i=o,s+=t;let l=e.doc.resolve(s);if(n.valid(l))return l}return null}}};$e.prototype.visible=!1;$e.findFrom=$e.findGapCursorFrom;I.jsonID("gapcursor",$e);var Dh=class n{constructor(e){this.pos=e}map(e){return new n(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return $e.valid(t)?new $e(t):I.near(t)}};function P0(n){return n.isAtom||n.spec.isolating||n.spec.createGapCursor}function gM(n){for(let e=n.depth;e>=0;e--){let t=n.index(e),r=n.node(e);if(t==0){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(t-1);;s=s.lastChild){if(s.childCount==0&&!s.inlineContent||P0(s.type))return!0;if(s.inlineContent)return!1}}return!0}function yM(n){for(let e=n.depth;e>=0;e--){let t=n.indexAfter(e),r=n.node(e);if(t==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(t);;s=s.firstChild){if(s.childCount==0&&!s.inlineContent||P0(s.type))return!0;if(s.inlineContent)return!1}}return!0}function L0(){return new O({props:{decorations:xM,createSelectionBetween(n,e,t){return e.pos==t.pos&&$e.valid(t)?new $e(t):null},handleClick:kM,handleKeyDown:wM,handleDOMEvents:{beforeinput:bM}}})}var wM=ui({ArrowLeft:ka("horiz",-1),ArrowRight:ka("horiz",1),ArrowUp:ka("vert",-1),ArrowDown:ka("vert",1)});function ka(n,e){let t=n=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,s,i){let o=r.selection,l=e>0?o.$to:o.$from,a=o.empty;if(o instanceof E){if(!i.endOfTextblock(t)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=$e.findGapCursorFrom(l,e,a);return c?(s&&s(r.tr.setSelection(new $e(c))),!0):!1}}function kM(n,e,t){if(!n||!n.editable)return!1;let r=n.state.doc.resolve(e);if(!$e.valid(r))return!1;let s=n.posAtCoords({left:t.clientX,top:t.clientY});return s&&s.inside>-1&&M.isSelectable(n.state.doc.nodeAt(s.inside))?!1:(n.dispatch(n.state.tr.setSelection(new $e(r))),!0)}function bM(n,e){if(e.inputType!="insertCompositionText"||!(n.state.selection instanceof $e))return!1;let{$from:t}=n.state.selection,r=t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);if(!r)return!1;let s=k.empty;for(let o=r.length-1;o>=0;o--)s=k.from(r[o].createAndFill(null,s));let i=n.state.tr.replace(t.pos,t.pos,new S(s,0,0));return i.setSelection(E.near(i.doc.resolve(t.pos+1))),n.dispatch(i),!1}function xM(n){if(!(n.selection instanceof $e))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",X.create(n.doc,[de.widget(n.selection.head,e,{key:"gapcursor"})])}var ba=200,De=function(){};De.prototype.append=function(e){return e.length?(e=De.from(e),!this.length&&e||e.length=t?De.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};De.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};De.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};De.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var s=[];return this.forEach(function(i,o){return s.push(e(i,o))},t,r),s};De.from=function(e){return e instanceof De?e:e&&e.length?new _0(e):De.empty};var _0=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(s,i){return s==0&&i==this.length?this:new e(this.values.slice(s,i))},e.prototype.getInner=function(s){return this.values[s]},e.prototype.forEachInner=function(s,i,o,l){for(var a=i;a=o;a--)if(s(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(s){if(this.length+s.length<=ba)return new e(this.values.concat(s.flatten()))},e.prototype.leafPrepend=function(s){if(this.length+s.length<=ba)return new e(s.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(De);De.empty=new _0([]);var SM=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(s-l,0),Math.min(this.length,i)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,s,i,o){var l=this.left.length;if(s>l&&this.right.forEachInvertedInner(r,s-l,Math.max(i,l)-l,o+l)===!1||i=i?this.right.slice(r-i,s-i):this.left.slice(r,i).append(this.right.slice(0,s-i))},e.prototype.leafAppend=function(r){var s=this.right.leafAppend(r);if(s)return new e(this.left,s)},e.prototype.leafPrepend=function(r){var s=this.left.leafPrepend(r);if(s)return new e(s,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(De),Oh=De;var vM=500,fr=class n{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let s,i;t&&(s=this.remapping(r,this.items.length),i=s.maps.length);let o=e.tr,l,a,c=[],u=[];return this.items.forEach((d,h)=>{if(!d.step){s||(s=this.remapping(r,h+1),i=s.maps.length),i--,u.push(d);return}if(s){u.push(new Ft(d.map));let f=d.step.map(s.slice(i)),p;f&&o.maybeStep(f).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new Ft(p,void 0,void 0,c.length+u.length))),i--,p&&s.appendMap(p,i)}else o.maybeStep(d.step);if(d.selection)return l=s?d.selection.map(s.slice(i)):d.selection,a=new n(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,s){let i=[],o=this.eventCount,l=this.items,a=!s&&l.length?l.get(l.length-1):null;for(let u=0;uTM&&(l=CM(l,c),o-=c),new n(l.append(i),o)}remapping(e,t){let r=new Gs;return this.items.forEach((s,i)=>{let o=s.mirrorOffset!=null&&i-s.mirrorOffset>=e?r.maps.length-s.mirrorOffset:void 0;r.appendMap(s.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new Ft(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],s=Math.max(0,this.items.length-t),i=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(h=>{h.selection&&l--},s);let a=t;this.items.forEach(h=>{let f=i.getMirror(--a);if(f==null)return;o=Math.min(o,f);let p=i.maps[f];if(h.step){let m=e.steps[f].invert(e.docs[f]),g=h.selection&&h.selection.map(i.slice(a+1,f));g&&l++,r.push(new Ft(p,m,g))}else r.push(new Ft(p))},s);let c=[];for(let h=t;hvM&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,s=[],i=0;return this.items.forEach((o,l)=>{if(l>=e)s.push(o),o.selection&&i++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let u=o.selection&&o.selection.map(t.slice(r));u&&i++;let d=new Ft(c.invert(),a,u),h,f=s.length-1;(h=s.length&&s[f].merge(d))?s[f]=h:s.push(d)}}else o.map&&r--},this.items.length,0),new n(Oh.from(s.reverse()),i)}};fr.empty=new fr(Oh.empty,0);function CM(n,e){let t;return n.forEach((r,s)=>{if(r.selection&&e--==0)return t=s,!1}),n.slice(t)}var Ft=class n{constructor(e,t,r,s){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=s}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new n(t.getMap().invert(),t,this.selection)}}},Vt=class{constructor(e,t,r,s,i){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=s,this.prevComposition=i}},TM=20;function AM(n,e,t,r){let s=t.getMeta(hr),i;if(s)return s.historyState;t.getMeta(RM)&&(n=new Vt(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(hr))return o.getMeta(hr).redo?new Vt(n.done.addTransform(t,void 0,r,xa(e)),n.undone,B0(t.mapping.maps),n.prevTime,n.prevComposition):new Vt(n.done,n.undone.addTransform(t,void 0,r,xa(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!EM(t,n.prevRanges)),c=o?Ph(n.prevRanges,t.mapping):B0(t.mapping.maps);return new Vt(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,xa(e)),fr.empty,c,t.time,l??n.prevComposition)}else return(i=t.getMeta("rebased"))?new Vt(n.done.rebased(t,i),n.undone.rebased(t,i),Ph(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Vt(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Ph(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function EM(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,s)=>{for(let i=0;i=e[i]&&(t=!0)}),t}function B0(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,s,i,o)=>e.push(i,o));return e}function Ph(n,e){if(!n)return null;let t=[];for(let r=0;r{let s=hr.getState(t);if(!s||(n?s.undone:s.done).eventCount==0)return!1;if(r){let i=MM(s,t,n);i&&r(e?i.scrollIntoView():i)}return!0}}var _h=Sa(!1,!0),Bh=Sa(!0,!0),vz=Sa(!1,!1),Cz=Sa(!0,!1);var Nz=F.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:n=>n.length,wordCounter:n=>n.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=n=>{let e=n?.node||this.editor.state.doc;if((n?.mode||this.options.mode)==="textSize"){let r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=n=>{let e=n?.node||this.editor.state.doc,t=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(t)}},addProseMirrorPlugins(){let n=!1;return[new O({key:new P("characterCount"),appendTransaction:(e,t,r)=>{if(n)return;let s=this.options.limit,i=this.options.autoTrim;if(s==null||s===0||i===!1){n=!0;return}let o=this.storage.characters({node:r.doc});if(o>s){let l=o-s,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${s} characters. Content was automatically trimmed.`);let u=r.tr.deleteRange(a,c);return n=!0,u}n=!0},filterTransaction:(e,t)=>{let r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;let s=this.storage.characters({node:t.doc}),i=this.storage.characters({node:e.doc});if(i<=r||s>r&&i>r&&i<=s)return!0;if(s>r&&i>r&&i>s||!e.getMeta("paste"))return!1;let l=e.selection.$head.pos,a=i-r,c=l-a,u=l;return e.deleteRange(c,u),!(this.storage.characters({node:e.doc})>r)}})]}}),W0=F.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[O0(this.options)]}}),_z=F.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new O({key:new P("focus"),props:{decorations:({doc:n,selection:e})=>{let{isEditable:t,isFocused:r}=this.editor,{anchor:s}=e,i=[];if(!t||!r)return X.create(n,[]);let o=0;this.options.mode==="deepest"&&n.descendants((a,c)=>{if(a.isText)return;if(!(s>=c&&s<=c+a.nodeSize-1))return!1;o+=1});let l=0;return n.descendants((a,c)=>{if(a.isText||!(s>=c&&s<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(de.node(c,c+a.nodeSize,{class:this.options.className}))}),X.create(n,i)}}})]}}),j0=F.create({name:"gapCursor",addProseMirrorPlugins(){return[L0()]},extendNodeSchema(n){var e;let t={name:n.name,options:n.options,storage:n.storage};return{allowGapCursor:(e=W(N(n,"allowGapCursor",t)))!=null?e:null}}}),q0="placeholder",_i=new P("tiptap__placeholder"),U0=200;function F0(n){let{editor:e,placeholder:t,dataAttribute:r,pos:s,node:i,isEmptyDoc:o,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=n,u=[a];return o&&u.push(c),de.node(s,s+i.nodeSize,{class:u.join(" "),[r]:typeof t=="function"?t({editor:e,node:i,pos:s,hasAnchor:l}):t})}function V0(n,e){return typeof n=="function"?n(e):n}function NM({editor:n,options:e,dataAttribute:t,doc:r,selection:s}){var i,o;if(!(n.isEditable||!e.showOnlyWhenEditable))return null;let{anchor:a}=s,c=[],u=n.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){let h=r.resolve(a),f=h.depth>0?h.node(1):h.nodeAfter,p=h.depth>0?h.before(1):a;if(f&&f.type.isTextblock&&es(f)){let m=a>=p&&a<=p+f.nodeSize;c.push(F0({editor:n,isEmptyDoc:u,dataAttribute:t,hasAnchor:m,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:V0(e.emptyNodeClass,{editor:n,node:f,pos:p,hasAnchor:m})},node:f,pos:p}))}}else{let h=_i.getState(n.state),f=(i=h?.topPos)!=null?i:0,p=(o=h?.bottomPos)!=null?o:r.content.size;r.nodesBetween(f,p,(m,g)=>{let y=a>=g&&a<=g+m.nodeSize,w=!m.isLeaf&&es(m);return m.type.isTextblock&&(y||!e.showOnlyCurrent)&&w&&c.push(F0({editor:n,isEmptyDoc:u,dataAttribute:t,hasAnchor:y,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:V0(e.emptyNodeClass,{editor:n,node:m,pos:g,hasAnchor:y})},node:m,pos:g})),e.includeChildren})}return X.create(r,c)}function IM(n){return n.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function DM(n){let e=getComputedStyle(n),t=`${e.overflow} ${e.overflowY} ${e.overflowX}`;return/auto|scroll|overlay/.test(t)}function OM(n){let e=n;for(;e;){if(DM(e))return e;let t=e.parentElement;if(!t){let r=e.getRootNode();if(r instanceof ShadowRoot){e=r.host;continue}return window}e=t}return window}function PM(n){return n===window?{top:0,bottom:window.innerHeight}:n.getBoundingClientRect()}function LM({doc:n,view:e,scrollContainer:t}){let r=e.dom.getBoundingClientRect(),s=t?PM(t):{top:0,bottom:window.innerHeight},i=Math.max(r.top,s.top)-U0,o=Math.min(r.bottom,s.bottom)+U0;if(i>=o)return{top:0,bottom:n.content.size};let a=getComputedStyle(e.dom).direction==="rtl"?Math.max(r.right-2,r.left+2):r.left+2,c=e.posAtCoords({left:a,top:i+2}),u=e.posAtCoords({left:a,top:o-2});return{top:c?c.pos:0,bottom:u?u.pos:n.content.size}}var _M={init(){return{topPos:null,bottomPos:null}},apply(n,e){let t=n.getMeta(_i);return t?.positions?{topPos:t.positions.top,bottomPos:t.positions.bottom}:n.docChanged?{topPos:e.topPos!==null?n.mapping.map(e.topPos):null,bottomPos:e.bottomPos!==null?n.mapping.map(e.bottomPos):null}:e}};function BM(n){let e=OM(n.dom),t=()=>{let l=LM({view:n,doc:n.state.doc,scrollContainer:e}),a=_i.getState(n.state);if(a?.topPos===l.top&&a?.bottomPos===l.bottom)return;let c=n.state.tr.setMeta(_i,{positions:l});n.dispatch(c)},r=null,s=0,i=150,o=()=>{r===null&&(r=requestAnimationFrame(()=>{r=null;let l=performance.now();l-s>=i?(s=l,t()):o()}))};return e.addEventListener("scroll",o,{passive:!0}),t(),{update(l,a){n.state.doc.content.size!==a.doc.content.size&&o()},destroy:()=>{r!==null&&cancelAnimationFrame(r),e.removeEventListener("scroll",o)}}}function zM({editor:n,options:e}){let t=e.dataAttribute?`data-${IM(e.dataAttribute)}`:`data-${q0}`;return new O({key:_i,state:_M,view:BM,props:{decorations:({doc:r,selection:s})=>NM({editor:n,options:e,dataAttribute:t,doc:r,selection:s})}})}var zh=F.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:q0,placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[zM({editor:this.editor,options:this.options})]}}),$M=`.ProseMirror:not(.ProseMirror-focused) *::selection { +`),[i,o]=fM(s);if(i.length===0)return;let l=D0(i,0,t);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=i[0])==null?void 0:r.number)||1,items:l,raw:s.slice(0,o).join(` +`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(mM,this.editor.getAttributes(A0)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let n=zt({find:E0,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(n=zt({find:E0,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(A0)}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1],editor:this.editor})),[n]}}),gM=/^\s*(\[([( |x])?\])\s$/,ya=V.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:n=>{let e=n.getAttribute("data-checked");return e===""||e==="true"},renderHTML:n=>({"data-checked":n.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:n,HTMLAttributes:e}){return["li",B(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:n.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(n,e)=>{let t=[];if(n.tokens&&n.tokens.length>0?t.push(e.createNode("paragraph",{},e.parseInline(n.tokens))):n.text?t.push(e.createNode("paragraph",{},[e.createNode("text",{text:n.text})])):t.push(e.createNode("paragraph",{},[])),n.nestedTokens&&n.nestedTokens.length>0){let r=e.parseChildren(n.nestedTokens);t.push(...r)}return e.createNode("taskItem",{checked:n.checked||!1},t)},renderMarkdown:(n,e)=>{var t;let s=`- [${(t=n.attrs)!=null&&t.checked?"x":" "}] `;return wi(n,e,s)},addExtensions(){return this.options.nested?[M0(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let n={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...n,Tab:()=>this.editor.commands.sinkListItem(this.name)}:n},addNodeView(){return({node:n,HTMLAttributes:e,getPos:t,editor:r})=>{let s=document.createElement("li"),i=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),a=document.createElement("div"),c=d=>{var h,f;l.ariaLabel=((f=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:f.call(h,d,l.checked))||`Task item checkbox for ${d.textContent||"empty task item"}`};c(n),i.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}let{checked:h}=d.target;r.isEditable&&typeof t=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{let p=t();if(typeof p!="number")return!1;let m=f.doc.nodeAt(p);return f.setNodeMarkup(p,void 0,{...m?.attrs,checked:h}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(n,h)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,h])=>{s.setAttribute(d,h)}),s.dataset.checked=n.attrs.checked,l.checked=n.attrs.checked,i.append(l,o),s.append(i,a),Object.entries(e).forEach(([d,h])=>{s.setAttribute(d,h)});let u=new Set(Object.keys(e));return{dom:s,contentDOM:a,update:d=>{if(d.type!==this.type)return!1;s.dataset.checked=d.attrs.checked,l.checked=d.attrs.checked,c(d);let h=r.extensionManager.attributes,f=Zr(d,h),p=new Set(Object.keys(f)),m=this.options.HTMLAttributes;return u.forEach(g=>{p.has(g)||(g in m?s.setAttribute(g,m[g]):s.removeAttribute(g))}),Object.entries(f).forEach(([g,y])=>{y==null?g in m?s.setAttribute(g,m[g]):s.removeAttribute(g):s.setAttribute(g,y)}),u=p,!0}}}},addInputRules(){return[zt({find:gM,type:this.type,getAttributes:n=>({checked:n[n.length-1]==="x"})})]}}),wa=V.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:n}){return["ul",B(this.options.HTMLAttributes,n,{"data-type":this.name}),0]},parseMarkdown:(n,e)=>e.createNode("taskList",{},e.parseChildren(n.items||[])),renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`):"",markdownTokenizer:{name:"taskList",level:"block",start(n){var e;let t=(e=n.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return t!==void 0?t:-1},tokenize(n,e,t){let r=i=>{let o=Al(i,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,a)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:t.inlineTokens(l.mainContent),nestedTokens:a}),customNestedParser:r},t);return o?[{type:"taskList",raw:o.raw,items:o.items}]:t.blockTokens(i)},s=Al(n,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:i=>({indentLevel:i[1].length,mainContent:i[4],checked:i[3].toLowerCase()==="x"}),createToken:(i,o)=>({type:"taskItem",raw:"",mainContent:i.mainContent,indentLevel:i.indentLevel,checked:i.checked,text:i.mainContent,tokens:t.inlineTokens(i.mainContent),nestedTokens:o}),customNestedParser:r},t);if(s)return{type:"taskList",raw:s.raw,items:s.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:n})=>n.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),tz=F.create({name:"listKit",addExtensions(){let n=[];return this.options.bulletList!==!1&&n.push(Eh.configure(this.options.bulletList)),this.options.listItem!==!1&&n.push(Mh.configure(this.options.listItem)),this.options.listKeymap!==!1&&n.push(Nh.configure(this.options.listKeymap)),this.options.orderedList!==!1&&n.push(Ih.configure(this.options.orderedList)),this.options.taskItem!==!1&&n.push(ya.configure(this.options.taskItem)),this.options.taskList!==!1&&n.push(wa.configure(this.options.taskList)),n}});var ka=" ",Dh="\xA0",O0=V.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:n}){return["p",B(this.options.HTMLAttributes,n),0]},parseMarkdown:(n,e)=>{let t=n.tokens||[];if(t.length===1&&t[0].type==="image")return e.parseChildren([t[0]]);let r=e.parseInline(t);return t.length===1&&t[0].type==="text"&&(t[0].raw===ka||t[0].text===ka||t[0].raw===Dh||t[0].text===Dh)&&r.length===1&&r[0].type==="text"&&(r[0].text===ka||r[0].text===Dh)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(n,e,t)=>{var r,s;if(!n)return"";let i=Array.isArray(n.content)?n.content:[];if(i.length===0){let o=Array.isArray((r=t?.previousNode)==null?void 0:r.content)?t.previousNode.content:[];return((s=t?.previousNode)==null?void 0:s.type)==="paragraph"&&o.length===0?ka:""}return e.renderChildren(i)},addCommands(){return{setParagraph:()=>({commands:n})=>n.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}});var yM=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,wM=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,P0=lt.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["s",B(this.options.HTMLAttributes,n),0]},markdownTokenName:"del",parseMarkdown:(n,e)=>e.applyMark("strike",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`~~${e.renderChildren(n)}~~`,addCommands(){return{setStrike:()=>({commands:n})=>n.setMark(this.name),toggleStrike:()=>({commands:n})=>n.toggleMark(this.name),unsetStrike:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Bt({find:yM,type:this.type})]},addPasteRules(){return[wt({find:wM,type:this.type})]}});var L0=V.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""});var _0=lt.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["u",B(this.options.HTMLAttributes,n),0]},parseMarkdown(n,e){return e.applyMark(this.name||"underline",e.parseInline(n.tokens||[]))},renderMarkdown(n,e){return`++${e.renderChildren(n)}++`},markdownTokenizer:{name:"underline",level:"inline",start(n){return n.indexOf("++")},tokenize(n,e,t){let s=/^(\+\+)([\s\S]+?)(\+\+)/.exec(n);if(!s)return;let i=s[2].trim();return{type:"underline",raw:s[0],text:i,tokens:t.inlineTokens(i)}}},addCommands(){return{setUnderline:()=>({commands:n})=>n.setMark(this.name),toggleUnderline:()=>({commands:n})=>n.toggleMark(this.name),unsetUnderline:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function B0(n={}){return new O({view(e){return new Oh(e,n)}})}var Oh=class{constructor(e,t){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=t.width)!==null&&r!==void 0?r:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(s=>{let i=o=>{this[s](o)};return e.dom.addEventListener(s,i),{name:s,handler:i}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,r,s=this.editorView.dom,i=s.getBoundingClientRect(),o=i.width/s.offsetWidth,l=i.height/s.offsetHeight;if(t){let d=e.nodeBefore,h=e.nodeAfter;if(d||h){let f=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(f){let p=f.getBoundingClientRect(),m=d?p.bottom:p.top;d&&h&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*o;r={left:d.left-h,right:d.left+h,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),h=d.width/a.offsetWidth,f=d.height/a.offsetHeight;c=d.left-a.scrollLeft*h,u=d.top-a.scrollTop*f}this.element.style.left=(r.left-c)/o+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),s=r&&r.type.spec.disableDropCursor,i=typeof s=="function"?s(this.editorView,t,e):s;if(t&&!i){let o=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=qo(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var $e=class n extends N{constructor(e){super(e,e)}map(e,t){let r=e.resolve(t.map(this.head));return n.valid(r)?new n(r):N.near(r)}content(){return S.empty}eq(e){return e instanceof n&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new n(e.resolve(t.pos))}getBookmark(){return new Ph(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!kM(e)||!bM(e))return!1;let r=t.type.spec.allowGapCursor;if(r!=null)return r;let s=t.contentMatchAt(e.index()).defaultType;return s&&s.isTextblock}static findGapCursorFrom(e,t,r=!1){e:for(;;){if(!r&&n.valid(e))return e;let s=e.pos,i=null;for(let o=e.depth;;o--){let l=e.node(o);if(t>0?e.indexAfter(o)0){i=l.child(t>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;s+=t;let a=e.doc.resolve(s);if(n.valid(a))return a}for(;;){let o=t>0?i.firstChild:i.lastChild;if(!o){if(i.isAtom&&!i.isText&&!M.isSelectable(i)){e=e.doc.resolve(s+i.nodeSize*t),r=!1;continue e}break}i=o,s+=t;let l=e.doc.resolve(s);if(n.valid(l))return l}return null}}};$e.prototype.visible=!1;$e.findFrom=$e.findGapCursorFrom;N.jsonID("gapcursor",$e);var Ph=class n{constructor(e){this.pos=e}map(e){return new n(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return $e.valid(t)?new $e(t):N.near(t)}};function z0(n){return n.isAtom||n.spec.isolating||n.spec.createGapCursor}function kM(n){for(let e=n.depth;e>=0;e--){let t=n.index(e),r=n.node(e);if(t==0){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(t-1);;s=s.lastChild){if(s.childCount==0&&!s.inlineContent||z0(s.type))return!0;if(s.inlineContent)return!1}}return!0}function bM(n){for(let e=n.depth;e>=0;e--){let t=n.indexAfter(e),r=n.node(e);if(t==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(t);;s=s.firstChild){if(s.childCount==0&&!s.inlineContent||z0(s.type))return!0;if(s.inlineContent)return!1}}return!0}function $0(){return new O({props:{decorations:CM,createSelectionBetween(n,e,t){return e.pos==t.pos&&$e.valid(t)?new $e(t):null},handleClick:SM,handleKeyDown:xM,handleDOMEvents:{beforeinput:vM}}})}var xM=hi({ArrowLeft:ba("horiz",-1),ArrowRight:ba("horiz",1),ArrowUp:ba("vert",-1),ArrowDown:ba("vert",1)});function ba(n,e){let t=n=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,s,i){let o=r.selection,l=e>0?o.$to:o.$from,a=o.empty;if(o instanceof A){if(!i.endOfTextblock(t)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=$e.findGapCursorFrom(l,e,a);return c?(s&&s(r.tr.setSelection(new $e(c))),!0):!1}}function SM(n,e,t){if(!n||!n.editable)return!1;let r=n.state.doc.resolve(e);if(!$e.valid(r))return!1;let s=n.posAtCoords({left:t.clientX,top:t.clientY});return s&&s.inside>-1&&M.isSelectable(n.state.doc.nodeAt(s.inside))?!1:(n.dispatch(n.state.tr.setSelection(new $e(r))),!0)}function vM(n,e){if(e.inputType!="insertCompositionText"||!(n.state.selection instanceof $e))return!1;let{$from:t}=n.state.selection,r=t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);if(!r)return!1;let s=k.empty;for(let o=r.length-1;o>=0;o--)s=k.from(r[o].createAndFill(null,s));let i=n.state.tr.replace(t.pos,t.pos,new S(s,0,0));return i.setSelection(A.near(i.doc.resolve(t.pos+1))),n.dispatch(i),!1}function CM(n){if(!(n.selection instanceof $e))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",X.create(n.doc,[de.widget(n.selection.head,e,{key:"gapcursor"})])}var xa=200,De=function(){};De.prototype.append=function(e){return e.length?(e=De.from(e),!this.length&&e||e.length=t?De.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};De.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};De.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};De.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var s=[];return this.forEach(function(i,o){return s.push(e(i,o))},t,r),s};De.from=function(e){return e instanceof De?e:e&&e.length?new U0(e):De.empty};var U0=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(s,i){return s==0&&i==this.length?this:new e(this.values.slice(s,i))},e.prototype.getInner=function(s){return this.values[s]},e.prototype.forEachInner=function(s,i,o,l){for(var a=i;a=o;a--)if(s(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(s){if(this.length+s.length<=xa)return new e(this.values.concat(s.flatten()))},e.prototype.leafPrepend=function(s){if(this.length+s.length<=xa)return new e(s.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(De);De.empty=new U0([]);var TM=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(s-l,0),Math.min(this.length,i)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,s,i,o){var l=this.left.length;if(s>l&&this.right.forEachInvertedInner(r,s-l,Math.max(i,l)-l,o+l)===!1||i=i?this.right.slice(r-i,s-i):this.left.slice(r,i).append(this.right.slice(0,s-i))},e.prototype.leafAppend=function(r){var s=this.right.leafAppend(r);if(s)return new e(this.left,s)},e.prototype.leafPrepend=function(r){var s=this.left.leafPrepend(r);if(s)return new e(s,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(De),Lh=De;var AM=500,fr=class n{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let s,i;t&&(s=this.remapping(r,this.items.length),i=s.maps.length);let o=e.tr,l,a,c=[],u=[];return this.items.forEach((d,h)=>{if(!d.step){s||(s=this.remapping(r,h+1),i=s.maps.length),i--,u.push(d);return}if(s){u.push(new Ft(d.map));let f=d.step.map(s.slice(i)),p;f&&o.maybeStep(f).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new Ft(p,void 0,void 0,c.length+u.length))),i--,p&&s.appendMap(p,i)}else o.maybeStep(d.step);if(d.selection)return l=s?d.selection.map(s.slice(i)):d.selection,a=new n(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,s){let i=[],o=this.eventCount,l=this.items,a=!s&&l.length?l.get(l.length-1):null;for(let u=0;uMM&&(l=EM(l,c),o-=c),new n(l.append(i),o)}remapping(e,t){let r=new Gs;return this.items.forEach((s,i)=>{let o=s.mirrorOffset!=null&&i-s.mirrorOffset>=e?r.maps.length-s.mirrorOffset:void 0;r.appendMap(s.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new n(this.items.append(e.map(t=>new Ft(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],s=Math.max(0,this.items.length-t),i=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(h=>{h.selection&&l--},s);let a=t;this.items.forEach(h=>{let f=i.getMirror(--a);if(f==null)return;o=Math.min(o,f);let p=i.maps[f];if(h.step){let m=e.steps[f].invert(e.docs[f]),g=h.selection&&h.selection.map(i.slice(a+1,f));g&&l++,r.push(new Ft(p,m,g))}else r.push(new Ft(p))},s);let c=[];for(let h=t;hAM&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,s=[],i=0;return this.items.forEach((o,l)=>{if(l>=e)s.push(o),o.selection&&i++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let u=o.selection&&o.selection.map(t.slice(r));u&&i++;let d=new Ft(c.invert(),a,u),h,f=s.length-1;(h=s.length&&s[f].merge(d))?s[f]=h:s.push(d)}}else o.map&&r--},this.items.length,0),new n(Lh.from(s.reverse()),i)}};fr.empty=new fr(Lh.empty,0);function EM(n,e){let t;return n.forEach((r,s)=>{if(r.selection&&e--==0)return t=s,!1}),n.slice(t)}var Ft=class n{constructor(e,t,r,s){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=s}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new n(t.getMap().invert(),t,this.selection)}}},Vt=class{constructor(e,t,r,s,i){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=s,this.prevComposition=i}},MM=20;function RM(n,e,t,r){let s=t.getMeta(hr),i;if(s)return s.historyState;t.getMeta(DM)&&(n=new Vt(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(hr))return o.getMeta(hr).redo?new Vt(n.done.addTransform(t,void 0,r,Sa(e)),n.undone,F0(t.mapping.maps),n.prevTime,n.prevComposition):new Vt(n.done,n.undone.addTransform(t,void 0,r,Sa(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!NM(t,n.prevRanges)),c=o?_h(n.prevRanges,t.mapping):F0(t.mapping.maps);return new Vt(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,Sa(e)),fr.empty,c,t.time,l??n.prevComposition)}else return(i=t.getMeta("rebased"))?new Vt(n.done.rebased(t,i),n.undone.rebased(t,i),_h(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Vt(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),_h(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function NM(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,s)=>{for(let i=0;i=e[i]&&(t=!0)}),t}function F0(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,s,i,o)=>e.push(i,o));return e}function _h(n,e){if(!n)return null;let t=[];for(let r=0;r{let s=hr.getState(t);if(!s||(n?s.undone:s.done).eventCount==0)return!1;if(r){let i=IM(s,t,n);i&&r(e?i.scrollIntoView():i)}return!0}}var zh=va(!1,!0),$h=va(!0,!0),Ez=va(!1,!1),Mz=va(!0,!1);var Pz=F.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:n=>n.length,wordCounter:n=>n.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=n=>{let e=n?.node||this.editor.state.doc;if((n?.mode||this.options.mode)==="textSize"){let r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=n=>{let e=n?.node||this.editor.state.doc,t=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(t)}},addProseMirrorPlugins(){let n=!1;return[new O({key:new P("characterCount"),appendTransaction:(e,t,r)=>{if(n)return;let s=this.options.limit,i=this.options.autoTrim;if(s==null||s===0||i===!1){n=!0;return}let o=this.storage.characters({node:r.doc});if(o>s){let l=o-s,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${s} characters. Content was automatically trimmed.`);let u=r.tr.deleteRange(a,c);return n=!0,u}n=!0},filterTransaction:(e,t)=>{let r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;let s=this.storage.characters({node:t.doc}),i=this.storage.characters({node:e.doc});if(i<=r||s>r&&i>r&&i<=s)return!0;if(s>r&&i>r&&i>s||!e.getMeta("paste"))return!1;let l=e.selection.$head.pos,a=i-r,c=l-a,u=l;return e.deleteRange(c,u),!(this.storage.characters({node:e.doc})>r)}})]}}),K0=F.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[B0(this.options)]}}),Uz=F.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new O({key:new P("focus"),props:{decorations:({doc:n,selection:e})=>{let{isEditable:t,isFocused:r}=this.editor,{anchor:s}=e,i=[];if(!t||!r)return X.create(n,[]);let o=0;this.options.mode==="deepest"&&n.descendants((a,c)=>{if(a.isText)return;if(!(s>=c&&s<=c+a.nodeSize-1))return!1;o+=1});let l=0;return n.descendants((a,c)=>{if(a.isText||!(s>=c&&s<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(de.node(c,c+a.nodeSize,{class:this.options.className}))}),X.create(n,i)}}})]}}),Y0=F.create({name:"gapCursor",addProseMirrorPlugins(){return[$0()]},extendNodeSchema(n){var e;let t={name:n.name,options:n.options,storage:n.storage};return{allowGapCursor:(e=W(I(n,"allowGapCursor",t)))!=null?e:null}}}),G0="placeholder",zi=new P("tiptap__placeholder"),W0=200;function j0(n){let{editor:e,placeholder:t,dataAttribute:r,pos:s,node:i,isEmptyDoc:o,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=n,u=[a];return o&&u.push(c),de.node(s,s+i.nodeSize,{class:u.join(" "),[r]:typeof t=="function"?t({editor:e,node:i,pos:s,hasAnchor:l}):t})}function q0(n,e){return typeof n=="function"?n(e):n}function OM({editor:n,options:e,dataAttribute:t,doc:r,selection:s}){var i,o;if(!(n.isEditable||!e.showOnlyWhenEditable))return null;let{anchor:a}=s,c=[],u=n.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){let h=r.resolve(a),f=h.depth>0?h.node(1):h.nodeAfter,p=h.depth>0?h.before(1):a;if(f&&f.type.isTextblock&&es(f)){let m=a>=p&&a<=p+f.nodeSize;c.push(j0({editor:n,isEmptyDoc:u,dataAttribute:t,hasAnchor:m,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:q0(e.emptyNodeClass,{editor:n,node:f,pos:p,hasAnchor:m})},node:f,pos:p}))}}else{let h=zi.getState(n.state),f=(i=h?.topPos)!=null?i:0,p=(o=h?.bottomPos)!=null?o:r.content.size;r.nodesBetween(f,p,(m,g)=>{let y=a>=g&&a<=g+m.nodeSize,w=!m.isLeaf&&es(m);return m.type.isTextblock&&(y||!e.showOnlyCurrent)&&w&&c.push(j0({editor:n,isEmptyDoc:u,dataAttribute:t,hasAnchor:y,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:q0(e.emptyNodeClass,{editor:n,node:m,pos:g,hasAnchor:y})},node:m,pos:g})),e.includeChildren})}return X.create(r,c)}function PM(n){return n.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function LM(n){let e=getComputedStyle(n),t=`${e.overflow} ${e.overflowY} ${e.overflowX}`;return/auto|scroll|overlay/.test(t)}function _M(n){let e=n;for(;e;){if(LM(e))return e;let t=e.parentElement;if(!t){let r=e.getRootNode();if(r instanceof ShadowRoot){e=r.host;continue}return window}e=t}return window}function BM(n){return n===window?{top:0,bottom:window.innerHeight}:n.getBoundingClientRect()}function zM({doc:n,view:e,scrollContainer:t}){let r=e.dom.getBoundingClientRect(),s=t?BM(t):{top:0,bottom:window.innerHeight},i=Math.max(r.top,s.top)-W0,o=Math.min(r.bottom,s.bottom)+W0;if(i>=o)return{top:0,bottom:n.content.size};let a=getComputedStyle(e.dom).direction==="rtl"?Math.max(r.right-2,r.left+2):r.left+2,c=e.posAtCoords({left:a,top:i+2}),u=e.posAtCoords({left:a,top:o-2});return{top:c?c.pos:0,bottom:u?u.pos:n.content.size}}var $M={init(){return{topPos:null,bottomPos:null}},apply(n,e){let t=n.getMeta(zi);return t?.positions?{topPos:t.positions.top,bottomPos:t.positions.bottom}:n.docChanged?{topPos:e.topPos!==null?n.mapping.map(e.topPos):null,bottomPos:e.bottomPos!==null?n.mapping.map(e.bottomPos):null}:e}};function UM(n){let e=_M(n.dom),t=()=>{let l=zM({view:n,doc:n.state.doc,scrollContainer:e}),a=zi.getState(n.state);if(a?.topPos===l.top&&a?.bottomPos===l.bottom)return;let c=n.state.tr.setMeta(zi,{positions:l});n.dispatch(c)},r=null,s=0,i=150,o=()=>{r===null&&(r=requestAnimationFrame(()=>{r=null;let l=performance.now();l-s>=i?(s=l,t()):o()}))};return e.addEventListener("scroll",o,{passive:!0}),t(),{update(l,a){n.state.doc.content.size!==a.doc.content.size&&o()},destroy:()=>{r!==null&&cancelAnimationFrame(r),e.removeEventListener("scroll",o)}}}function FM({editor:n,options:e}){let t=e.dataAttribute?`data-${PM(e.dataAttribute)}`:`data-${G0}`;return new O({key:zi,state:$M,view:UM,props:{decorations:({doc:r,selection:s})=>OM({editor:n,options:e,dataAttribute:t,doc:r,selection:s})}})}var Uh=F.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:G0,placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[FM({editor:this.editor,options:this.options})]}}),VM=`.ProseMirror:not(.ProseMirror-focused) *::selection { background: transparent; } .ProseMirror:not(.ProseMirror-focused) *::-moz-selection { background: transparent; -}`,Kz=F.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){let{editor:n,options:e}=this;return n.options.injectCSS&&typeof document<"u"&&_d($M,n.options.injectNonce,"selection"),[new O({key:new P("selection"),props:{decorations(t){return t.selection.empty||n.isFocused||!n.isEditable||xl(t.selection)||n.view.dragging?null:X.create(t.doc,[de.inline(t.selection.from,t.selection.to,{class:e.className})])}}})]}}),UM="skipTrailingNode";function H0({types:n,node:e}){return e&&Array.isArray(n)&&n.includes(e.type)||e?.type===n}var J0=F.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var n;let e=new P(this.name),t=this.options.node||((n=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:n.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,s])=>s).filter(s=>(this.options.notAfter||[]).concat(t).includes(s.name));return[new O({key:e,appendTransaction:(s,i,o)=>{let{doc:l,tr:a,schema:c}=o,u=e.getState(o),d=l.content.size,h=c.nodes[t];if(!s.some(f=>f.getMeta(UM))&&u)return a.insert(d,h.create())},state:{init:(s,i)=>{let o=i.tr.doc.lastChild;return!H0({node:o,types:r})},apply:(s,i)=>{if(!s.docChanged||s.getMeta("__uniqueIDTransaction"))return i;let o=s.doc.lastChild;return!H0({node:o,types:r})}}})]}}),K0=F.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:n,dispatch:e})=>_h(n,e),redo:()=>({state:n,dispatch:e})=>Bh(n,e)}},addProseMirrorPlugins(){return[$0(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});var FM=F.create({name:"starterKit",addExtensions(){var n,e,t,r;let s=[];return this.options.bold!==!1&&s.push(Gw.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(Yw.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(Th.configure(this.options.bulletList)),this.options.code!==!1&&s.push(Xw.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(Qw.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(Zw.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(W0.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(j0.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(e0.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(t0.configure(this.options.heading)),this.options.undoRedo!==!1&&s.push(K0.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&s.push(n0.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(r0.configure(this.options.italic)),this.options.listItem!==!1&&s.push(Ah.configure(this.options.listItem)),this.options.listKeymap!==!1&&s.push(Mh.configure((n=this.options)==null?void 0:n.listKeymap)),this.options.link!==!1&&s.push(Sh.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&s.push(Rh.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(R0.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(N0.configure(this.options.strike)),this.options.text!==!1&&s.push(I0.configure(this.options.text)),this.options.underline!==!1&&s.push(D0.configure((t=this.options)==null?void 0:t.underline)),this.options.trailingNode!==!1&&s.push(J0.configure((r=this.options)==null?void 0:r.trailingNode)),s}}),Y0=FM;var ye=()=>new Map,va=n=>{let e=ye();return n.forEach((t,r)=>{e.set(r,t)}),e},Ge=(n,e,t)=>{let r=n.get(e);return r===void 0&&n.set(e,r=t()),r},G0=(n,e)=>{let t=[];for(let[r,s]of n)t.push(e(s,r));return t},X0=(n,e)=>{for(let[t,r]of n)if(e(r,t))return!0;return!1};var tt=()=>new Set;var Ca=n=>n[n.length-1];var Q0=(n,e)=>{for(let t=0;t{for(let t=0;t{for(let t=0;t{let t=new Array(n);for(let r=0;r{this.off(e,r),t(...s)};this.on(e,r)}off(e,t){let r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e))}emit(e,t){return Ct((this._observers.get(e)||ye()).values()).forEach(r=>r(...t))}destroy(){this._observers=ye()}},Aa=class{constructor(){this._observers=ye()}on(e,t){Ge(this._observers,e,tt).add(t)}once(e,t){let r=(...s)=>{this.off(e,r),t(...s)};this.on(e,r)}off(e,t){let r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e))}emit(e,t){return Ct((this._observers.get(e)||ye()).values()).forEach(r=>r(...t))}destroy(){this._observers=ye()}};var we=Math.floor;var gr=Math.abs;var Tt=(n,e)=>nn>e?n:e,k2=Number.isNaN,ek=Math.pow;var Ea=n=>n!==0?n<0:1/n<0;var cs=Number.MAX_SAFE_INTEGER,$h=Number.MIN_SAFE_INTEGER,b2=1<<31;var tk=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&we(n)===n),x2=Number.isNaN,S2=Number.parseInt;var Ui=String.fromCharCode,VM=String.fromCodePoint,v2=Ui(65535),HM=n=>n.toLowerCase(),WM=/^\s*/g,jM=n=>n.replace(WM,""),qM=/([A-Z])/g,Fh=(n,e)=>jM(n.replace(qM,t=>`${e}${HM(t)}`));var JM=n=>{let e=unescape(encodeURIComponent(n)),t=e.length,r=new Uint8Array(t);for(let s=0;sds.encode(n),nk=ds?KM:JM;var us=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});us&&us.decode(new Uint8Array).length===1&&(us=null);var rk=(n,e)=>Z0(e,()=>n).join("");var yr=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},fe=()=>new yr,ak=n=>{let e=fe();return n(e),Y(e)},Ra=n=>{let e=n.cpos;for(let t=0;t{let e=new Uint8Array(Ra(n)),t=0;for(let r=0;r{let t=n.cbuf.length;t-n.cpos{let t=n.cbuf.length;n.cpos===t&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(t*2),n.cpos=0),n.cbuf[n.cpos++]=e};var Na=Te;var D=(n,e)=>{for(;e>127;)Te(n,128|127&e),e=we(e/128);Te(n,127&e)},Ia=(n,e)=>{let t=Ea(e);for(t&&(e=-e),Te(n,(e>63?128:0)|(t?64:0)|63&e),e=we(e/64);e>0;)Te(n,(e>127?128:0)|127&e),e=we(e/128)},Vh=new Uint8Array(3e4),GM=Vh.length/3,XM=(n,e)=>{if(e.length{let t=unescape(encodeURIComponent(e)),r=t.length;D(n,r);for(let s=0;s{let t=n.cbuf.length,r=n.cpos,s=Tt(t-r,e.length),i=e.length-s;n.cbuf.set(e.subarray(0,s),r),n.cpos+=s,i>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(xt(t*2,i)),n.cbuf.set(e.subarray(s)),n.cpos=i)},Z=(n,e)=>{D(n,e.byteLength),Hi(n,e)},Hh=(n,e)=>{YM(n,e);let t=new DataView(n.cbuf.buffer,n.cpos,e);return n.cpos+=e,t},ZM=(n,e)=>Hh(n,4).setFloat32(0,e,!1),eR=(n,e)=>Hh(n,8).setFloat64(0,e,!1),tR=(n,e)=>Hh(n,8).setBigInt64(0,e,!1);var ik=new DataView(new ArrayBuffer(4)),nR=n=>(ik.setFloat32(0,n),ik.getFloat32(0)===n),Dn=(n,e)=>{switch(typeof e){case"string":Te(n,119),fn(n,e);break;case"number":tk(e)&&gr(e)<=2147483647?(Te(n,125),Ia(n,e)):nR(e)?(Te(n,124),ZM(n,e)):(Te(n,123),eR(n,e));break;case"bigint":Te(n,122),tR(n,e);break;case"object":if(e===null)Te(n,126);else if(dn(e)){Te(n,117),D(n,e.length);for(let t=0;t0&&D(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};var ok=n=>{n.count>0&&(Ia(n.encoder,n.count===1?n.s:-n.s),n.count>1&&D(n.encoder,n.count-2))},wr=class{constructor(){this.encoder=new yr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ok(this),this.count=1,this.s=e)}toUint8Array(){return ok(this),Y(this.encoder)}};var lk=n=>{if(n.count>0){let e=n.diff*2+(n.count===1?0:1);Ia(n.encoder,e),n.count>1&&D(n.encoder,n.count-2)}},fs=class{constructor(){this.encoder=new yr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(lk(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return lk(this),Y(this.encoder)}},Ma=class{constructor(){this.sarr=[],this.s="",this.lensE=new wr}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){let e=new yr;return this.sarr.push(this.s),this.s="",fn(e,this.sarr.join("")),Hi(e,this.lensE.toUint8Array()),Y(e)}};var at=n=>new Error(n),Xe=()=>{throw at("Method unimplemented")},Ae=()=>{throw at("Unexpected case")};var ck=at("Unexpected end of array"),uk=at("Integer out of Range"),ps=class{constructor(e){this.arr=e,this.pos=0}},Et=n=>new ps(n),dk=n=>n.pos!==n.arr.length;var rR=(n,e)=>{let t=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,e);return n.pos+=e,t},ke=n=>rR(n,L(n));var kr=n=>n.arr[n.pos++];var L=n=>{let e=0,t=1,r=n.arr.length;for(;n.poscs)throw uk}throw ck},Pa=n=>{let e=n.arr[n.pos++],t=e&63,r=64,s=(e&64)>0?-1:1;if((e&128)===0)return s*t;let i=n.arr.length;for(;n.poscs)throw uk}throw ck};var sR=n=>{let e=L(n);if(e===0)return"";{let t=String.fromCodePoint(kr(n));if(--e<100)for(;e--;)t+=String.fromCodePoint(kr(n));else for(;e>0;){let r=e<1e4?e:1e4,s=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,t+=String.fromCodePoint.apply(null,s),e-=r}return decodeURIComponent(escape(t))}},iR=n=>us.decode(ke(n)),At=us?iR:sR;var Wh=(n,e)=>{let t=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,e);return n.pos+=e,t},oR=n=>Wh(n,4).getFloat32(0,!1),lR=n=>Wh(n,8).getFloat64(0,!1),aR=n=>Wh(n,8).getBigInt64(0,!1);var cR=[n=>{},n=>null,Pa,oR,lR,aR,n=>!1,n=>!0,At,n=>{let e=L(n),t={};for(let r=0;r{let e=L(n),t=[];for(let r=0;rcR[127-kr(n)](n),ji=class extends ps{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),dk(this)?this.count=L(this)+1:this.count=-1),this.count--,this.s}};var br=class extends ps{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Pa(this);let e=Ea(this.s);this.count=1,e&&(this.s=-this.s,this.count=L(this)+2)}return this.count--,this.s}};var gs=class extends ps{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Pa(this),t=e&1;this.diff=we(e/2),this.count=1,t&&(this.count=L(this)+2)}return this.s+=this.diff,this.count--,this.s}},Oa=class{constructor(e){this.decoder=new br(e),this.str=At(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};var A2=crypto.subtle,hk=crypto.getRandomValues.bind(crypto);var uR=Math.random,jh=()=>hk(new Uint32Array(1))[0];var fk=n=>n[we(uR()*n.length)],dR="10000000-1000-4000-8000"+-1e11,pk=()=>dR.replace(/[018]/g,n=>(n^jh()&15>>n/4).toString(16));var ct=Date.now;var qh=n=>new Promise(n);var R2=Promise.all.bind(Promise);var Jh=n=>n===void 0?null:n;var Kh=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},gk=new Kh,Yh=!0;try{typeof localStorage<"u"&&localStorage&&(gk=localStorage,Yh=!1)}catch{}var _a=gk,yk=n=>Yh||addEventListener("storage",n),wk=n=>Yh||removeEventListener("storage",n);var xr=Symbol("Equality"),Ba=(n,e)=>n===e||!!n?.[xr]?.(e)||!1;var bk=n=>typeof n=="object",xk=Object.assign,Xh=Object.keys;var Sk=(n,e)=>{for(let t in n)e(n[t],t)},vk=(n,e)=>{let t=[];for(let r in n)t.push(e(n[r],r));return t};var Ji=n=>Xh(n).length;var Ck=n=>{for(let e in n)return!1;return!0},Pn=(n,e)=>{for(let t in n)if(!e(n[t],t))return!1;return!0},Ki=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),Qh=(n,e)=>n===e||Ji(n)===Ji(e)&&Pn(n,(t,r)=>(t!==void 0||Ki(e,r))&&Ba(e[r],t)),pR=Object.freeze,Zh=n=>{for(let e in n){let t=n[e];(typeof t=="object"||typeof t=="function")&&Zh(n[e])}return pR(n)};var Gi=(n,e,t=0)=>{try{for(;tn;var Ln=(n,e)=>{if(n===e)return!0;if(n==null||e==null||n.constructor!==e.constructor&&(n.constructor||Object)!==(e.constructor||Object))return!1;if(n[xr]!=null)return n[xr](e);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),e=new Uint8Array(e);case Uint8Array:{if(n.byteLength!==e.byteLength)return!1;for(let t=0;te.includes(n);var pn=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ys=typeof window<"u"&&typeof document<"u"&&!pn,N2=typeof navigator<"u"?/Mac/.test(navigator.platform):!1,Ht,mR=[],gR=()=>{if(Ht===void 0)if(pn){Ht=ye();let n=process.argv,e=null;for(let t=0;t{if(n.length!==0){let[e,t]=n.split("=");Ht.set(`--${Fh(e,"-")}`,t),Ht.set(`-${Fh(e,"-")}`,t)}})):Ht=ye();return Ht},ef=n=>gR().has(n);var Xi=n=>pn?Jh(process.env[n.toUpperCase().replaceAll("-","_")]):Jh(_a.getItem(n));var Ek=n=>ef("--"+n)||Xi(n)!==null,Mk=Ek("production"),yR=pn&&Ak(process.env.FORCE_COLOR,["true","1","2"]),Rk=yR||!ef("--no-colors")&&!Ek("no-color")&&(!pn||process.stdout.isTTY)&&(!pn||ef("--color")||Xi("COLORTERM")!==null||(Xi("TERM")||"").includes("color"));var Nk=n=>new Uint8Array(n),wR=(n,e,t)=>new Uint8Array(n,e,t),Ik=n=>new Uint8Array(n),kR=n=>{let e="";for(let t=0;tBuffer.from(n.buffer,n.byteOffset,n.byteLength).toString("base64"),xR=n=>{let e=atob(n),t=Nk(e.length);for(let r=0;r{let e=Buffer.from(n,"base64");return wR(e.buffer,e.byteOffset,e.byteLength)},$a=ys?kR:bR,Dk=ys?xR:SR;var Ok=n=>{let e=Nk(n.byteLength);return e.set(n),e},Pk=n=>ak(e=>Dn(e,n));var nf=class{constructor(e,t){this.left=e,this.right=t}},Wt=(n,e)=>new nf(n,e);var rf=n=>n.next()>=.5,Ua=(n,e,t)=>we(n.next()*(t+1-e)+e);var sf=(n,e,t)=>we(n.next()*(t+1-e)+e);var of=(n,e,t)=>sf(n,e,t);var CR=n=>Ui(of(n,97,122)),Lk=(n,e=0,t=20)=>{let r=of(n,e,t),s="";for(let i=0;ie[of(n,0,e.length-1)];var AR=Symbol("0schema"),lf=class{constructor(){this._rerrs=[]}extend(e,t,r,s=null){this._rerrs.push({path:e,expected:t,has:r,message:s})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let r=this._rerrs[t];e.push(rk(" ",(this._rerrs.length-t)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(` -`)}},af=(n,e)=>n===e?!0:n==null||e==null||n.constructor!==e.constructor?!1:n[xr]?Ba(n,e):dn(n)?Ta(n,t=>zi(e,r=>af(t,r))):bk(n)?Pn(n,(t,r)=>af(t,e[r])):!1,Oe=class{static _dilutes=!1;extends(e){let[t,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,t]=[t,r]),af(t,r)}equals(e){return this.constructor===e.constructor&&Ln(this.shape,e.shape)}[AR](){return!0}[xr](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){Xe()}get nullable(){return vs(this,Za)}get optional(){return new Va(this)}cast(e){return _k(e,this),e}expect(e){return _k(e,this),e}},Qi=class extends Oe{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let r=e?.constructor===this.shape&&(this._c==null||this._c(e));return!r&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor!==this.shape?"Constructor match failed":"Check failed"),r}},pe=(n,e=null)=>new Qi(n,e),D2=pe(Qi),Zi=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=this.shape(e);return!r&&t?.extend(null,"custom prop",e?.constructor.name,"failed to check custom prop"),r}},be=n=>new Zi(n),O2=pe(Zi),xs=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=this.shape.some(s=>s===e);return!r&&t?.extend(null,this.shape.join(" | "),e.toString()),r}},Xa=(...n)=>new xs(n),Bk=pe(xs),ER=RegExp.escape||(n=>n.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),zk=n=>{if(Ss.check(n))return[ER(n)];if(Bk.check(n))return n.shape.map(e=>e+"");if(Hk.check(n))return["[+-]?\\d+.?\\d*"];if(Wk.check(n))return[".*"];if(Ya.check(n))return n.shape.map(zk).flat(1);Ae()},cf=class extends Oe{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(zk).map(t=>`(${t.join("|")})`).join("")+"$")}check(e,t){let r=this._r.exec(e)!=null;return!r&&t?.extend(null,this._r.toString(),e.toString(),"String doesn't match string template."),r}};var P2=pe(cf),MR=Symbol("optional"),Va=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=e===void 0||this.shape.check(e);return!r&&t?.extend(null,"undefined (optional)","()"),r}get[MR](){return!0}},RR=pe(Va),Ha=class extends Oe{check(e,t){return t?.extend(null,"never",typeof e),!1}},L2=new Ha,_2=pe(Ha),Wa=class n extends Oe{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new n(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,"object","null"),!1):Pn(this.shape,(r,s)=>{let i=this._isPartial&&!Ki(e,s)||r.check(e[s],t);return!i&&t?.extend(s.toString(),r.toString(),typeof e[s],"Object property does not match"),i})}},NR=n=>new Wa(n),IR=pe(Wa),DR=be(n=>n!=null&&(n.constructor===Object||n.constructor==null)),ja=class extends Oe{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&Pn(e,(r,s)=>{let i=this.shape.keys.check(s,t);return!i&&t?.extend(s+"","Record",typeof e,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(r,t)})}},$k=(n,e)=>new ja(n,e),OR=pe(ja),qa=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&Pn(this.shape,(r,s)=>{let i=r.check(e[s],t);return!i&&t?.extend(s.toString(),"Tuple",typeof r),i})}},PR=(...n)=>new qa(n),B2=pe(qa),Ja=class extends Oe{constructor(e){super(),this.shape=e.length===1?e[0]:new eo(e)}check(e,t){let r=dn(e)&&Ta(e,s=>this.shape.check(s));return!r&&t?.extend(null,"Array",""),r}},Uk=(...n)=>new Ja(n),LR=pe(Ja),_R=be(n=>dn(n)),Ka=class extends Oe{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&t?.extend(null,this.shape.name,e?.constructor.name),r}},BR=(n,e=null)=>new Ka(n,e),z2=pe(Ka),zR=BR(Oe),uf=class extends Oe{constructor(e){super(),this.len=e.length-1,this.args=PR(...e.slice(-1)),this.res=e[this.len]}check(e,t){let r=e.constructor===Function&&e.length<=this.len;return!r&&t?.extend(null,"function",typeof e),r}};var $R=pe(uf),UR=be(n=>typeof n=="function"),df=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=Ta(this.shape,s=>s.check(e,t));return!r&&t?.extend(null,"Intersectinon",typeof e),r}};var $2=pe(df,n=>n.shape.length>0),eo=class extends Oe{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let r=zi(this.shape,s=>s.check(e,t));return t?.extend(null,"Union",typeof e),r}},vs=(...n)=>n.findIndex(e=>Ya.check(e))>=0?vs(...n.map(e=>to(e)).map(e=>Ya.check(e)?e.shape:[e]).flat(1)):n.length===1?n[0]:new eo(n),Ya=pe(eo),Fk=()=>!0,Ga=be(Fk),FR=pe(Zi,n=>n.shape===Fk),ff=be(n=>typeof n=="bigint"),VR=be(n=>n===ff),Vk=be(n=>typeof n=="symbol"),U2=be(n=>n===Vk),bs=be(n=>typeof n=="number"),Hk=be(n=>n===bs),Ss=be(n=>typeof n=="string"),Wk=be(n=>n===Ss),Qa=be(n=>typeof n=="boolean"),HR=be(n=>n===Qa),jk=Xa(void 0),F2=pe(xs,n=>n.shape.length===1&&n.shape[0]===void 0),V2=Xa(void 0);var Za=Xa(null),WR=pe(xs,n=>n.shape.length===1&&n.shape[0]===null),H2=pe(Uint8Array),W2=pe(Qi,n=>n.shape===Uint8Array),jR=vs(bs,Ss,Za,jk,ff,Qa,Vk),j2=(()=>{let n=Uk(Ga),e=$k(Ss,Ga),t=vs(bs,Ss,Za,Qa,n,e);return n.shape=t,e.shape.values=t,t})(),to=n=>{if(zR.check(n))return n;if(DR.check(n)){let e={};for(let t in n)e[t]=to(n[t]);return NR(e)}else{if(_R.check(n))return vs(...n.map(to));if(jR.check(n))return Xa(n);if(UR.check(n))return pe(n)}Ae()},_k=Mk?()=>{}:(n,e)=>{let t=new lf;if(!e.check(n,t))throw at(`Expected value to be of type ${e.constructor.name}. -${t.toString()}`)},hf=class{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:to(e),h:t}),this}else(e){return this.if(Ga,e)}done(){return(e,t)=>{for(let r=0;rnew hf(n),qk=qR(Ga).if(Hk,(n,e)=>Ua(e,$h,cs)).if(Wk,(n,e)=>Lk(e)).if(HR,(n,e)=>rf(e)).if(VR,(n,e)=>BigInt(Ua(e,$h,cs))).if(Ya,(n,e)=>ks(e,Fa(e,n.shape))).if(IR,(n,e)=>{let t={};for(let r in n.shape){let s=n.shape[r];if(RR.check(s)){if(rf(e))continue;s=s.shape}t[r]=qk(s,e)}return t}).if(LR,(n,e)=>{let t=[],r=sf(e,0,42);for(let s=0;sFa(e,n.shape)).if(WR,(n,e)=>null).if($R,(n,e)=>{let t=ks(e,n.res);return()=>t}).if(FR,(n,e)=>ks(e,Fa(e,[bs,Ss,Za,jk,ff,Qa,Uk(bs),$k(vs("a","b","c"),bs)]))).if(OR,(n,e)=>{let t={},r=Ua(e,0,3);for(let s=0;sqk(to(e),n);var mn=typeof document<"u"?document:{};var q2=be(n=>n.nodeType===XR);var J2=typeof DOMParser<"u"?new DOMParser:null;var K2=be(n=>n.nodeType===KR);var Y2=be(n=>n.nodeType===YR);var Jk=n=>G0(n,(e,t)=>`${t}:${e};`).join("");var KR=mn.ELEMENT_NODE,YR=mn.TEXT_NODE,G2=mn.CDATA_SECTION_NODE,X2=mn.COMMENT_NODE,GR=mn.DOCUMENT_NODE,Q2=mn.DOCUMENT_TYPE_NODE,XR=mn.DOCUMENT_FRAGMENT_NODE,Z2=be(n=>n.nodeType===GR);var ec=n=>class{constructor(t){this._=t}destroy(){n(this._)}},QR=ec(clearTimeout),pf=(n,e)=>new QR(setTimeout(e,n)),t$=ec(clearInterval);var n$=ec(n=>typeof requestAnimationFrame<"u"&&cancelAnimationFrame(n));var r$=ec(n=>typeof cancelIdleCallback<"u"&&cancelIdleCallback(n));var jt=Symbol;var no=jt(),ro=jt(),mf=jt(),gf=jt(),yf=jt(),so=jt(),wf=jt(),Cs=jt(),kf=jt(),Yk=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=0;for(;r0&&t.push(e.join(""));r{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=ye(),s=[],i=0;for(;i0||a.length>0?(e.push("%c"+o),t.push(a)):e.push(o)}else break}}for(i>0&&(s=t,s.unshift(e.join("")));i{console.log(...Gk(n)),Qk.forEach(e=>e.print(n))},bf=(...n)=>{console.warn(...Gk(n)),n.unshift(Cs),Qk.forEach(e=>e.print(n))};var Qk=tt();var Zk=n=>({[Symbol.iterator](){return this},next:n}),eb=(n,e)=>Zk(()=>{let t;do t=n.next();while(!t.done&&!e(t.value));return t}),tc=(n,e)=>Zk(()=>{let{done:t,value:r}=n.next();return{done:t,value:t?void 0:e(r)}});var As=class{constructor(e,t){this.clock=e,this.len=t}},$n=class{constructor(){this.clients=new Map}},gn=(n,e,t)=>e.clients.forEach((r,s)=>{let i=n.doc.store.clients.get(s);if(i!=null){let o=i[i.length-1],l=o.id.clock+o.length;for(let a=0,c=r[a];a{let t=0,r=n.length-1;for(;t<=r;){let s=we((t+r)/2),i=n[s],o=i.clock;if(o<=e){if(e{let t=n.clients.get(e.client);return t!==void 0&&aN(t,e.clock)!==null},$f=n=>{n.clients.forEach(e=>{e.sort((s,i)=>s.clock-i.clock);let t,r;for(t=1,r=1;t=i.clock?e[r-1]=new As(s.clock,xt(s.len,i.clock+i.len-s.clock)):(r{let e=new $n;for(let t=0;t{if(!e.clients.has(s)){let i=r.slice();for(let o=t+1;o{Ge(n.clients,e,()=>[]).push(new As(t,r))},kc=()=>new $n,yb=n=>{let e=kc();return n.clients.forEach((t,r)=>{let s=[];for(let i=0;i0&&e.clients.set(r,s)}),e},Ds=(n,e)=>{D(n.restEncoder,e.clients.size),Ct(e.clients.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{n.resetDsCurVal(),D(n.restEncoder,t);let s=r.length;D(n.restEncoder,s);for(let i=0;i{let e=new $n,t=L(n.restDecoder);for(let r=0;r0){let o=Ge(e.clients,s,()=>[]);for(let l=0;l{let r=new $n,s=L(n.restDecoder);for(let i=0;i0){let i=new yn;return D(i.restEncoder,0),Ds(i,r),i.toUint8Array()}return null};var wb=jh,qt=class n extends mr{constructor({guid:e=pk(),collectionid:t=null,gc:r=!0,gcFilter:s=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=s,this.clientID=wb(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new hc,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=qh(c=>{this.on("load",()=>{this.isLoaded=!0,c(this)})});let a=()=>qh(c=>{let u=d=>{(d===void 0||d===!0)&&(this.off("sync",u),c())};this.on("sync",u)});this.on("sync",c=>{c===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=c===void 0||c===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=a()}load(){let e=this._item;e!==null&&!this.shouldLoad&&G(e.parent.doc,t=>{t.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ct(this.subdocs).map(e=>e.guid))}transact(e,t=null){return G(this,e,t)}get(e,t=me){let r=Ge(this.share,e,()=>{let i=new t;return i._integrate(this,null),i}),s=r.constructor;if(t!==me&&s!==t)if(s===me){let i=new t;i._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=r._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=r._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,gc)}getText(e=""){return this.get(e,wn)}getMap(e=""){return this.get(e,ho)}getXmlElement(e=""){return this.get(e,Fe)}getXmlFragment(e=""){return this.get(e,Tr)}toJSON(){let e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Ct(this.subdocs).forEach(t=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new n({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,G(e.parent.doc,r=>{let s=t.doc;e.deleted||r.subdocsAdded.add(s),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},ac=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return L(this.restDecoder)}readDsLen(){return L(this.restDecoder)}},cc=class extends ac{readLeftID(){return z(L(this.restDecoder),L(this.restDecoder))}readRightID(){return z(L(this.restDecoder),L(this.restDecoder))}readClient(){return L(this.restDecoder)}readInfo(){return kr(this.restDecoder)}readString(){return At(this.restDecoder)}readParentInfo(){return L(this.restDecoder)===1}readTypeRef(){return L(this.restDecoder)}readLen(){return L(this.restDecoder)}readAny(){return ms(this.restDecoder)}readBuf(){return Ok(ke(this.restDecoder))}readJSON(){return JSON.parse(At(this.restDecoder))}readKey(){return At(this.restDecoder)}},vf=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=L(this.restDecoder),this.dsCurrVal}readDsLen(){let e=L(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Un=class extends vf{constructor(e){super(e),this.keys=[],L(e),this.keyClockDecoder=new gs(ke(e)),this.clientDecoder=new br(ke(e)),this.leftClockDecoder=new gs(ke(e)),this.rightClockDecoder=new gs(ke(e)),this.infoDecoder=new ji(ke(e),kr),this.stringDecoder=new Oa(ke(e)),this.parentInfoDecoder=new ji(ke(e),kr),this.typeRefDecoder=new br(ke(e)),this.lenDecoder=new br(ke(e))}readLeftID(){return new zn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new zn(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ms(this.restDecoder)}readBuf(){return ke(this.restDecoder)}readJSON(){return ms(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e{r=xt(r,e[0].id.clock);let s=St(e,r);D(n.restEncoder,e.length-s),n.writeClient(t),D(n.restEncoder,r);let i=e[s];i.write(n,r-i.id.clock);for(let o=s+1;o{let r=new Map;t.forEach((s,i)=>{oe(e,i)>s&&r.set(i,s)}),wo(e).forEach((s,i)=>{t.has(i)||r.set(i,0)}),D(n.restEncoder,r.size),Ct(r.entries()).sort((s,i)=>i[0]-s[0]).forEach(([s,i])=>{cN(n,e.clients.get(s),s,i)})},uN=(n,e)=>{let t=ye(),r=L(n.restDecoder);for(let s=0;s{let r=[],s=Ct(t.keys()).sort((f,p)=>f-p);if(s.length===0)return null;let i=()=>{if(s.length===0)return null;let f=t.get(s[s.length-1]);for(;f.refs.length===f.i;)if(s.pop(),s.length>0)f=t.get(s[s.length-1]);else return null;return f},o=i();if(o===null)return null;let l=new hc,a=new Map,c=(f,p)=>{let m=a.get(f);(m==null||m>p)&&a.set(f,p)},u=o.refs[o.i++],d=new Map,h=()=>{for(let f of r){let p=f.id.client,m=t.get(p);m?(m.i--,l.clients.set(p,m.refs.slice(m.i)),t.delete(p),m.i=0,m.refs=[]):l.clients.set(p,[f]),s=s.filter(g=>g!==p)}r.length=0};for(;;){if(u.constructor!==it){let p=Ge(d,u.id.client,()=>oe(e,u.id.client))-u.id.clock;if(p<0)r.push(u),c(u.id.client,u.id.clock-1),h();else{let m=u.getMissing(n,e);if(m!==null){r.push(u);let g=t.get(m)||{refs:[],i:0};if(g.refs.length===g.i)c(m,oe(e,m)),h();else{u=g.refs[g.i++];continue}}else(p===0||p0)u=r.pop();else if(o!==null&&o.i0){let f=new yn;return Ff(f,l,new Map),D(f.restEncoder,0),{missing:a,update:f.toUint8Array()}}return null},hN=(n,e)=>Ff(n,e.doc.store,e.beforeState),fN=(n,e,t,r=new Un(n))=>G(e,s=>{s.local=!1;let i=!1,o=s.doc,l=o.store,a=uN(r,o),c=dN(s,l,a),u=l.pendingStructs;if(u){for(let[h,f]of u.missing)if(ff)&&u.missing.set(h,f)}u.update=fc([u.update,c.update])}}else l.pendingStructs=c;let d=rb(r,s,l);if(l.pendingDs){let h=new Un(Et(l.pendingDs));L(h.restDecoder);let f=rb(h,s,l);d&&f?l.pendingDs=fc([d,f]):l.pendingDs=d||f}else l.pendingDs=d;if(i){let h=l.pendingStructs.update;l.pendingStructs=null,yo(s.doc,h)}},t,!1);var yo=(n,e,t,r=Un)=>{let s=Et(e);fN(s,n,t,new r(s))},kb=(n,e,t)=>yo(n,e,t,cc),pN=(n,e,t=new Map)=>{Ff(n,e.store,t),Ds(n,yb(e.store))},mN=(n,e=new Uint8Array([0]),t=new yn)=>{let r=xb(e);pN(t,n,r);let s=[t.toUint8Array()];if(n.store.pendingDs&&s.push(n.store.pendingDs),n.store.pendingStructs&&s.push(MN(n.store.pendingStructs.update,e)),s.length>1){if(t.constructor===vr)return AN(s.map((i,o)=>o===0?i:NN(i)));if(t.constructor===yn)return fc(s)}return s[0]},bb=(n,e)=>mN(n,e,new vr),gN=n=>{let e=new Map,t=L(n.restDecoder);for(let r=0;rgN(new ac(Et(n))),Sb=(n,e)=>(D(n.restEncoder,e.size),Ct(e.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{D(n.restEncoder,t),D(n.restEncoder,r)}),n),yN=(n,e)=>Sb(n,wo(e.store)),wN=(n,e=new dc)=>(n instanceof Map?Sb(e,n):yN(e,n),e.toUint8Array()),vb=n=>wN(n,new uc),Cf=class{constructor(){this.l=[]}},sb=()=>new Cf,ib=(n,e)=>n.l.push(e),ob=(n,e)=>{let t=n.l,r=t.length;n.l=t.filter(s=>e!==s),r===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Cb=(n,e,t)=>Gi(n.l,[e,t]),zn=class{constructor(e,t){this.client=e,this.clock=t}},nc=(n,e)=>n===e||n!==null&&e!==null&&n.client===e.client&&n.clock===e.clock,z=(n,e)=>new zn(n,e);var Os=n=>{for(let[e,t]of n.doc.share.entries())if(t===n)return e;throw Ae()},Es=(n,e)=>{for(;e!==null;){if(e.parent===n)return!0;e=e.parent._item}return!1};var Cr=class{constructor(e,t,r,s=0){this.type=e,this.tname=t,this.item=r,this.assoc=s}};var Tf=class{constructor(e,t,r=0){this.type=e,this.index=t,this.assoc=r}},kN=(n,e,t=0)=>new Tf(n,e,t),rc=(n,e,t)=>{let r=null,s=null;return n._item===null?s=Os(n):r=z(n._item.id.client,n._item.id.clock),new Cr(r,s,e,t)},bc=(n,e,t=0)=>{let r=n._start;if(t<0){if(e===0)return rc(n,null,t);e--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>e)return rc(n,z(r.id.client,r.id.clock+e),t);e-=r.length}if(r.right===null&&t<0)return rc(n,r.lastId,t);r=r.right}return rc(n,null,t)};var bN=(n,e)=>{let t=Ts(n,e),r=e.clock-t.id.clock;return{item:t,diff:r}},Tb=(n,e,t=!0)=>{let r=e.store,s=n.item,i=n.type,o=n.tname,l=n.assoc,a=null,c=0;if(s!==null){if(oe(r,s.client)<=s.clock)return null;let u=t?Bf(r,s):bN(r,s),d=u.item;if(!(d instanceof q))return null;if(a=d.parent,a._item===null||!a._item.deleted){c=d.deleted||!d.countable?0:u.diff+(l>=0?0:1);let h=d.left;for(;h!==null;)!h.deleted&&h.countable&&(c+=h.length),h=h.left}}else{if(o!==null)a=e.get(o);else if(i!==null){if(oe(r,i.client)<=i.clock)return null;let{item:u}=t?Bf(r,i):{item:Ts(r,i)};if(u instanceof q&&u.content instanceof vt)a=u.content.type;else return null}else throw Ae();l>=0?c=a._length:c=0}return kN(a,c,n.assoc)};var Ms=class{constructor(e,t){this.ds=e,this.sv=t}};var xc=(n,e)=>new Ms(n,e),p$=xc(kc(),new Map),Sc=n=>xc(yb(n.store),wo(n.store)),Sr=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&(e.sv.get(n.id.client)||0)>n.id.clock&&!Er(e.ds,n.id),Af=(n,e)=>{let t=Ge(n.meta,Af,tt),r=n.doc.store;t.has(e)||(e.sv.forEach((s,i)=>{s{}),t.add(e))};var hc=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},wo=n=>{let e=new Map;return n.clients.forEach((t,r)=>{let s=t[t.length-1];e.set(r,s.id.clock+s.length)}),e},oe=(n,e)=>{let t=n.clients.get(e);if(t===void 0)return 0;let r=t[t.length-1];return r.id.clock+r.length},Ab=(n,e)=>{let t=n.clients.get(e.id.client);if(t===void 0)t=[],n.clients.set(e.id.client,t);else{let r=t[t.length-1];if(r.id.clock+r.length!==e.id.clock)throw Ae()}t.push(e)},St=(n,e)=>{let t=0,r=n.length-1,s=n[r],i=s.id.clock;if(i===e)return r;let o=we(e/(i+s.length-1)*r);for(;t<=r;){if(s=n[o],i=s.id.clock,i<=e){if(e{let t=n.clients.get(e.client);return t[St(t,e.clock)]},Ts=xN,Ef=(n,e,t)=>{let r=St(e,t),s=e[r];return s.id.clock{let t=n.doc.store.clients.get(e.client);return t[Ef(n,t,e.clock)]},lb=(n,e,t)=>{let r=e.clients.get(t.client),s=St(r,t.clock),i=r[s];return t.clock!==i.id.clock+i.length-1&&i.constructor!==st&&r.splice(s+1,0,wc(n,i,t.clock-i.id.clock+1)),i},SN=(n,e,t)=>{let r=n.clients.get(e.id.client);r[St(r,e.id.clock)]=t},Eb=(n,e,t,r,s)=>{if(r===0)return;let i=t+r,o=Ef(n,e,t),l;do l=e[o++],ie.deleteSet.clients.size===0&&!X0(e.afterState,(t,r)=>e.beforeState.get(r)!==t)?!1:($f(e.deleteSet),hN(n,e),Ds(n,e.deleteSet),!0),cb=(n,e,t)=>{let r=e._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ge(n.changed,e,tt).add(t)},oc=(n,e)=>{let t=n[e],r=n[e-1],s=e;for(;s>0;t=r,r=n[--s-1]){if(r.deleted===t.deleted&&r.constructor===t.constructor&&r.mergeWith(t)){t instanceof q&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,r);continue}break}let i=e-s;return i&&n.splice(e+1-i,i),i},vN=(n,e,t)=>{for(let[r,s]of n.clients.entries()){let i=e.clients.get(r);for(let o=s.length-1;o>=0;o--){let l=s[o],a=l.clock+l.len;for(let c=St(i,l.clock),u=i[c];c{n.clients.forEach((t,r)=>{let s=e.clients.get(r);for(let i=t.length-1;i>=0;i--){let o=t[i],l=Tt(s.length-1,1+St(s,o.clock+o.len-1));for(let a=l,c=s[a];a>0&&c.id.clock>=o.clock;c=s[a])a-=1+oc(s,a)}})};var Mb=(n,e)=>{if(el.push(()=>{(c._item===null||!c._item.deleted)&&c._callObserver(t,a)})),l.push(()=>{t.changedParentTypes.forEach((a,c)=>{c._dEH.l.length>0&&(c._item===null||!c._item.deleted)&&(a=a.filter(u=>u.target._item===null||!u.target._item.deleted),a.forEach(u=>{u.currentTarget=c,u._path=null}),a.sort((u,d)=>u.path.length-d.path.length),l.push(()=>{Cb(c._dEH,a,t)}))}),l.push(()=>r.emit("afterTransaction",[t,r])),l.push(()=>{t._needFormattingCleanup&&FN(t)})}),Gi(l,[])}finally{r.gc&&vN(i,s,r.gcFilter),CN(i,s),t.afterState.forEach((u,d)=>{let h=t.beforeState.get(d)||0;if(h!==u){let f=s.clients.get(d),p=xt(St(f,h),1);for(let m=f.length-1;m>=p;)m-=1+oc(f,m)}});for(let u=o.length-1;u>=0;u--){let{client:d,clock:h}=o[u].id,f=s.clients.get(d),p=St(f,h);p+11||p>0&&oc(f,p)}if(!t.local&&t.afterState.get(r.clientID)!==t.beforeState.get(r.clientID)&&(Xk(Cs,no,"[yjs] ",ro,so,"Changed the client-id because another client seems to be using it."),r.clientID=wb()),r.emit("afterTransactionCleanup",[t,r]),r._observers.has("update")){let u=new vr;ab(u,t)&&r.emit("update",[u.toUint8Array(),t.origin,r,t])}if(r._observers.has("updateV2")){let u=new yn;ab(u,t)&&r.emit("updateV2",[u.toUint8Array(),t.origin,r,t])}let{subdocsAdded:l,subdocsLoaded:a,subdocsRemoved:c}=t;(l.size>0||c.size>0||a.size>0)&&(l.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),c.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:a,added:l,removed:c},r,t]),c.forEach(u=>u.destroy())),n.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,n])):Mb(n,e+1)}}},G=(n,e,t=null,r=!0)=>{let s=n._transactionCleanups,i=!1,o=null;n._transaction===null&&(i=!0,n._transaction=new Mf(n,t,r),s.push(n._transaction),s.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=e(n._transaction)}finally{if(i){let l=n._transaction===s[0];n._transaction=null,l&&Mb(s,0)}}return o},Rf=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},ub=(n,e,t)=>{gn(n,t.deletions,r=>{r instanceof q&&e.scope.some(s=>s===n.doc||Es(s,r))&&Jf(r,!1)})},db=(n,e,t)=>{let r=null,s=n.doc,i=n.scope;G(s,l=>{for(;e.length>0&&n.currStackItem===null;){let a=s.store,c=e.pop(),u=new Set,d=[],h=!1;gn(l,c.insertions,f=>{if(f instanceof q){if(f.redone!==null){let{item:p,diff:m}=Bf(a,f.id);m>0&&(p=rt(l,z(p.id.client,p.id.clock+m))),f=p}!f.deleted&&i.some(p=>p===l.doc||Es(p,f))&&d.push(f)}}),gn(l,c.deletions,f=>{f instanceof q&&i.some(p=>p===l.doc||Es(p,f))&&!Er(c.insertions,f.id)&&u.add(f)}),u.forEach(f=>{h=qb(l,f,u,c.insertions,n.ignoreRemoteMapChanges,n)!==null||h});for(let f=d.length-1;f>=0;f--){let p=d[f];n.deleteFilter(p)&&(p.delete(l),h=!0)}n.currStackItem=h?c:null}l.changed.forEach((a,c)=>{a.has(null)&&c._searchMarker&&(c._searchMarker.length=0)}),r=l},n);let o=n.currStackItem;if(o!=null){let l=r.changedParentTypes;n.emit("stack-item-popped",[{stackItem:o,type:t,changedParentTypes:l,origin:n},n]),n.currStackItem=null}return o},Rs=class extends mr{constructor(e,{captureTimeout:t=500,captureTransaction:r=a=>!0,deleteFilter:s=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=dn(e)?e[0].doc:e instanceof qt?e:e.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(e),this.deleteFilter=s,i.add(this),this.trackedOrigins=i,this.captureTransaction=r,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=t,this.afterTransactionHandler=a=>{if(!this.captureTransaction(a)||!this.scope.some(g=>a.changedParentTypes.has(g)||g===this.doc)||!this.trackedOrigins.has(a.origin)&&(!a.origin||!this.trackedOrigins.has(a.origin.constructor)))return;let c=this.undoing,u=this.redoing,d=c?this.redoStack:this.undoStack;c?this.stopCapturing():u||this.clear(!1,!0);let h=new $n;a.afterState.forEach((g,y)=>{let w=a.beforeState.get(y)||0,b=g-w;b>0&&oo(h,y,w,b)});let f=ct(),p=!1;if(this.lastChange>0&&f-this.lastChange0&&!c&&!u){let g=d[d.length-1];g.deletions=Sf([g.deletions,a.deleteSet]),g.insertions=Sf([g.insertions,h])}else d.push(new Rf(a.deleteSet,h)),p=!0;!c&&!u&&(this.lastChange=f),gn(a,a.deleteSet,g=>{g instanceof q&&this.scope.some(y=>y===a.doc||Es(y,g))&&Jf(g,!0)});let m=[{stackItem:d[d.length-1],origin:a.origin,type:c?"redo":"undo",changedParentTypes:a.changedParentTypes},this];p?this.emit("stack-item-added",m):this.emit("stack-item-updated",m)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=dn(e)?e:[e],e.forEach(r=>{t.has(r)||(t.add(r),(r instanceof me?r.doc!==this.doc:r!==this.doc)&&bf("[yjs#509] Not same Y.Doc"),this.scope.push(r))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(r=>{e&&(this.undoStack.forEach(s=>ub(r,this,s)),this.undoStack=[]),t&&(this.redoStack.forEach(s=>ub(r,this,s)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=db(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=db(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}};function*TN(n){let e=L(n.restDecoder);for(let t=0;tfc(n,cc,vr);var EN=(n,e)=>{if(n.constructor===st){let{client:t,clock:r}=n.id;return new st(z(t,r+e),n.length-e)}else if(n.constructor===it){let{client:t,clock:r}=n.id;return new it(z(t,r+e),n.length-e)}else{let t=n,{client:r,clock:s}=t.id;return new q(z(r,s+e),null,z(r,s+e-1),null,t.rightOrigin,t.parent,t.parentSub,t.content.splice(e))}},fc=(n,e=Un,t=yn)=>{if(n.length===1)return n[0];let r=n.map(u=>new e(Et(u))),s=r.map(u=>new lo(u,!0)),i=null,o=new t,l=new ao(o);for(;s=s.filter(h=>h.curr!==null),s.sort((h,f)=>{if(h.curr.id.client===f.curr.id.client){let p=h.curr.id.clock-f.curr.id.clock;return p===0?h.curr.constructor===f.curr.constructor?0:h.curr.constructor===it?1:-1:p}else return f.curr.id.client-h.curr.id.client}),s.length!==0;){let u=s[0],d=u.curr.id.client;if(i!==null){let h=u.curr,f=!1;for(;h!==null&&h.id.clock+h.length<=i.struct.id.clock+i.struct.length&&h.id.client>=i.struct.id.client;)h=u.next(),f=!0;if(h===null||h.id.client!==d||f&&h.id.clock>i.struct.id.clock+i.struct.length)continue;if(d!==i.struct.id.client)_n(l,i.struct,i.offset),i={struct:h,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===it?i.struct.length-=p:h=EN(h,p)),i.struct.mergeWith(h)||(_n(l,i.struct,i.offset),i={struct:h,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let h=u.curr;h!==null&&h.id.client===d&&h.id.clock===i.struct.id.clock+i.struct.length&&h.constructor!==it;h=u.next())_n(l,i.struct,i.offset),i={struct:h,offset:0}}i!==null&&(_n(l,i.struct,i.offset),i=null),Vf(l);let a=r.map(u=>Uf(u)),c=Sf(a);return Ds(o,c),o.toUint8Array()},MN=(n,e,t=Un,r=yn)=>{let s=xb(e),i=new r,o=new ao(i),l=new t(Et(n)),a=new lo(l,!1);for(;a.curr;){let u=a.curr,d=u.id.client,h=s.get(d)||0;if(a.curr.constructor===it){a.next();continue}if(u.id.clock+u.length>h)for(_n(o,u,xt(h-u.id.clock,0)),a.next();a.curr&&a.curr.id.client===d;)_n(o,a.curr,0),a.next();else for(;a.curr&&a.curr.id.client===d&&a.curr.id.clock+a.curr.length<=h;)a.next()}Vf(o);let c=Uf(l);return Ds(i,c),i.toUint8Array()};var Rb=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:Y(n.encoder.restEncoder)}),n.encoder.restEncoder=fe(),n.written=0)},_n=(n,e,t)=>{n.written>0&&n.currClient!==e.id.client&&Rb(n),n.written===0&&(n.currClient=e.id.client,n.encoder.writeClient(e.id.client),D(n.encoder.restEncoder,e.id.clock+t)),e.write(n.encoder,t),n.written++},Vf=n=>{Rb(n);let e=n.encoder.restEncoder;D(e,n.clientStructs.length);for(let t=0;t{let s=new t(Et(n)),i=new lo(s,!1),o=new r,l=new ao(o);for(let c=i.curr;c!==null;c=i.next())_n(l,e(c),0);Vf(l);let a=Uf(s);return Ds(o,a),o.toUint8Array()};var NN=n=>RN(n,Tk,Un,vr),hb="You must not compute changes after the event-handler fired.",Ns=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=IN(this.currentTarget,this.target))}deletes(e){return Er(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw at(hb);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(s=>{if(s!==null){let i=t._map.get(s),o,l;if(this.adds(i)){let a=i.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(i))if(a!==null&&this.deletes(a))o="delete",l=Ca(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",l=Ca(a.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=Ca(i.content.getContent());else return;e.set(s,{action:o,oldValue:l})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw at(hb);let t=this.target,r=tt(),s=tt(),i=[];if(e={added:r,deleted:s,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let l=null,a=()=>{l&&i.push(l)};for(let c=t._start;c!==null;c=c.right)c.deleted?this.deletes(c)&&!this.adds(c)&&((l===null||l.delete===void 0)&&(a(),l={delete:0}),l.delete+=c.length,s.add(c)):this.adds(c)?((l===null||l.insert===void 0)&&(a(),l={insert:[]}),l.insert=l.insert.concat(c.content.getContent()),r.add(c)):((l===null||l.retain===void 0)&&(a(),l={retain:0}),l.retain+=c.length);l!==null&&l.retain===void 0&&a()}this._changes=e}return e}},IN=(n,e)=>{let t=[];for(;e._item!==null&&e!==n;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else{let r=0,s=e._item.parent._start;for(;s!==e._item&&s!==null;)!s.deleted&&s.countable&&(r+=s.length),s=s.right;t.unshift(r)}e=e._item.parent}return t},Ue=()=>{bf("Invalid access: Add Yjs type to a document before reading data.")},Nb=80,Hf=0,Nf=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Hf++}},DN=n=>{n.timestamp=Hf++},Ib=(n,e,t)=>{n.p.marker=!1,n.p=e,e.marker=!0,n.index=t,n.timestamp=Hf++},ON=(n,e,t)=>{if(n.length>=Nb){let r=n.reduce((s,i)=>s.timestamp{if(n._start===null||e===0||n._searchMarker===null)return null;let t=n._searchMarker.length===0?null:n._searchMarker.reduce((i,o)=>gr(e-i.index)e;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);return t!==null&&gr(t.index-s){for(let r=n.length-1;r>=0;r--){let s=n[r];if(t>0){let i=s.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(s.index-=i.length);if(i===null||i.marker===!0){n.splice(r,1);continue}s.p=i,i.marker=!0}(e0&&e===s.index)&&(s.index=xt(e,s.index+t))}};var Cc=(n,e,t)=>{let r=n,s=e.changedParentTypes;for(;Ge(s,n,()=>[]).push(t),n._item!==null;)n=n._item.parent;Cb(r._eH,t,e)},me=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=sb(),this._dEH=sb(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Xe()}clone(){throw Xe()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){ib(this._eH,e)}observeDeep(e){ib(this._dEH,e)}unobserve(e){ob(this._eH,e)}unobserveDeep(e){ob(this._dEH,e)}toJSON(){}},Db=(n,e,t)=>{n.doc??Ue(),e<0&&(e=n._length+e),t<0&&(t=n._length+t);let r=t-e,s=[],i=n._start;for(;i!==null&&r>0;){if(i.countable&&!i.deleted){let o=i.content.getContent();if(o.length<=e)e-=o.length;else{for(let l=e;l0;l++)s.push(o[l]),r--;e=0}}i=i.right}return s},Ob=n=>{n.doc??Ue();let e=[],t=n._start;for(;t!==null;){if(t.countable&&!t.deleted){let r=t.content.getContent();for(let s=0;s{let t=[],r=n._start;for(;r!==null;){if(r.countable&&Sr(r,e)){let s=r.content.getContent();for(let i=0;i{let t=0,r=n._start;for(n.doc??Ue();r!==null;){if(r.countable&&!r.deleted){let s=r.content.getContent();for(let i=0;i{let t=[];return uo(n,(r,s)=>{t.push(e(r,s,n))}),t},PN=n=>{let e=n._start,t=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(t===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};t=e.content.getContent(),r=0,e=e.right}let s=t[r++];return t.length<=r&&(t=null),{done:!1,value:s}}}},Lb=(n,e)=>{n.doc??Ue();let t=vc(n,e),r=n._start;for(t!==null&&(r=t.p,e-=t.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let s=t,i=n.doc,o=i.clientID,l=i.store,a=t===null?e._start:t.right,c=[],u=()=>{c.length>0&&(s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new Is(c)),s.integrate(n,0),c=[])};r.forEach(d=>{if(d===null)c.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:c.push(d);break;default:switch(u(),d.constructor){case Uint8Array:case ArrayBuffer:s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new mo(new Uint8Array(d))),s.integrate(n,0);break;case qt:s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new go(d)),s.integrate(n,0);break;default:if(d instanceof me)s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new vt(d)),s.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},_b=()=>at("Length exceeded!"),Bb=(n,e,t,r)=>{if(t>e._length)throw _b();if(t===0)return e._searchMarker&&co(e._searchMarker,t,r.length),pc(n,e,null,r);let s=t,i=vc(e,t),o=e._start;for(i!==null&&(o=i.p,t-=i.index,t===0&&(o=o.prev,t+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(t<=o.length){t{let s=(e._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:e._start}).p;if(s)for(;s.right;)s=s.right;return pc(n,e,s,t)},zb=(n,e,t,r)=>{if(r===0)return;let s=t,i=r,o=vc(e,t),l=e._start;for(o!==null&&(l=o.p,t-=o.index);l!==null&&t>0;l=l.right)!l.deleted&&l.countable&&(t0&&l!==null;)l.deleted||(r0)throw _b();e._searchMarker&&co(e._searchMarker,s,-i+r)},mc=(n,e,t)=>{let r=e._map.get(t);r!==void 0&&r.delete(n)},jf=(n,e,t,r)=>{let s=e._map.get(t)||null,i=n.doc,o=i.clientID,l;if(r==null)l=new Is([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Is([r]);break;case Uint8Array:l=new mo(r);break;case qt:l=new go(r);break;default:if(r instanceof me)l=new vt(r);else throw new Error("Unexpected content type")}new q(z(o,oe(i.store,o)),s,s&&s.lastId,null,null,e,t,l).integrate(n,0)},qf=(n,e)=>{n.doc??Ue();let t=n._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},$b=n=>{let e={};return n.doc??Ue(),n._map.forEach((t,r)=>{t.deleted||(e[r]=t.content.getContent()[t.length-1])}),e},Ub=(n,e)=>{n.doc??Ue();let t=n._map.get(e);return t!==void 0&&!t.deleted};var _N=(n,e)=>{let t={};return n._map.forEach((r,s)=>{let i=r;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&Sr(i,e)&&(t[s]=i.content.getContent()[i.length-1])}),t},sc=n=>(n.doc??Ue(),eb(n._map.entries(),e=>!e[1].deleted)),If=class extends Ns{},gc=class n extends me{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){let t=new n;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof me?t.clone():t)),e}get length(){return this.doc??Ue(),this._length}_callObserver(e,t){super._callObserver(e,t),Cc(this,e,new If(this,e))}insert(e,t){this.doc!==null?G(this.doc,r=>{Bb(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){this.doc!==null?G(this.doc,t=>{LN(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc!==null?G(this.doc,r=>{zb(r,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return Lb(this,e)}toArray(){return Ob(this)}slice(e=0,t=this.length){return Db(this,e,t)}toJSON(){return this.map(e=>e instanceof me?e.toJSON():e)}map(e){return Pb(this,e)}forEach(e){uo(this,e)}[Symbol.iterator](){return PN(this)}_write(e){e.writeTypeRef(sI)}},BN=n=>new gc,Df=class extends Ns{constructor(e,t,r){super(e,t),this.keysChanged=r}},ho=class n extends me{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((r,s)=>{this.set(s,r)}),this._prelimContent=null}_copy(){return new n}clone(){let e=new n;return this.forEach((t,r)=>{e.set(r,t instanceof me?t.clone():t)}),e}_callObserver(e,t){Cc(this,e,new Df(this,e,t))}toJSON(){this.doc??Ue();let e={};return this._map.forEach((t,r)=>{if(!t.deleted){let s=t.content.getContent()[t.length-1];e[r]=s instanceof me?s.toJSON():s}}),e}get size(){return[...sc(this)].length}keys(){return tc(sc(this),e=>e[0])}values(){return tc(sc(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return tc(sc(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ue(),this._map.forEach((t,r)=>{t.deleted||e(t.content.getContent()[t.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?G(this.doc,t=>{mc(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return this.doc!==null?G(this.doc,r=>{jf(r,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return qf(this,e)}has(e){return Ub(this,e)}clear(){this.doc!==null?G(this.doc,e=>{this.forEach(function(t,r,s){mc(e,s,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(iI)}},zN=n=>new ho,Bn=(n,e)=>n===e||typeof n=="object"&&typeof e=="object"&&n&&e&&Qh(n,e),fo=class{constructor(e,t,r,s){this.left=e,this.right=t,this.index=r,this.currentAttributes=s}forward(){this.right===null&&Ae(),this.right.content.constructor===le?this.right.deleted||Ps(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}},fb=(n,e,t)=>{for(;e.right!==null&&t>0;)e.right.content.constructor===le?e.right.deleted||Ps(e.currentAttributes,e.right.content):e.right.deleted||(t{let s=new Map,i=r?vc(e,t):null;if(i){let o=new fo(i.p.left,i.p,i.index,s);return fb(n,o,t-i.index)}else{let o=new fo(null,e._start,0,s);return fb(n,o,t)}},Fb=(n,e,t,r)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===le&&Bn(r.get(t.right.content.key),t.right.content.value));)t.right.deleted||r.delete(t.right.content.key),t.forward();let s=n.doc,i=s.clientID;r.forEach((o,l)=>{let a=t.left,c=t.right,u=new q(z(i,oe(s.store,i)),a,a&&a.lastId,c,c&&c.id,e,null,new le(l,o));u.integrate(n,0),t.right=u,t.forward()})},Ps=(n,e)=>{let{key:t,value:r}=e;r===null?n.delete(t):n.set(t,r)},Vb=(n,e)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===le&&Bn(e[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},Hb=(n,e,t,r)=>{let s=n.doc,i=s.clientID,o=new Map;for(let l in r){let a=r[l],c=t.currentAttributes.get(l)??null;if(!Bn(c,a)){o.set(l,c);let{left:u,right:d}=t;t.right=new q(z(i,oe(s.store,i)),u,u&&u.lastId,d,d&&d.id,e,null,new le(l,a)),t.right.integrate(n,0),t.forward()}}return o},xf=(n,e,t,r,s)=>{t.currentAttributes.forEach((h,f)=>{s[f]===void 0&&(s[f]=null)});let i=n.doc,o=i.clientID;Vb(t,s);let l=Hb(n,e,t,s),a=r.constructor===String?new Mt(r):r instanceof me?new vt(r):new Ar(r),{left:c,right:u,index:d}=t;e._searchMarker&&co(e._searchMarker,t.index,a.getLength()),u=new q(z(o,oe(i.store,o)),c,c&&c.lastId,u,u&&u.id,e,null,a),u.integrate(n,0),t.right=u,t.index=d,t.forward(),Fb(n,e,t,l)},pb=(n,e,t,r,s)=>{let i=n.doc,o=i.clientID;Vb(t,s);let l=Hb(n,e,t,s);e:for(;t.right!==null&&(r>0||l.size>0&&(t.right.deleted||t.right.content.constructor===le));){if(!t.right.deleted)switch(t.right.content.constructor){case le:{let{key:a,value:c}=t.right.content,u=s[a];if(u!==void 0){if(Bn(u,c))l.delete(a);else{if(r===0)break e;l.set(a,c)}t.right.delete(n)}else t.currentAttributes.set(a,c);break}default:r0){let a="";for(;r>0;r--)a+=` -`;t.right=new q(z(o,oe(i.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new Mt(a)),t.right.integrate(n,0),t.forward()}Fb(n,e,t,l)},Wb=(n,e,t,r,s)=>{let i=e,o=ye();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===le){let c=i.content;o.set(c.key,c)}i=i.right}let l=0,a=!1;for(;e!==i;){if(t===e&&(a=!0),!e.deleted){let c=e.content;if(c.constructor===le){let{key:u,value:d}=c,h=r.get(u)??null;(o.get(u)!==c||h===d)&&(e.delete(n),l++,!a&&(s.get(u)??null)===d&&h!==d&&(h===null?s.delete(u):s.set(u,h))),!a&&!e.deleted&&Ps(s,c)}}e=e.right}return l},$N=(n,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;let t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===le){let r=e.content.key;t.has(r)?e.delete(n):t.add(r)}e=e.left}},UN=n=>{let e=0;return G(n.doc,t=>{let r=n._start,s=n._start,i=ye(),o=va(i);for(;s;)s.deleted===!1&&(s.content.constructor===le?Ps(o,s.content):(e+=Wb(t,r,s,i,o),i=va(o),r=s)),s=s.right}),e},FN=n=>{let e=new Set,t=n.doc;for(let[r,s]of n.afterState.entries()){let i=n.beforeState.get(r)||0;s!==i&&Eb(n,t.store.clients.get(r),i,s,o=>{!o.deleted&&o.content.constructor===le&&o.constructor!==st&&e.add(o.parent)})}G(t,r=>{gn(n,n.deleteSet,s=>{if(s instanceof st||!s.parent._hasFormatting||e.has(s.parent))return;let i=s.parent;s.content.constructor===le?e.add(i):$N(r,s)});for(let s of e)UN(s)})},mb=(n,e,t)=>{let r=t,s=va(e.currentAttributes),i=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case vt:case Ar:case Mt:t{s===null?this.childListChanged=!0:this.keysChanged.add(s)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];G(e,r=>{let s=new Map,i=new Map,o=this.target._start,l=null,a={},c="",u=0,d=0,h=()=>{if(l!==null){let f=null;switch(l){case"delete":d>0&&(f={delete:d}),d=0;break;case"insert":(typeof c=="object"||c.length>0)&&(f={insert:c},s.size>0&&(f.attributes={},s.forEach((p,m)=>{p!==null&&(f.attributes[m]=p)}))),c="";break;case"retain":u>0&&(f={retain:u},Ck(a)||(f.attributes=xk({},a))),u=0;break}f&&t.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case vt:case Ar:this.adds(o)?this.deletes(o)||(h(),l="insert",c=o.content.getContent()[0],h()):this.deletes(o)?(l!=="delete"&&(h(),l="delete"),d+=1):o.deleted||(l!=="retain"&&(h(),l="retain"),u+=1);break;case Mt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(h(),l="insert"),c+=o.content.str):this.deletes(o)?(l!=="delete"&&(h(),l="delete"),d+=o.length):o.deleted||(l!=="retain"&&(h(),l="retain"),u+=o.length);break;case le:{let{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){let m=s.get(f)??null;Bn(m,p)?p!==null&&o.delete(r):(l==="retain"&&h(),Bn(p,i.get(f)??null)?delete a[f]:a[f]=p)}}else if(this.deletes(o)){i.set(f,p);let m=s.get(f)??null;Bn(m,p)||(l==="retain"&&h(),a[f]=m)}else if(!o.deleted){i.set(f,p);let m=a[f];m!==void 0&&(Bn(m,p)?m!==null&&o.delete(r):(l==="retain"&&h(),p===null?delete a[f]:a[f]=p))}o.deleted||(l==="insert"&&h(),Ps(s,o.content));break}}o=o.right}for(h();t.length>0;){let f=t[t.length-1];if(f.retain!==void 0&&f.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},wn=class n extends me{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ue(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new n}clone(){let e=new n;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);let r=new Of(this,e,t);Cc(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ue();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Mt&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?G(this.doc,r=>{let s=new fo(null,this._start,0,new Map);for(let i=0;i0)&&xf(r,this,s,l,o.attributes||{})}else o.retain!==void 0?pb(r,this,s,o.retain,o.attributes||{}):o.delete!==void 0&&mb(r,s,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,r){this.doc??Ue();let s=[],i=new Map,o=this.doc,l="",a=this._start;function c(){if(l.length>0){let d={},h=!1;i.forEach((p,m)=>{h=!0,d[m]=p});let f={insert:l};h&&(f.attributes=d),s.push(f),l=""}}let u=()=>{for(;a!==null;){if(Sr(a,e)||t!==void 0&&Sr(a,t))switch(a.content.constructor){case Mt:{let d=i.get("ychange");e!==void 0&&!Sr(a,e)?(d===void 0||d.user!==a.id.client||d.type!=="removed")&&(c(),i.set("ychange",r?r("removed",a.id):{type:"removed"})):t!==void 0&&!Sr(a,t)?(d===void 0||d.user!==a.id.client||d.type!=="added")&&(c(),i.set("ychange",r?r("added",a.id):{type:"added"})):d!==void 0&&(c(),i.delete("ychange")),l+=a.content.str;break}case vt:case Ar:{c();let d={insert:a.content.getContent()[0]};if(i.size>0){let h={};d.attributes=h,i.forEach((f,p)=>{h[p]=f})}s.push(d);break}case le:Sr(a,e)&&(c(),Ps(i,a.content));break}a=a.right}c()};return e||t?G(o,d=>{e&&Af(d,e),t&&Af(d,t),u()},"cleanup"):u(),s}insert(e,t,r){if(t.length<=0)return;let s=this.doc;s!==null?G(s,i=>{let o=ic(i,this,e,!r);r||(r={},o.currentAttributes.forEach((l,a)=>{r[a]=l})),xf(i,this,o,t,r)}):this._pending.push(()=>this.insert(e,t,r))}insertEmbed(e,t,r){let s=this.doc;s!==null?G(s,i=>{let o=ic(i,this,e,!r);xf(i,this,o,t,r||{})}):this._pending.push(()=>this.insertEmbed(e,t,r||{}))}delete(e,t){if(t===0)return;let r=this.doc;r!==null?G(r,s=>{mb(s,ic(s,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,r){if(t===0)return;let s=this.doc;s!==null?G(s,i=>{let o=ic(i,this,e,!1);o.right!==null&&pb(i,this,o,t,r)}):this._pending.push(()=>this.format(e,t,r))}removeAttribute(e){this.doc!==null?G(this.doc,t=>{mc(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){this.doc!==null?G(this.doc,r=>{jf(r,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return qf(this,e)}getAttributes(){return $b(this)}_write(e){e.writeTypeRef(oI)}},VN=n=>new wn,io=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ue()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Fe||t.constructor===Tr)&&t._start!==null)e=t._start;else for(;e!==null;){let r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},Tr=class n extends me{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof me?t.clone():t)),e}get length(){return this.doc??Ue(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new io(this,e)}querySelector(e){e=e.toUpperCase();let r=new io(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Ct(new io(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Cc(this,e,new Pf(this,t,e))}toString(){return Pb(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},r){let s=e.createDocumentFragment();return r!==void 0&&r._createAssociation(s,this),uo(this,i=>{s.insertBefore(i.toDOM(e,t,r),null)}),s}insert(e,t){this.doc!==null?G(this.doc,r=>{Bb(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)G(this.doc,r=>{let s=e&&e instanceof me?e._item:e;pc(r,this,s,t)});else{let r=this._prelimContent,s=e===null?0:r.findIndex(i=>i===e)+1;if(s===0&&e!==null)throw at("Reference item not found");r.splice(s,0,...t)}}delete(e,t=1){this.doc!==null?G(this.doc,r=>{zb(r,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Ob(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Lb(this,e)}slice(e=0,t=this.length){return Db(this,e,t)}forEach(e){uo(this,e)}_write(e){e.writeTypeRef(aI)}},HN=n=>new Tr,Fe=class n extends Tr{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,s)=>{this.setAttribute(s,r)}),this._prelimAttrs=null}_copy(){return new n(this.nodeName)}clone(){let e=new n(this.nodeName),t=this.getAttributes();return Sk(t,(r,s)=>{e.setAttribute(s,r)}),e.insert(0,this.toArray().map(r=>r instanceof me?r.clone():r)),e}toString(){let e=this.getAttributes(),t=[],r=[];for(let l in e)r.push(l);r.sort();let s=r.length;for(let l=0;l0?" "+t.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?G(this.doc,t=>{mc(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){this.doc!==null?G(this.doc,r=>{jf(r,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return qf(this,e)}hasAttribute(e){return Ub(this,e)}getAttributes(e){return e?_N(this,e):$b(this)}toDOM(e=document,t={},r){let s=e.createElement(this.nodeName),i=this.getAttributes();for(let o in i){let l=i[o];typeof l=="string"&&s.setAttribute(o,l)}return uo(this,o=>{s.appendChild(o.toDOM(e,t,r))}),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(lI),e.writeKey(this.nodeName)}},WN=n=>new Fe(n.readKey()),Pf=class extends Ns{constructor(e,t,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}},Lf=class n extends ho{constructor(e){super(),this.hookName=e}_copy(){return new n(this.hookName)}clone(){let e=new n(this.hookName);return this.forEach((t,r)=>{e.set(r,t)}),e}toDOM(e=document,t={},r){let s=t[this.hookName],i;return s!==void 0?i=s.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(cI),e.writeKey(this.hookName)}},jN=n=>new Lf(n.readKey()),ut=class n extends wn{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new n}clone(){let e=new n;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,r){let s=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(s,this),s}toString(){return this.toDelta().map(e=>{let t=[];for(let s in e.attributes){let i=[];for(let o in e.attributes[s])i.push({key:o,value:e.attributes[s][o]});i.sort((o,l)=>o.keys.nodeName=0;s--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(uI)}},qN=n=>new ut,po=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Xe()}mergeWith(e){return!1}write(e,t,r){throw Xe()}integrate(e,t){throw Xe()}},JN=0,st=class extends po{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Ab(e.doc.store,this)}write(e,t){e.writeInfo(JN),e.writeLen(this.length-t)}getMissing(e,t){return null}},mo=class n{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new n(this.content)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},KN=n=>new mo(n.readBuf()),yc=class n{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new n(this.len)}splice(e){let t=new n(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){oo(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},YN=n=>new yc(n.readLen()),jb=(n,e)=>new qt({guid:n,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),go=class n{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new n(jb(this.doc.guid,this.opts))}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},GN=n=>new go(jb(n.readString(),n.readAny())),Ar=class n{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new n(this.embed)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},XN=n=>new Ar(n.readJSON()),le=class n{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new n(this.key,this.value)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){let r=t.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},QN=n=>new le(n.readKey(),n.readJSON()),_f=class n{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new n(this.arr)}splice(e){let t=new n(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let r=this.arr.length;e.writeLen(r-t);for(let s=t;s{let e=n.readLen(),t=[];for(let r=0;r{let e=n.readLen(),t=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",t.str="\uFFFD"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}},nI=n=>new Mt(n.readString()),rI=[BN,zN,VN,WN,HN,jN,qN],sI=0,iI=1,oI=2,lI=3,aI=4,cI=5,uI=6,vt=class n{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new n(this.type._copy())}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},dI=n=>new vt(rI[n.readTypeRef()](n)),Bf=(n,e)=>{let t=e,r=0,s;do r>0&&(t=z(t.client,t.clock+r)),s=Ts(n,t),r=t.clock-s.id.clock,t=s.redone;while(t!==null&&s instanceof q);return{item:s,diff:r}},Jf=(n,e)=>{for(;n!==null&&n.keep!==e;)n.keep=e,n=n.parent._item},wc=(n,e,t)=>{let{client:r,clock:s}=e.id,i=new q(z(r,s+t),e,z(r,s+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&i.markDeleted(),e.keep&&(i.keep=!0),e.redone!==null&&(i.redone=z(e.redone.client,e.redone.clock+t)),e.right=i,i.right!==null&&(i.right.left=i),n._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),e.length=t,i},gb=(n,e)=>zi(n,t=>Er(t.deletions,e)),qb=(n,e,t,r,s,i)=>{let o=n.doc,l=o.store,a=o.clientID,c=e.redone;if(c!==null)return rt(n,c);let u=e.parent._item,d=null,h;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!t.has(u)||qb(n,u,t,r,s,i)===null))return null;for(;u.redone!==null;)u=rt(n,u.redone)}let f=u===null?e.parent:u.content.type;if(e.parentSub===null){for(d=e.left,h=e;d!==null;){let y=d;for(;y!==null&&y.parent._item!==u;)y=y.redone===null?null:rt(n,y.redone);if(y!==null&&y.parent._item===u){d=y;break}d=d.left}for(;h!==null;){let y=h;for(;y!==null&&y.parent._item!==u;)y=y.redone===null?null:rt(n,y.redone);if(y!==null&&y.parent._item===u){h=y;break}h=h.right}}else{if(h=null,e.right&&!s){for(d=e;d!==null&&d.right!==null&&(d.right.redone||Er(r,d.right.id)||gb(i.undoStack,d.right.id)||gb(i.redoStack,d.right.id));)for(d=d.right;d.redone;)d=rt(n,d.redone);if(d&&d.right!==null)return null}else d=f._map.get(e.parentSub)||null;d!==null&&d.parent._item!==u&&(d=f._map.get(e.parentSub)||null)}let p=oe(l,a),m=z(a,p),g=new q(m,d,d&&d.lastId,h,h&&h.id,f,e.parentSub,e.content.copy());return e.redone=m,Jf(g,!0),g.integrate(n,0),g},q=class n extends po{constructor(e,t,r,s,i,o,l,a){super(e,a.getLength()),this.origin=r,this.left=t,this.right=s,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=oe(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=oe(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===zn&&this.id.client!==this.parent.client&&this.parent.clock>=oe(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=lb(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===st||this.right&&this.right.constructor===st)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===n?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===n&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===zn){let r=Ts(t,this.parent);r.constructor===st?this.parent=null:this.parent=r.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=lb(e,e.doc.store,z(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,s;if(r!==null)s=r.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;let i=new Set,o=new Set;for(;s!==null&&s!==this.right;){if(o.add(s),i.add(s),nc(this.origin,s.origin)){if(s.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),oo(e.deleteSet,this.id.client,this.id.clock,this.length),cb(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Ae();this.content.gc(e),t?SN(e,this,new st(this.id,this.length)):this.content=new yc(this.length)}write(e,t){let r=t>0?z(this.id.client,this.id.clock+t-1):this.origin,s=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&31|(r===null?0:128)|(s===null?0:64)|(i===null?0:32);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),s!==null&&e.writeRightID(s),r===null&&s===null){let l=this.parent;if(l._item!==void 0){let a=l._item;if(a===null){let c=Os(l);e.writeParentInfo(!0),e.writeString(c)}else e.writeParentInfo(!1),e.writeLeftID(a.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===zn?(e.writeParentInfo(!1),e.writeLeftID(l)):Ae();i!==null&&e.writeString(i)}this.content.write(e,t)}},Jb=(n,e)=>hI[e&31](n),hI=[()=>{Ae()},YN,ZN,KN,nI,XN,QN,dI,tI,GN,()=>{Ae()}],fI=10,it=class extends po{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){Ae()}write(e,t){e.writeInfo(fI),D(e.restEncoder,this.length-t)}getMissing(e,t){return null}},Kb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Yb="__ $YJS$ __";Kb[Yb]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Kb[Yb]=!0;var Yf=3e4,Tc=class extends Aa{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let t=ct();this.getLocalState()!==null&&Yf/2<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let r=[];this.meta.forEach((s,i)=>{i!==this.clientID&&Yf<=t-s.lastUpdated&&this.states.has(i)&&r.push(i)}),r.length>0&&Ac(this,r,"timeout")},we(Yf/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,r=this.meta.get(t),s=r===void 0?0:r.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:s,lastUpdated:ct()});let o=[],l=[],a=[],c=[];e===null?c.push(t):i==null?e!=null&&o.push(t):(l.push(t),Ln(i,e)||a.push(t)),(o.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:o,updated:a,removed:c},"local"]),this.emit("update",[{added:o,updated:l,removed:c},"local"])}setLocalStateField(e,t){let r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:t})}getStates(){return this.states}},Ac=(n,e,t)=>{let r=[];for(let s=0;s0&&(n.emit("change",[{added:[],updated:[],removed:r},t]),n.emit("update",[{added:[],updated:[],removed:r},t]))},Ls=(n,e,t=n.states)=>{let r=e.length,s=fe();D(s,r);for(let i=0;i{let r=Et(e),s=ct(),i=[],o=[],l=[],a=[],c=L(r);for(let u=0;u0||l.length>0||a.length>0)&&n.emit("change",[{added:i,updated:l,removed:a},t]),(i.length>0||o.length>0||a.length>0)&&n.emit("update",[{added:i,updated:o,removed:a},t])};var Xb=()=>{let n=!0;return(e,t)=>{if(n){n=!1;try{e()}finally{n=!0}}else t!==void 0&&t()}};var mI=/[\uD800-\uDBFF]/,gI=/[\uDC00-\uDFFF]/,yI=(n,e)=>{let t=0,r=0;for(;t0&&mI.test(n[t-1])&&t--;r+t0&&gI.test(n[n.length-r])&&r--,{index:t,remove:n.length-t-r,insert:e.slice(t,e.length-r)}},Qb=yI;var Jt=(n,e)=>n>>>e|n<<32-e,wI=n=>Jt(n,2)^Jt(n,13)^Jt(n,22),kI=n=>Jt(n,6)^Jt(n,11)^Jt(n,25),bI=n=>Jt(n,7)^Jt(n,18)^n>>>3,xI=n=>Jt(n,17)^Jt(n,19)^n>>>10,SI=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),vI=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Gf=class{constructor(){let e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(vI),this._W=new Uint32Array(e,64,64)}_updateHash(){let e=this._H,t=this._W;for(let d=16;d<64;d++)t[d]=xI(t[d-2])+t[d-7]+bI(t[d-15])+t[d-16];let r=e[0],s=e[1],i=e[2],o=e[3],l=e[4],a=e[5],c=e[6],u=e[7];for(let d=0,h,f;d<64;d++)h=u+kI(l)+(l&a^~l&c)+SI[d]+t[d]>>>0,f=wI(r)+(r&s^r&i^s&i)>>>0,u=c,c=a,a=l,l=o+h>>>0,o=i,i=s,s=r,r=h+f>>>0;e[0]+=r,e[1]+=s,e[2]+=i,e[3]+=o,e[4]+=l,e[5]+=a,e[6]+=c,e[7]+=u}digest(e){let t=0;for(;t+56<=e.length;){let o=0;for(;o<16&&t+3=0&&t>>(3-l)*8;return i}},Zb=n=>new Gf().digest(n);var ee=new P("y-sync"),Kt=new P("y-undo"),A$=new P("yjs-cursor"),TI=n=>{for(let t=6;t$a(TI(Zb(Pk(n))));var Mc=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&e.sv.get(n.id.client)>n.id.clock&&!Er(e.ds,n.id),EI=[{light:"#ecd44433",dark:"#ecd444"}],MI=(n,e,t)=>{if(!n.has(t)){if(n.sizer.add(s)),e=e.filter(s=>!r.has(s))}n.set(t,fk(e))}return n.get(t)},nx=(n,{colors:e=EI,colorMapping:t=new Map,permanentUserData:r=null,onFirstRender:s=()=>{},mapping:i}={})=>{let o=!1,l=new Qf(n,i),a=new O({props:{editable:c=>{let u=ee.getState(c);return u.snapshot==null&&u.prevSnapshot==null}},key:ee,state:{init:(c,u)=>({type:n,doc:n.doc,binding:l,snapshot:null,prevSnapshot:null,isChangeOrigin:!1,isUndoRedoOperation:!1,addToHistory:!0,colors:e,colorMapping:t,permanentUserData:r}),apply:(c,u)=>{let d=c.getMeta(ee);if(d!==void 0){u=Object.assign({},u);for(let h in d)u[h]=d[h]}return u.addToHistory=c.getMeta("addToHistory")!==!1,u.isChangeOrigin=d!==void 0&&!!d.isChangeOrigin,u.isUndoRedoOperation=d!==void 0&&!!d.isChangeOrigin&&!!d.isUndoRedoOperation,l.prosemirrorView!==null&&d!==void 0&&(d.snapshot!=null||d.prevSnapshot!=null)&&pf(0,()=>{l.prosemirrorView!=null&&(d.restore==null?l._renderSnapshot(d.snapshot,d.prevSnapshot,u):(l._renderSnapshot(d.snapshot,d.snapshot,u),delete u.restore,delete u.snapshot,delete u.prevSnapshot,l.mux(()=>{l._prosemirrorChanged(l.prosemirrorView.state.doc)})))}),u}},view:c=>(l.initView(c),i==null&&l._forceRerender(),s(),{update:()=>{let u=a.getState(c.state);if(u.snapshot==null&&u.prevSnapshot==null&&(o||c.state.doc.content.findDiffStart(c.state.doc.type.createAndFill().content)!==null)){if(o=!0,u.addToHistory===!1&&!u.isChangeOrigin){let d=Kt.getState(c.state),h=d&&d.undoManager;h&&h.stopCapturing()}l.mux(()=>{u.doc.transact(d=>{d.meta.set("addToHistory",u.addToHistory),l._prosemirrorChanged(c.state.doc)},ee)})}},destroy:()=>{l.destroy()}})});return a},RI=(n,e,t)=>{if(e!==null&&e.anchor!==null&&e.head!==null)if(e.type==="all")n.setSelection(new Re(n.doc));else if(e.type==="node"){let r=ko(t.doc,t.type,e.anchor,t.mapping);n.setSelection(NI(n,r))}else{let r=ko(t.doc,t.type,e.anchor,t.mapping),s=ko(t.doc,t.type,e.head,t.mapping);r!==null&&s!==null&&n.setSelection(E.between(n.doc.resolve(r),n.doc.resolve(s)))}},NI=(n,e)=>{let t=n.doc.resolve(e);return t.nodeAfter?M.create(n.doc,e):E.near(t)},Xf=(n,e)=>({type:e.selection.jsonID,anchor:Nc(e.selection.anchor,n.type,n.mapping),head:Nc(e.selection.head,n.type,n.mapping)}),Qf=class{constructor(e,t=new Map){this.type=e,this.prosemirrorView=null,this.mux=Xb(),this.mapping=t,this.isOMark=new Map,this._observeFunction=this._typeChanged.bind(this),this.doc=e.doc,this.beforeTransactionSelection=null,this.beforeAllTransactions=()=>{this.beforeTransactionSelection===null&&this.prosemirrorView!=null&&(this.beforeTransactionSelection=Xf(this,this.prosemirrorView.state))},this.afterAllTransactions=()=>{this.beforeTransactionSelection=null},this._domSelectionInView=null}get _tr(){return this.prosemirrorView.state.tr.setMeta("addToHistory",!1)}_isLocalCursorInView(){return this.prosemirrorView.hasFocus()?(ys&&this._domSelectionInView===null&&(pf(0,()=>{this._domSelectionInView=null}),this._domSelectionInView=this._isDomSelectionInView()),this._domSelectionInView):!1}_isDomSelectionInView(){let e=this.prosemirrorView._root.getSelection();if(e==null||e.anchorNode==null)return!1;let t=this.prosemirrorView._root.createRange();t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.getClientRects().length===0&&t.startContainer&&t.collapsed&&t.selectNodeContents(t.startContainer);let s=t.getBoundingClientRect(),i=mn.documentElement;return s.bottom>=0&&s.right>=0&&s.left<=(window.innerWidth||i.clientWidth||0)&&s.top<=(window.innerHeight||i.clientHeight||0)}renderSnapshot(e,t){t||(t=xc(kc(),new Map)),this.prosemirrorView.dispatch(this._tr.setMeta(ee,{snapshot:e,prevSnapshot:t}))}unrenderSnapshot(){this.mapping.clear(),this.mux(()=>{let e=this.type.toArray().map(r=>Ec(r,this.prosemirrorView.state.schema,this)).filter(r=>r!==null),t=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(e),0,0));t.setMeta(ee,{snapshot:null,prevSnapshot:null}),this.prosemirrorView.dispatch(t)})}_forceRerender(){this.mapping.clear(),this.mux(()=>{let e=this.beforeTransactionSelection!==null?null:this.prosemirrorView.state.selection,t=this.type.toArray().map(s=>Ec(s,this.prosemirrorView.state.schema,this)).filter(s=>s!==null),r=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(t),0,0));if(e){let s=Tt(xt(e.anchor,0),r.doc.content.size),i=Tt(xt(e.head,0),r.doc.content.size);r.setSelection(E.create(r.doc,s,i))}this.prosemirrorView.dispatch(r.setMeta(ee,{isChangeOrigin:!0,binding:this}))})}_renderSnapshot(e,t,r){let s=this.doc,i=this.type;if(e||(e=Sc(this.doc)),e instanceof Uint8Array||t instanceof Uint8Array)if((!(e instanceof Uint8Array)||!(t instanceof Uint8Array))&&Ae(),s=new qt({gc:!1}),yo(s,t),t=Sc(s),yo(s,e),e=Sc(s),i._item===null){let o=Array.from(this.doc.share.keys()).find(l=>this.doc.share.get(l)===this.type);i=s.getXmlFragment(o)}else{let o=s.store.clients.get(i._item.id.client)??[],l=St(o,i._item.id.clock);i=o[l].content.type}this.mapping.clear(),this.mux(()=>{s.transact(o=>{let l=r.permanentUserData;l&&l.dss.forEach(d=>{gn(o,d,h=>{})});let a=(d,h)=>{let f=d==="added"?l.getUserByClientId(h.client):l.getUserByDeletedId(h);return{user:f,type:d,color:MI(r.colorMapping,r.colors,f)}},c=Wf(i,new Ms(t.ds,e.sv)).map(d=>!d._item.deleted||Mc(d._item,e)||Mc(d._item,t)?Ec(d,this.prosemirrorView.state.schema,{mapping:new Map,isOMark:new Map},e,t,a):null).filter(d=>d!==null),u=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(c),0,0));this.prosemirrorView.dispatch(u.setMeta(ee,{isChangeOrigin:!0}))},ee)})}_typeChanged(e,t){if(this.prosemirrorView==null)return;let r=ee.getState(this.prosemirrorView.state);if(e.length===0||r.snapshot!=null||r.prevSnapshot!=null){this.renderSnapshot(r.snapshot,r.prevSnapshot);return}this.mux(()=>{let s=(l,a)=>this.mapping.delete(a);gn(t,t.deleteSet,l=>{if(l.constructor===q){let a=l.content.type;a&&this.mapping.delete(a)}}),t.changed.forEach(s),t.changedParentTypes.forEach(s);let i=this.type.toArray().map(l=>rx(l,this.prosemirrorView.state.schema,this)).filter(l=>l!==null),o=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(i),0,0));RI(o,this.beforeTransactionSelection,this),o=o.setMeta(ee,{isChangeOrigin:!0,isUndoRedoOperation:t.origin instanceof Rs}),this.beforeTransactionSelection!==null&&this._isLocalCursorInView()&&o.scrollIntoView(),this.prosemirrorView.dispatch(o)})}_prosemirrorChanged(e){this.doc.transact(()=>{ep(this.doc,this.type,e,this),this.beforeTransactionSelection=Xf(this,this.prosemirrorView.state)},ee)}initView(e){this.prosemirrorView!=null&&this.destroy(),this.prosemirrorView=e,this.doc.on("beforeAllTransactions",this.beforeAllTransactions),this.doc.on("afterAllTransactions",this.afterAllTransactions),this.type.observeDeep(this._observeFunction)}destroy(){this.prosemirrorView!=null&&(this.prosemirrorView=null,this.type.unobserveDeep(this._observeFunction),this.doc.off("beforeAllTransactions",this.beforeAllTransactions),this.doc.off("afterAllTransactions",this.afterAllTransactions))}},rx=(n,e,t,r,s,i)=>{let o=t.mapping.get(n);if(o===void 0){if(n instanceof Fe)return Ec(n,e,t,r,s,i);throw Xe()}return o},Ec=(n,e,t,r,s,i)=>{let o=[],l=a=>{if(a instanceof Fe){let c=rx(a,e,t,r,s,i);c!==null&&o.push(c)}else{let c=a._item.right?.content?.type;c instanceof wn&&!c._item.deleted&&c._item.id.client===c.doc.clientID&&(a.applyDelta([{retain:a.length},...c.toDelta()]),c.doc.transact(d=>{c._item.delete(d)}));let u=II(a,e,t,r,s,i);u!==null&&u.forEach(d=>{d!==null&&o.push(d)})}};r===void 0||s===void 0?n.toArray().forEach(l):Wf(n,new Ms(s.ds,r.sv)).forEach(l);try{let a=n.getAttributes(r);r!==void 0&&(Mc(n._item,r)?Mc(n._item,s)||(a.ychange=i?i("added",n._item.id):{type:"added"}):a.ychange=i?i("removed",n._item.id):{type:"removed"});let c=e.node(n.nodeName,a,o);return t.mapping.set(n,c),c}catch{return n.doc.transact(c=>{n._item.delete(c)},ee),t.mapping.delete(n),null}},II=(n,e,t,r,s,i)=>{let o=[],l=n.toDelta(r,s,i);try{for(let a=0;a{n._item.delete(c)},ee),null}return o},DI=(n,e)=>{let t=new ut,r=n.map(s=>({insert:s.text,attributes:ox(s.marks,e)}));return t.applyDelta(r),e.mapping.set(t,n),t},OI=(n,e)=>{let t=new Fe(n.type.name);for(let r in n.attrs){let s=n.attrs[r];s!==null&&r!=="ychange"&&t.setAttribute(r,s)}return t.insert(0,Ic(n).map(r=>Zf(r,e))),e.mapping.set(t,n),t},Zf=(n,e)=>n instanceof Array?DI(n,e):OI(n,e),ex=n=>typeof n=="object"&&n!==null,np=(n,e)=>{let t=Object.keys(n).filter(s=>n[s]!==null),r=t.length===Object.keys(e).filter(s=>e[s]!==null).length;for(let s=0;s{let e=n.content.content,t=[];for(let r=0;r{let t=n.toDelta();return t.length===e.length&&t.every((r,s)=>r.insert===e[s].text&&Xh(r.attributes||{}).length===e[s].marks.length&&Pn(r.attributes,(i,o)=>{let l=ix(o),a=e[s].marks;return a.find(u=>u.type.name===l)?np(i,a.find(u=>u.type.name===l)?.attrs):!1}))},bo=(n,e)=>{if(n instanceof Fe&&!(e instanceof Array)&&tp(n,e)){let t=Ic(e);return n._length===t.length&&np(n.getAttributes(),e.attrs)&&n.toArray().every((r,s)=>bo(r,t[s]))}return n instanceof ut&&e instanceof Array&&sx(n,e)},Rc=(n,e)=>n===e||n instanceof Array&&e instanceof Array&&n.length===e.length&&n.every((t,r)=>e[r]===t),tx=(n,e,t)=>{let r=n.toArray(),s=Ic(e),i=s.length,o=r.length,l=Tt(o,i),a=0,c=0,u=!1;for(;a{let e="",t=n._start,r={};for(;t!==null;)t.deleted||(t.countable&&t.content instanceof Mt?e+=t.content.str:t.content instanceof le&&(r[t.content.key]=null)),t=t.right;return{str:e,nAttrs:r}},LI=(n,e,t)=>{t.mapping.set(n,e);let{nAttrs:r,str:s}=PI(n),i=e.map(c=>({insert:c.text,attributes:Object.assign({},r,ox(c.marks,t))})),{insert:o,remove:l,index:a}=Qb(s,i.map(c=>c.insert).join(""));n.delete(a,l),n.insert(a,o),n.applyDelta(i.map(c=>({retain:c.insert.length,attributes:c.attributes})))},_I=/(.*)(--[a-zA-Z0-9+/=]{8})$/,ix=n=>_I.exec(n)?.[1]??n,BI=(n,e)=>{let t=[];for(let r in n)t.push(e.mark(ix(r),n[r]));return t},ox=(n,e)=>{let t={};return n.forEach(r=>{if(r.type.name!=="ychange"){let s=Ge(e.isOMark,r.type,()=>!r.type.excludes(r.type));t[s?`${r.type.name}--${AI(r.toJSON())}`:r.type.name]=r.attrs}}),t},ep=(n,e,t,r)=>{if(e instanceof Fe&&e.nodeName!==t.type.name)throw new Error("node name mismatch!");if(r.mapping.set(e,t),e instanceof Fe){let d=e.getAttributes(),h=t.attrs;for(let f in h)h[f]!==null?d[f]!==h[f]&&f!=="ychange"&&e.setAttribute(f,h[f]):e.removeAttribute(f);for(let f in d)h[f]===void 0&&e.removeAttribute(f)}let s=Ic(t),i=s.length,o=e.toArray(),l=o.length,a=Tt(i,l),c=0,u=0;for(;c{for(;l-c-u>0&&i-c-u>0;){let h=o[c],f=s[c],p=o[l-u-1],m=s[i-u-1];if(h instanceof ut&&f instanceof Array)sx(h,f)||LI(h,f,r),c+=1;else{let g=h instanceof Fe&&tp(h,f),y=p instanceof Fe&&tp(p,m);if(g&&y){let w=tx(h,f,r),b=tx(p,m,r);w.foundMappedChild&&!b.foundMappedChild?y=!1:!w.foundMappedChild&&b.foundMappedChild||w.equalityFactor0&&(e.slice(c,c+d).forEach(h=>r.mapping.delete(h)),e.delete(c,d)),c+u!(e instanceof Array)&&n.nodeName===e.type.name;var Nc=(n,e,t)=>{if(n===0)return bc(e,0,-1);let r=e._first===null?null:e._first.content.type;for(;r!==null&&e!==r;){if(r instanceof ut){if(r._length>=n)return bc(r,n,-1);if(n-=r._length,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{do r=r._item===null?null:r._item.parent,n--;while(r!==e&&r!==null&&r._item!==null&&r._item.next===null);r!==null&&r!==e&&(r=r._item===null?null:r._item.next.content.type)}}else{let s=(t.get(r)||{nodeSize:0}).nodeSize;if(r._first!==null&&n1)return new Cr(r._item===null?null:r._item.id,r._item===null?Os(r):null,null);if(n-=s,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{if(n===0)return r=r._item===null?r:r._item.parent,new Cr(r._item===null?null:r._item.id,r._item===null?Os(r):null,null);do r=r._item.parent,n--;while(r!==e&&r._item.next===null);r!==e&&(r=r._item.next.content.type)}}}if(r===null)throw Ae();if(n===0&&r.constructor!==ut&&r!==e)return zI(r._item.parent,r._item)}return bc(e,e._length,-1)},zI=(n,e)=>{let t=null,r=null;return n._item===null?r=Os(n):t=z(n._item.id.client,n._item.id.clock),new Cr(t,r,e.id)},ko=(n,e,t,r)=>{let s=Tb(t,n);if(s===null||s.type!==e&&!Es(e,s.type._item))return null;let i=s.type,o=0;if(i.constructor===ut)o=s.index;else if(i._item===null||!i._item.deleted){let l=i._first,a=0;for(;a{let e=Kt.getState(n).undoManager;if(e!=null)return e.undo(),!0},ax=n=>{let e=Kt.getState(n).undoManager;if(e!=null)return e.redo(),!0},$I=new Set(["paragraph"]),UI=(n,e)=>!(n instanceof q)||!(n.content instanceof vt)||!(n.content.type instanceof wn||n.content.type instanceof Fe&&e.has(n.content.type.nodeName))||n.content.type._length===0,cx=({protectedNodes:n=$I,trackedOrigins:e=[],undoManager:t=null}={})=>new O({key:Kt,state:{init:(r,s)=>{let i=ee.getState(s),o=t;if(!o){let l=i.doc,a=new Set(l?l._observers.get("destroy"):[]);o=new Rs(i.type,{trackedOrigins:new Set([ee].concat(e)),deleteFilter:u=>UI(u,n),captureTransaction:u=>u.meta.get("addToHistory")!==!1});let c=l?l._observers.get("destroy"):new Set;o._yTiptapDocDestroyListeners=Array.from(c||[]).filter(u=>!a.has(u))}return{undoManager:o,prevSel:null,hasUndoOps:o.undoStack.length>0,hasRedoOps:o.redoStack.length>0}},apply:(r,s,i,o)=>{let l=ee.getState(o).binding,a=s.undoManager,c=a.undoStack.length>0,u=a.redoStack.length>0;return l?{undoManager:a,prevSel:Xf(l,i),hasUndoOps:c,hasRedoOps:u}:c!==s.hasUndoOps||u!==s.hasRedoOps?Object.assign({},s,{hasUndoOps:a.undoStack.length>0,hasRedoOps:a.redoStack.length>0}):s}},view:r=>{let s=ee.getState(r.state),i=Kt.getState(r.state).undoManager;return i.on("stack-item-added",({stackItem:o})=>{let l=s.binding;l&&o.meta.set(l,Kt.getState(r.state).prevSel)}),i.on("stack-item-popped",({stackItem:o})=>{let l=s.binding;l&&(l.beforeTransactionSelection=o.meta.get(l)||l.beforeTransactionSelection)}),{destroy:()=>{i.destroy();let o=i._yTiptapDocDestroyListeners;o&&i.doc&&(o.forEach(l=>i.doc.off("destroy",l)),i._yTiptapDocDestroyListeners=null)}}}});function ux(n){return!!n.getMeta(ee)}function FI(n,e){let t=ee.getState(n);return ko(t.doc,t.type,e,t.binding.mapping)||0}function dx(n,e){let t=ee.getState(n);return Nc(e,t.type,t.binding.mapping)}var Dc=class hx extends Sl{constructor(e,t){super(e),this.yRelativePosition=t}static fromJSON(e){return new hx(e.position,e.yRelativePosition)}toJSON(){return{position:this.position,yRelativePosition:this.yRelativePosition}}};function VI(n,e){let t=dx(e,n);return new Dc(n,t)}function HI(n,e,t){let r=n instanceof Dc?n.yRelativePosition:null;if(ux(e)&&r){let o=FI(t,r);return{position:new Dc(o,r),mapResult:null}}let s=Pd(n,e),i=s.position.position;return{position:new Dc(i,r??dx(t,i)),mapResult:s.mapResult}}var WI=F.create({name:"collaboration",priority:1e3,addOptions(){return{document:null,field:"default",fragment:null,provider:null}},addStorage(){return{isDisabled:!1}},onCreate(){this.editor.extensionManager.extensions.find(n=>n.name==="undoRedo")&&console.warn('[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-undo-redo".')},onBeforeCreate(){this.editor.utils.getUpdatedPosition=(n,e)=>HI(n,e,this.editor.state),this.editor.utils.createMappablePosition=n=>VI(n,this.editor.state)},addCommands(){return{undo:()=>({tr:n,state:e,dispatch:t})=>(n.setMeta("preventDispatch",!0),Kt.getState(e).undoManager.undoStack.length===0?!1:t?lx(e):!0),redo:()=>({tr:n,state:e,dispatch:t})=>(n.setMeta("preventDispatch",!0),Kt.getState(e).undoManager.redoStack.length===0?!1:t?ax(e):!0)}},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Mod-y":()=>this.editor.commands.redo(),"Shift-Mod-z":()=>this.editor.commands.redo()}},addProseMirrorPlugins(){let n=this.options.fragment?this.options.fragment:this.options.document.getXmlFragment(this.options.field),e=cx(this.options.yUndoOptions),t=e.spec.view;e.spec.view=i=>{let{undoManager:o}=Kt.getState(i.state);o.restore&&(o.restore(),o.restore=()=>{});let l=t?t(i):void 0;return{destroy:()=>{let a=o.trackedOrigins.has(o),c=o._observers;o.restore=()=>{a&&o.trackedOrigins.add(o),o.doc.on("afterTransaction",o.afterTransactionHandler),o._observers=c},l?.destroy&&l.destroy()}}};let r={...this.options.ySyncOptions,onFirstRender:this.options.onFirstRender};return[nx(n,r),e,this.editor.options.enableContentCheck&&new O({key:new P("filterInvalidContent"),filterTransaction:i=>{if(!ux(i))return!0;if(this.storage.isDisabled)return!1;if(!i.docChanged)return!0;try{return i.doc.check(),!0}catch(o){return this.storage.isDisabled=!0,this.editor.emit("contentError",{error:o,editor:this.editor,disableCollaboration:()=>{var l;(l=n.doc)==null||l.destroy()}}),!0}}})].filter(Boolean)}}),fx=WI;var px=zh;var mx=ya;var gx=ga;var sp,ip;if(typeof WeakMap<"u"){let n=new WeakMap;sp=e=>n.get(e),ip=(e,t)=>(n.set(e,t),t)}else{let n=[],t=0;sp=r=>{for(let s=0;s(t==10&&(t=0),n[t++]=r,n[t++]=s)}var se=class{constructor(n,e,t,r){this.width=n,this.height=e,this.map=t,this.problems=r}findCell(n){for(let e=0;e=t){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:y-b});break}let v=s+b*e;for(let C=0;Cr&&(i+=c.attrs.colspan)}}for(let o=0;o1&&(t=!0)}e==-1?e=i:e!=i&&(e=Math.max(e,i))}return e}function JI(n,e,t){n.problems||(n.problems=[]);let r={};for(let s=0;s0;e--)if(n.node(e).type.spec.tableRole=="row")return n.node(0).resolve(n.before(e+1));return null}function YI(n){for(let e=n.depth;e>0;e--){let t=n.node(e).type.spec.tableRole;if(t==="cell"||t==="header_cell")return n.node(e)}return null}function Rt(n){let e=n.selection.$head;for(let t=e.depth;t>0;t--)if(e.node(t).type.spec.tableRole=="row")return!0;return!1}function zc(n){let e=n.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;let t=Mr(e.$head)||GI(e.$head);if(t)return t;throw new RangeError(`No cell found around position ${e.head}`)}function GI(n){for(let e=n.nodeAfter,t=n.pos;e;e=e.firstChild,t++){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return n.doc.resolve(t)}for(let e=n.nodeBefore,t=n.pos;e;e=e.lastChild,t--){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return n.doc.resolve(t-e.nodeSize)}}function op(n){return n.parent.type.spec.tableRole=="row"&&!!n.nodeAfter}function XI(n){return n.node(0).resolve(n.pos+n.nodeAfter.nodeSize)}function cp(n,e){return n.depth==e.depth&&n.pos>=e.start(-1)&&n.pos<=e.end(-1)}function Ax(n,e,t){let r=n.node(-1),s=se.get(r),i=n.start(-1),o=s.nextCell(n.pos-i,e,t);return o==null?null:n.node(0).resolve(i+o)}function Rr(n,e,t=1){let r={...n,colspan:n.colspan-t};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,t),r.colwidth.some(s=>s>0)||(r.colwidth=null)),r}function Ex(n,e,t=1){let r={...n,colspan:n.colspan+t};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let s=0;su!=t.pos-i);a.unshift(t.pos-i);let c=a.map(u=>{let d=r.nodeAt(u);if(!d)throw new RangeError(`No cell with offset ${u} found`);let h=i+u+1;return new Hr(l.resolve(h),l.resolve(h+d.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=t}map(e,t){let r=e.resolve(t.map(this.$anchorCell.pos)),s=e.resolve(t.map(this.$headCell.pos));if(op(r)&&op(s)&&cp(r,s)){let i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?kn.rowSelection(r,s):i&&this.isColSelection()?kn.colSelection(r,s):new kn(r,s)}return E.between(r,s)}content(){let e=this.$anchorCell.node(-1),t=se.get(e),r=this.$anchorCell.start(-1),s=t.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},o=[];for(let a=s.top;a0||g>0){let y=p.attrs;if(m>0&&(y=Rr(y,0,m)),g>0&&(y=Rr(y,y.colspan-g,g)),f.lefts.bottom){let y={...p.attrs,rowspan:Math.min(f.bottom,s.bottom)-Math.max(f.top,s.top)};f.top0)return!1;let r=e+this.$anchorCell.nodeAfter.attrs.rowspan,s=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,s)==this.$headCell.node(-1).childCount}static colSelection(e,t=e){let r=e.node(-1),s=se.get(r),i=e.start(-1),o=s.findCell(e.pos-i),l=s.findCell(t.pos-i),a=e.node(0);return o.top<=l.top?(o.top>0&&(e=a.resolve(i+s.map[o.left])),l.bottom0&&(t=a.resolve(i+s.map[l.left])),o.bottom0)return!1;let o=s+this.$anchorCell.nodeAfter.attrs.colspan,l=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(o,l)==t.width}eq(e){return e instanceof kn&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,t=e){let r=e.node(-1),s=se.get(r),i=e.start(-1),o=s.findCell(e.pos-i),l=s.findCell(t.pos-i),a=e.node(0);return o.left<=l.left?(o.left>0&&(e=a.resolve(i+s.map[o.top*s.width])),l.right0&&(t=a.resolve(i+s.map[l.top*s.width])),o.right{e.push(de.node(r,r+t.nodeSize,{class:"selectedCell"}))}),X.create(n.doc,e)}function tD({$from:n,$to:e}){if(n.pos==e.pos||n.pos=0&&!(n.after(s+1)=0&&!(e.before(i+1)>e.start(i));i--,r--);return t==r&&/row|table/.test(n.node(s).type.spec.tableRole)}function nD({$from:n,$to:e}){let t,r;for(let s=n.depth;s>0;s--){let i=n.node(s);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){t=i;break}}for(let s=e.depth;s>0;s--){let i=e.node(s);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}return t!==r&&e.parentOffset===0}function rD(n,e,t){let r=(e||n).selection,s=(e||n).doc,i,o;if(r instanceof M&&(o=r.node.type.spec.tableRole)){if(o=="cell"||o=="header_cell")i=K.create(s,r.from);else if(o=="row"){let l=s.resolve(r.from+1);i=K.rowSelection(l,l)}else if(!t){let l=se.get(r.node),a=r.from+1,c=a+l.map[l.width*l.height-1];i=K.create(s,a+1,c)}}else r instanceof E&&tD(r)?i=E.create(s,r.from):r instanceof E&&nD(r)&&(i=E.create(s,r.$from.start(),r.$from.end()));return i&&(e||(e=n.tr)).setSelection(i),e}var sD=new P("fix-tables");function Rx(n,e,t,r){let s=n.childCount,i=e.childCount;e:for(let o=0,l=0;o{s.type.spec.tableRole=="table"&&(t=iD(n,s,i,t))};return e?e.doc!=n.doc&&Rx(e.doc,n.doc,0,r):n.doc.descendants(r),t}function iD(n,e,t,r){let s=se.get(e);if(!s.problems)return r;r||(r=n.tr);let i=[];for(let a=0;a0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);let p=[];for(let g=0;g0?-1:0;QI(e,r,s+i)&&(i=s==0||s==e.width?null:0);for(let o=0;o0&&s0&&e.map[l-1]==a||s0?-1:0;lD(e,r,s+l)&&(l=s==0||s==e.height?null:0);for(let c=0,u=e.width*s;c0&&s0&&d==e.map[u-e.width]){let h=t.nodeAt(d).attrs;n.setNodeMarkup(n.mapping.slice(l).map(d+r),null,{...h,rowspan:h.rowspan-1}),c+=h.colspan-1}else if(s0&&t[i]==t[i-1]||r.right0&&t[s]==t[s-n]||r.bottom0){let u=a+1+c.content.size,d=yx(c)?a+1:u;i.replaceWith(d+r.tableStart,u+r.tableStart,l)}i.setSelection(new K(i.doc.resolve(a+r.tableStart))),e(i)}return!0}function hp(n,e){let t=Ve(n.schema);return uD(({node:r})=>t[r.type.spec.tableRole])(n,e)}function uD(n){return(e,t)=>{let r=e.selection,s,i;if(r instanceof K){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;s=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var o;if(s=YI(r.$from),!s)return!1;i=(o=Mr(r.$from))===null||o===void 0?void 0:o.pos}if(s==null||i==null||s.attrs.colspan==1&&s.attrs.rowspan==1)return!1;if(t){let l=s.attrs,a=[],c=l.colwidth;l.rowspan>1&&(l={...l,rowspan:1}),l.colspan>1&&(l={...l,colspan:1});let u=Yt(e),d=e.tr;for(let f=0;f{o.attrs[n]!==e&&i.setNodeMarkup(l,null,{...o.attrs,[n]:e})}):i.setNodeMarkup(s.pos,null,{...s.nodeAfter.attrs,[n]:e}),r(i)}return!0}}function dD(n){return function(e,t){if(!Rt(e))return!1;if(t){let r=Ve(e.schema),s=Yt(e),i=e.tr,o=s.map.cellsInRect(n=="column"?{left:s.left,top:0,right:s.right,bottom:s.map.height}:n=="row"?{left:0,top:s.top,right:s.map.width,bottom:s.bottom}:s),l=o.map(a=>s.table.nodeAt(a));for(let a=0;a{let f=h+i.tableStart,p=o.doc.nodeAt(f);p&&o.setNodeMarkup(f,d,p.attrs)}),r(o)}return!0}}var Y$=_s("row",{useDeprecatedLogic:!0}),G$=_s("column",{useDeprecatedLogic:!0}),$x=_s("cell",{useDeprecatedLogic:!0});function hD(n,e){if(e<0){let t=n.nodeBefore;if(t)return n.pos-t.nodeSize;for(let r=n.index(-1)-1,s=n.before();r>=0;r--){let i=n.node(-1).child(r),o=i.lastChild;if(o)return s-1-o.nodeSize;s-=i.nodeSize}}else{if(n.index()0;r--)if(t.node(r).type.spec.tableRole=="table")return e&&e(n.tr.delete(t.before(r),t.after(r)).scrollIntoView()),!0;return!1}function Oc(n,e){let t=n.selection;if(!(t instanceof K))return!1;if(e){let r=n.tr,s=Ve(n.schema).cell.createAndFill().content;t.forEachCell((i,o)=>{i.content.eq(s)||r.replace(r.mapping.map(o+1),r.mapping.map(o+i.nodeSize-1),new S(s,0,0))}),r.docChanged&&e(r)}return!0}function fD(n){if(n.size===0)return null;let{content:e,openStart:t,openEnd:r}=n;for(;e.childCount==1&&(t>0&&r>0||e.child(0).type.spec.tableRole=="table");)t--,r--,e=e.child(0).content;let s=e.child(0),i=s.type.spec.tableRole,o=s.type.schema,l=[];if(i=="row")for(let a=0;a=0;o--){let{rowspan:l,colspan:a}=i.child(o).attrs;for(let c=s;c=e.length&&e.push(k.empty),t[s]r&&(h=h.type.createChecked(Rr(h.attrs,h.attrs.colspan,u+h.attrs.colspan-r),h.content)),c.push(h),u+=h.attrs.colspan;for(let f=1;fs&&(d=d.type.create({...d.attrs,rowspan:Math.max(1,s-d.attrs.rowspan)},d.content)),a.push(d)}i.push(k.from(a))}t=i,e=s}return{width:n,height:e,rows:t}}function gD(n,e,t,r,s,i,o){let l=n.doc.type.schema,a=Ve(l),c,u;if(s>e.width)for(let d=0,h=0;de.height){let d=[];for(let p=0,m=(e.height-1)*e.width;p=e.width?!1:t.nodeAt(e.map[m+p]).type==a.header_cell;d.push(g?u||(u=a.header_cell.createAndFill()):c||(c=a.cell.createAndFill()))}let h=a.row.create(null,k.from(d)),f=[];for(let p=e.height;p{if(!s)return!1;let i=t.selection;if(i instanceof K)return _c(t,r,I.near(i.$headCell,e));if(n!="horiz"&&!i.empty)return!1;let o=Fx(s,n,e);if(o==null)return!1;if(n=="horiz")return _c(t,r,I.near(t.doc.resolve(i.head+e),e));{let l=t.doc.resolve(o),a=Ax(l,n,e),c;return a?c=I.near(a,1):e<0?c=I.near(t.doc.resolve(l.before(-1)),-1):c=I.near(t.doc.resolve(l.after(-1)),1),_c(t,r,c)}}}function Lc(n,e){return(t,r,s)=>{if(!s)return!1;let i=t.selection,o;if(i instanceof K)o=i;else{let a=Fx(s,n,e);if(a==null)return!1;o=new K(t.doc.resolve(a))}let l=Ax(o.$headCell,n,e);return l?_c(t,r,new K(o.$anchorCell,l)):!1}}function wD(n,e){let t=n.state.doc,r=Mr(t.resolve(e));return r?(n.dispatch(n.state.tr.setSelection(new K(r))),!0):!1}function kD(n,e,t){if(!Rt(n.state))return!1;let r=fD(t),s=n.state.selection;if(s instanceof K){r||(r={width:1,height:1,rows:[k.from(lp(Ve(n.state.schema).cell,t))]});let i=s.$anchorCell.node(-1),o=s.$anchorCell.start(-1),l=se.get(i).rectBetween(s.$anchorCell.pos-o,s.$headCell.pos-o);return r=mD(r,l.right-l.left,l.bottom-l.top),xx(n.state,n.dispatch,o,l,r),!0}else if(r){let i=zc(n.state),o=i.start(-1);return xx(n.state,n.dispatch,o,se.get(i.node(-1)).findCell(i.pos-o),r),!0}else return!1}function bD(n,e){var t;if(e.button!=0||e.ctrlKey||e.metaKey)return;let r=Sx(n,e.target),s;if(e.shiftKey&&n.state.selection instanceof K)i(n.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(s=Mr(n.state.selection.$anchor))!=null&&((t=rp(n,e))===null||t===void 0?void 0:t.pos)!=s.pos)i(s,e),e.preventDefault();else if(!r)return;function i(a,c){let u=rp(n,c),d=Fn.getState(n.state)==null;if(!u||!cp(a,u))if(d)u=a;else return;let h=new K(a,u);if(d||!n.state.selection.eq(h)){let f=n.state.tr.setSelection(h);d&&f.setMeta(Fn,a.pos),n.dispatch(f)}}function o(){n.root.removeEventListener("mouseup",o),n.root.removeEventListener("dragstart",o),n.root.removeEventListener("mousemove",l),Fn.getState(n.state)!=null&&n.dispatch(n.state.tr.setMeta(Fn,-1))}function l(a){let c=a,u=Fn.getState(n.state),d;if(u!=null)d=n.state.doc.resolve(u);else if(Sx(n,c.target)!=r&&(d=rp(n,e),!d))return o();d&&i(d,c)}n.root.addEventListener("mouseup",o),n.root.addEventListener("dragstart",o),n.root.addEventListener("mousemove",l)}function Fx(n,e,t){if(!(n.state.selection instanceof E))return null;let{$head:r}=n.state.selection;for(let s=r.depth-1;s>=0;s--){let i=r.node(s);if((t<0?r.index(s):r.indexAfter(s))!=(t<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){let o=r.before(s),l=e=="vert"?t>0?"down":"up":t>0?"right":"left";return n.endOfTextblock(l)?o:null}}return null}function Sx(n,e){for(;e&&e!=n.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function rp(n,e){let t=n.posAtCoords({left:e.clientX,top:e.clientY});if(!t)return null;let{inside:r,pos:s}=t;return r>=0&&Mr(n.state.doc.resolve(r))||Mr(n.state.doc.resolve(s))}var xD=class{constructor(n,e){this.node=n,this.defaultCellMinWidth=e,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${e}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),ap(n,this.colgroup,this.table,e),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(n){return n.type!=this.node.type?!1:(this.node=n,ap(n,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(n){return n.type=="attributes"&&(n.target==this.table||this.colgroup.contains(n.target))}};function ap(n,e,t,r,s,i){let o=0,l=!0,a=e.firstChild,c=n.firstChild;if(c){for(let d=0,h=0;dnew r(d,t,h)),new SD(-1,!1)},apply(o,l){return l.apply(o)}},props:{attributes:o=>{let l=dt.getState(o);return l&&l.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(o,l)=>{vD(o,l,n,s)},mouseleave:o=>{CD(o)},mousedown:(o,l)=>{TD(o,l,e,t)}},decorations:o=>{let l=dt.getState(o);if(l&&l.activeHandle>-1)return ND(o,l.activeHandle)},nodeViews:{}}});return i}var SD=class Bc{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(e){let t=this,r=e.getMeta(dt);if(r&&r.setHandle!=null)return new Bc(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new Bc(t.activeHandle,r.setDragging);if(t.activeHandle>-1&&e.docChanged){let s=e.mapping.map(t.activeHandle,-1);return op(e.doc.resolve(s))||(s=-1),new Bc(s,t.dragging)}return t}};function vD(n,e,t,r){if(!n.editable)return;let s=dt.getState(n.state);if(s&&!s.dragging){let i=ED(e.target),o=-1;if(i){let{left:l,right:a}=i.getBoundingClientRect();e.clientX-l<=t?o=vx(n,e,"left",t):a-e.clientX<=t&&(o=vx(n,e,"right",t))}if(o!=s.activeHandle){if(!r&&o!==-1){let l=n.state.doc.resolve(o),a=l.node(-1),c=se.get(a),u=l.start(-1);if(c.colCount(l.pos-u)+l.nodeAfter.attrs.colspan-1==c.width-1)return}Hx(n,o)}}}function CD(n){if(!n.editable)return;let e=dt.getState(n.state);e&&e.activeHandle>-1&&!e.dragging&&Hx(n,-1)}function TD(n,e,t,r){var s;if(!n.editable)return!1;let i=(s=n.dom.ownerDocument.defaultView)!==null&&s!==void 0?s:window,o=dt.getState(n.state);if(!o||o.activeHandle==-1||o.dragging)return!1;let l=n.state.doc.nodeAt(o.activeHandle),a=AD(n,o.activeHandle,l.attrs);n.dispatch(n.state.tr.setMeta(dt,{setDragging:{startX:e.clientX,startWidth:a}}));function c(d){i.removeEventListener("mouseup",c),i.removeEventListener("mousemove",u);let h=dt.getState(n.state);h?.dragging&&(MD(n,h.activeHandle,Cx(h.dragging,d,t)),n.dispatch(n.state.tr.setMeta(dt,{setDragging:null})))}function u(d){if(!d.which)return c(d);let h=dt.getState(n.state);if(h&&h.dragging){let f=Cx(h.dragging,d,t);Tx(n,h.activeHandle,f,r)}}return Tx(n,o.activeHandle,a,r),i.addEventListener("mouseup",c),i.addEventListener("mousemove",u),e.preventDefault(),!0}function AD(n,e,{colspan:t,colwidth:r}){let s=r&&r[r.length-1];if(s)return s;let i=n.domAtPos(e),o=i.node.childNodes[i.offset].offsetWidth,l=t;if(r)for(let a=0;aID(n),renderHTML:n=>n.align?{style:`text-align: ${n.align}`}:{}}}var Fc=V.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:n=>{var e,t;let r=n.getAttribute("colwidth"),s=r?r.split(",").map(i=>parseInt(i,10)):null;if(!s){let i=(e=n.closest("table"))==null?void 0:e.querySelectorAll("colgroup > col"),o=Array.from(((t=n.parentElement)==null?void 0:t.children)||[]).indexOf(n);if(o&&o>-1&&i&&i[o]){let l=i[o].getAttribute("width");return l?[parseInt(l,10)]:null}}return s}},align:Jx()}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:n}){return["td",B(this.options.HTMLAttributes,n),0]}}),Vc=V.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:n=>{let e=n.getAttribute("colwidth");return e?e.split(",").map(r=>parseInt(r,10)):null}},align:Jx()}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:n}){return["th",B(this.options.HTMLAttributes,n),0]}}),Hc=V.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:n}){return["tr",B(this.options.HTMLAttributes,n),0]}});function pp(n,e){return e?["width",`${Math.max(e,n)}px`]:["min-width",`${n}px`]}function jx(n,e,t,r,s,i){var o;let l=0,a=!0,c=e.firstChild,u=n.firstChild;if(u!==null)for(let h=0,f=0;h{let r=n.nodes[t];r.spec.tableRole&&(e[r.spec.tableRole]=r)}),n.cached.tableNodeTypes=e,e}function _D(n,e,t,r,s){let i=LD(n),o=[],l=[];for(let c=0;c{let{selection:e}=n.state;if(!BD(e))return!1;let t=0,r=Rd(e.ranges[0].$from,i=>i.type.name==="table");return r?.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(t+=1)}),t===e.ranges.length?(n.commands.deleteTable(),!0):!1},zD="";function $D(n){return(n||"").replace(/\s+/g," ").trim()}function UD(n,e,t={}){var r;let s=(r=t.cellLineSeparator)!=null?r:zD;if(!n||!n.content||n.content.length===0)return"";let i=[];n.content.forEach(m=>{let g=[];m.content&&m.content.forEach(y=>{let w="";y.content&&Array.isArray(y.content)&&y.content.length>1?w=y.content.map(A=>e.renderChildren(A)).join(s):w=y.content?e.renderChildren(y.content):"";let b=$D(w),v=y.type==="tableHeader",C=DD(y.attrs);g.push({text:b,isHeader:v,align:C})}),i.push(g)});let o=i.reduce((m,g)=>Math.max(m,g.length),0);if(o===0)return"";let l=Array.from({length:o}).fill(0);i.forEach(m=>{var g;for(let y=0;yl[y]&&(l[y]=b),l[y]<3&&(l[y]=3)}});let a=(m,g)=>m+" ".repeat(Math.max(0,g-m.length)),c=i[0],u=c.some(m=>m.isHeader),d=Array.from({length:o}).fill(null);i.forEach(m=>{var g;for(let y=0;ys).filter(s=>(this.options.notAfter||[]).concat(t).includes(s.name));return[new O({key:e,appendTransaction:(s,i,o)=>{let{doc:l,tr:a,schema:c}=o,u=e.getState(o),d=l.content.size,h=c.nodes[t];if(!s.some(f=>f.getMeta(HM))&&u)return a.insert(d,h.create())},state:{init:(s,i)=>{let o=i.tr.doc.lastChild;return!J0({node:o,types:r})},apply:(s,i)=>{if(!s.docChanged||s.getMeta("__uniqueIDTransaction"))return i;let o=s.doc.lastChild;return!J0({node:o,types:r})}}})]}}),Q0=F.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:n,dispatch:e})=>zh(n,e),redo:()=>({state:n,dispatch:e})=>$h(n,e)}},addProseMirrorPlugins(){return[H0(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});var WM=F.create({name:"starterKit",addExtensions(){var n,e,t,r;let s=[];return this.options.bold!==!1&&s.push(e0.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(Zw.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(Eh.configure(this.options.bulletList)),this.options.code!==!1&&s.push(t0.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(n0.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(r0.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(K0.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(Y0.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(s0.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(i0.configure(this.options.heading)),this.options.undoRedo!==!1&&s.push(Q0.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&s.push(o0.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(l0.configure(this.options.italic)),this.options.listItem!==!1&&s.push(Mh.configure(this.options.listItem)),this.options.listKeymap!==!1&&s.push(Nh.configure((n=this.options)==null?void 0:n.listKeymap)),this.options.link!==!1&&s.push(Ch.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&s.push(Ih.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(O0.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(P0.configure(this.options.strike)),this.options.text!==!1&&s.push(L0.configure(this.options.text)),this.options.underline!==!1&&s.push(_0.configure((t=this.options)==null?void 0:t.underline)),this.options.trailingNode!==!1&&s.push(X0.configure((r=this.options)==null?void 0:r.trailingNode)),s}}),Z0=WM;var ye=()=>new Map,Ca=n=>{let e=ye();return n.forEach((t,r)=>{e.set(r,t)}),e},Ge=(n,e,t)=>{let r=n.get(e);return r===void 0&&n.set(e,r=t()),r},ek=(n,e)=>{let t=[];for(let[r,s]of n)t.push(e(s,r));return t},tk=(n,e)=>{for(let[t,r]of n)if(e(r,t))return!0;return!1};var tt=()=>new Set;var Ta=n=>n[n.length-1];var nk=(n,e)=>{for(let t=0;t{for(let t=0;t{for(let t=0;t{let t=new Array(n);for(let r=0;r{this.off(e,r),t(...s)};this.on(e,r)}off(e,t){let r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e))}emit(e,t){return Ct((this._observers.get(e)||ye()).values()).forEach(r=>r(...t))}destroy(){this._observers=ye()}},Ea=class{constructor(){this._observers=ye()}on(e,t){Ge(this._observers,e,tt).add(t)}once(e,t){let r=(...s)=>{this.off(e,r),t(...s)};this.on(e,r)}off(e,t){let r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e))}emit(e,t){return Ct((this._observers.get(e)||ye()).values()).forEach(r=>r(...t))}destroy(){this._observers=ye()}};var we=Math.floor;var gr=Math.abs;var Tt=(n,e)=>nn>e?n:e,v2=Number.isNaN,sk=Math.pow;var Ma=n=>n!==0?n<0:1/n<0;var cs=Number.MAX_SAFE_INTEGER,Fh=Number.MIN_SAFE_INTEGER,C2=1<<31;var ik=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&we(n)===n),T2=Number.isNaN,A2=Number.parseInt;var Vi=String.fromCharCode,jM=String.fromCodePoint,E2=Vi(65535),qM=n=>n.toLowerCase(),JM=/^\s*/g,KM=n=>n.replace(JM,""),YM=/([A-Z])/g,Hh=(n,e)=>KM(n.replace(YM,t=>`${e}${qM(t)}`));var GM=n=>{let e=unescape(encodeURIComponent(n)),t=e.length,r=new Uint8Array(t);for(let s=0;sds.encode(n),ok=ds?XM:GM;var us=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});us&&us.decode(new Uint8Array).length===1&&(us=null);var lk=(n,e)=>rk(e,()=>n).join("");var yr=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},fe=()=>new yr,hk=n=>{let e=fe();return n(e),Y(e)},Na=n=>{let e=n.cpos;for(let t=0;t{let e=new Uint8Array(Na(n)),t=0;for(let r=0;r{let t=n.cbuf.length;t-n.cpos{let t=n.cbuf.length;n.cpos===t&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(t*2),n.cpos=0),n.cbuf[n.cpos++]=e};var Ia=Ae;var D=(n,e)=>{for(;e>127;)Ae(n,128|127&e),e=we(e/128);Ae(n,127&e)},Da=(n,e)=>{let t=Ma(e);for(t&&(e=-e),Ae(n,(e>63?128:0)|(t?64:0)|63&e),e=we(e/64);e>0;)Ae(n,(e>127?128:0)|127&e),e=we(e/128)},Wh=new Uint8Array(3e4),ZM=Wh.length/3,eR=(n,e)=>{if(e.length{let t=unescape(encodeURIComponent(e)),r=t.length;D(n,r);for(let s=0;s{let t=n.cbuf.length,r=n.cpos,s=Tt(t-r,e.length),i=e.length-s;n.cbuf.set(e.subarray(0,s),r),n.cpos+=s,i>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(xt(t*2,i)),n.cbuf.set(e.subarray(s)),n.cpos=i)},Z=(n,e)=>{D(n,e.byteLength),ji(n,e)},jh=(n,e)=>{QM(n,e);let t=new DataView(n.cbuf.buffer,n.cpos,e);return n.cpos+=e,t},nR=(n,e)=>jh(n,4).setFloat32(0,e,!1),rR=(n,e)=>jh(n,8).setFloat64(0,e,!1),sR=(n,e)=>jh(n,8).setBigInt64(0,e,!1);var ck=new DataView(new ArrayBuffer(4)),iR=n=>(ck.setFloat32(0,n),ck.getFloat32(0)===n),Dn=(n,e)=>{switch(typeof e){case"string":Ae(n,119),pn(n,e);break;case"number":ik(e)&&gr(e)<=2147483647?(Ae(n,125),Da(n,e)):iR(e)?(Ae(n,124),nR(n,e)):(Ae(n,123),rR(n,e));break;case"bigint":Ae(n,122),sR(n,e);break;case"object":if(e===null)Ae(n,126);else if(hn(e)){Ae(n,117),D(n,e.length);for(let t=0;t0&&D(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};var uk=n=>{n.count>0&&(Da(n.encoder,n.count===1?n.s:-n.s),n.count>1&&D(n.encoder,n.count-2))},wr=class{constructor(){this.encoder=new yr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(uk(this),this.count=1,this.s=e)}toUint8Array(){return uk(this),Y(this.encoder)}};var dk=n=>{if(n.count>0){let e=n.diff*2+(n.count===1?0:1);Da(n.encoder,e),n.count>1&&D(n.encoder,n.count-2)}},fs=class{constructor(){this.encoder=new yr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(dk(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return dk(this),Y(this.encoder)}},Ra=class{constructor(){this.sarr=[],this.s="",this.lensE=new wr}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){let e=new yr;return this.sarr.push(this.s),this.s="",pn(e,this.sarr.join("")),ji(e,this.lensE.toUint8Array()),Y(e)}};var at=n=>new Error(n),Xe=()=>{throw at("Method unimplemented")},Ee=()=>{throw at("Unexpected case")};var fk=at("Unexpected end of array"),pk=at("Integer out of Range"),ps=class{constructor(e){this.arr=e,this.pos=0}},Et=n=>new ps(n),mk=n=>n.pos!==n.arr.length;var oR=(n,e)=>{let t=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,e);return n.pos+=e,t},ke=n=>oR(n,L(n));var kr=n=>n.arr[n.pos++];var L=n=>{let e=0,t=1,r=n.arr.length;for(;n.poscs)throw pk}throw fk},La=n=>{let e=n.arr[n.pos++],t=e&63,r=64,s=(e&64)>0?-1:1;if((e&128)===0)return s*t;let i=n.arr.length;for(;n.poscs)throw pk}throw fk};var lR=n=>{let e=L(n);if(e===0)return"";{let t=String.fromCodePoint(kr(n));if(--e<100)for(;e--;)t+=String.fromCodePoint(kr(n));else for(;e>0;){let r=e<1e4?e:1e4,s=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,t+=String.fromCodePoint.apply(null,s),e-=r}return decodeURIComponent(escape(t))}},aR=n=>us.decode(ke(n)),At=us?aR:lR;var qh=(n,e)=>{let t=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,e);return n.pos+=e,t},cR=n=>qh(n,4).getFloat32(0,!1),uR=n=>qh(n,8).getFloat64(0,!1),dR=n=>qh(n,8).getBigInt64(0,!1);var hR=[n=>{},n=>null,La,cR,uR,dR,n=>!1,n=>!0,At,n=>{let e=L(n),t={};for(let r=0;r{let e=L(n),t=[];for(let r=0;rhR[127-kr(n)](n),Ji=class extends ps{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),mk(this)?this.count=L(this)+1:this.count=-1),this.count--,this.s}};var br=class extends ps{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=La(this);let e=Ma(this.s);this.count=1,e&&(this.s=-this.s,this.count=L(this)+2)}return this.count--,this.s}};var gs=class extends ps{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=La(this),t=e&1;this.diff=we(e/2),this.count=1,t&&(this.count=L(this)+2)}return this.s+=this.diff,this.count--,this.s}},Pa=class{constructor(e){this.decoder=new br(e),this.str=At(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};var N2=crypto.subtle,gk=crypto.getRandomValues.bind(crypto);var fR=Math.random,Jh=()=>gk(new Uint32Array(1))[0];var yk=n=>n[we(fR()*n.length)],pR="10000000-1000-4000-8000"+-1e11,wk=()=>pR.replace(/[018]/g,n=>(n^Jh()&15>>n/4).toString(16));var ct=Date.now;var Kh=n=>new Promise(n);var O2=Promise.all.bind(Promise);var Yh=n=>n===void 0?null:n;var Gh=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},bk=new Gh,Xh=!0;try{typeof localStorage<"u"&&localStorage&&(bk=localStorage,Xh=!1)}catch{}var Ba=bk,xk=n=>Xh||addEventListener("storage",n),Sk=n=>Xh||removeEventListener("storage",n);var xr=Symbol("Equality"),za=(n,e)=>n===e||!!n?.[xr]?.(e)||!1;var Ck=n=>typeof n=="object",Tk=Object.assign,Zh=Object.keys;var Ak=(n,e)=>{for(let t in n)e(n[t],t)},Ek=(n,e)=>{let t=[];for(let r in n)t.push(e(n[r],r));return t};var Yi=n=>Zh(n).length;var Mk=n=>{for(let e in n)return!1;return!0},Pn=(n,e)=>{for(let t in n)if(!e(n[t],t))return!1;return!0},Gi=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),ef=(n,e)=>n===e||Yi(n)===Yi(e)&&Pn(n,(t,r)=>(t!==void 0||Gi(e,r))&&za(e[r],t)),yR=Object.freeze,tf=n=>{for(let e in n){let t=n[e];(typeof t=="object"||typeof t=="function")&&tf(n[e])}return yR(n)};var Qi=(n,e,t=0)=>{try{for(;tn;var Ln=(n,e)=>{if(n===e)return!0;if(n==null||e==null||n.constructor!==e.constructor&&(n.constructor||Object)!==(e.constructor||Object))return!1;if(n[xr]!=null)return n[xr](e);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),e=new Uint8Array(e);case Uint8Array:{if(n.byteLength!==e.byteLength)return!1;for(let t=0;te.includes(n);var mn=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ys=typeof window<"u"&&typeof document<"u"&&!mn,P2=typeof navigator<"u"?/Mac/.test(navigator.platform):!1,Ht,wR=[],kR=()=>{if(Ht===void 0)if(mn){Ht=ye();let n=process.argv,e=null;for(let t=0;t{if(n.length!==0){let[e,t]=n.split("=");Ht.set(`--${Hh(e,"-")}`,t),Ht.set(`-${Hh(e,"-")}`,t)}})):Ht=ye();return Ht},nf=n=>kR().has(n);var Zi=n=>mn?Yh(process.env[n.toUpperCase().replaceAll("-","_")]):Yh(Ba.getItem(n));var Ik=n=>nf("--"+n)||Zi(n)!==null,Dk=Ik("production"),bR=mn&&Nk(process.env.FORCE_COLOR,["true","1","2"]),Ok=bR||!nf("--no-colors")&&!Ik("no-color")&&(!mn||process.stdout.isTTY)&&(!mn||nf("--color")||Zi("COLORTERM")!==null||(Zi("TERM")||"").includes("color"));var Pk=n=>new Uint8Array(n),xR=(n,e,t)=>new Uint8Array(n,e,t),Lk=n=>new Uint8Array(n),SR=n=>{let e="";for(let t=0;tBuffer.from(n.buffer,n.byteOffset,n.byteLength).toString("base64"),CR=n=>{let e=atob(n),t=Pk(e.length);for(let r=0;r{let e=Buffer.from(n,"base64");return xR(e.buffer,e.byteOffset,e.byteLength)},Ua=ys?SR:vR,_k=ys?CR:TR;var Bk=n=>{let e=Pk(n.byteLength);return e.set(n),e},zk=n=>hk(e=>Dn(e,n));var sf=class{constructor(e,t){this.left=e,this.right=t}},Wt=(n,e)=>new sf(n,e);var of=n=>n.next()>=.5,Fa=(n,e,t)=>we(n.next()*(t+1-e)+e);var lf=(n,e,t)=>we(n.next()*(t+1-e)+e);var af=(n,e,t)=>lf(n,e,t);var ER=n=>Vi(af(n,97,122)),$k=(n,e=0,t=20)=>{let r=af(n,e,t),s="";for(let i=0;ie[af(n,0,e.length-1)];var RR=Symbol("0schema"),cf=class{constructor(){this._rerrs=[]}extend(e,t,r,s=null){this._rerrs.push({path:e,expected:t,has:r,message:s})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let r=this._rerrs[t];e.push(lk(" ",(this._rerrs.length-t)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(` +`)}},uf=(n,e)=>n===e?!0:n==null||e==null||n.constructor!==e.constructor?!1:n[xr]?za(n,e):hn(n)?Aa(n,t=>Ui(e,r=>uf(t,r))):Ck(n)?Pn(n,(t,r)=>uf(t,e[r])):!1,Oe=class{static _dilutes=!1;extends(e){let[t,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,t]=[t,r]),uf(t,r)}equals(e){return this.constructor===e.constructor&&Ln(this.shape,e.shape)}[RR](){return!0}[xr](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){Xe()}get nullable(){return vs(this,ec)}get optional(){return new Ha(this)}cast(e){return Uk(e,this),e}expect(e){return Uk(e,this),e}},eo=class extends Oe{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let r=e?.constructor===this.shape&&(this._c==null||this._c(e));return!r&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor!==this.shape?"Constructor match failed":"Check failed"),r}},pe=(n,e=null)=>new eo(n,e),_2=pe(eo),to=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=this.shape(e);return!r&&t?.extend(null,"custom prop",e?.constructor.name,"failed to check custom prop"),r}},be=n=>new to(n),B2=pe(to),xs=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=this.shape.some(s=>s===e);return!r&&t?.extend(null,this.shape.join(" | "),e.toString()),r}},Qa=(...n)=>new xs(n),Fk=pe(xs),NR=RegExp.escape||(n=>n.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Vk=n=>{if(Ss.check(n))return[NR(n)];if(Fk.check(n))return n.shape.map(e=>e+"");if(Jk.check(n))return["[+-]?\\d+.?\\d*"];if(Kk.check(n))return[".*"];if(Ga.check(n))return n.shape.map(Vk).flat(1);Ee()},df=class extends Oe{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Vk).map(t=>`(${t.join("|")})`).join("")+"$")}check(e,t){let r=this._r.exec(e)!=null;return!r&&t?.extend(null,this._r.toString(),e.toString(),"String doesn't match string template."),r}};var z2=pe(df),IR=Symbol("optional"),Ha=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=e===void 0||this.shape.check(e);return!r&&t?.extend(null,"undefined (optional)","()"),r}get[IR](){return!0}},DR=pe(Ha),Wa=class extends Oe{check(e,t){return t?.extend(null,"never",typeof e),!1}},$2=new Wa,U2=pe(Wa),ja=class n extends Oe{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new n(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,"object","null"),!1):Pn(this.shape,(r,s)=>{let i=this._isPartial&&!Gi(e,s)||r.check(e[s],t);return!i&&t?.extend(s.toString(),r.toString(),typeof e[s],"Object property does not match"),i})}},OR=n=>new ja(n),PR=pe(ja),LR=be(n=>n!=null&&(n.constructor===Object||n.constructor==null)),qa=class extends Oe{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&Pn(e,(r,s)=>{let i=this.shape.keys.check(s,t);return!i&&t?.extend(s+"","Record",typeof e,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(r,t)})}},Hk=(n,e)=>new qa(n,e),_R=pe(qa),Ja=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&Pn(this.shape,(r,s)=>{let i=r.check(e[s],t);return!i&&t?.extend(s.toString(),"Tuple",typeof r),i})}},BR=(...n)=>new Ja(n),F2=pe(Ja),Ka=class extends Oe{constructor(e){super(),this.shape=e.length===1?e[0]:new no(e)}check(e,t){let r=hn(e)&&Aa(e,s=>this.shape.check(s));return!r&&t?.extend(null,"Array",""),r}},Wk=(...n)=>new Ka(n),zR=pe(Ka),$R=be(n=>hn(n)),Ya=class extends Oe{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&t?.extend(null,this.shape.name,e?.constructor.name),r}},UR=(n,e=null)=>new Ya(n,e),V2=pe(Ya),FR=UR(Oe),hf=class extends Oe{constructor(e){super(),this.len=e.length-1,this.args=BR(...e.slice(-1)),this.res=e[this.len]}check(e,t){let r=e.constructor===Function&&e.length<=this.len;return!r&&t?.extend(null,"function",typeof e),r}};var VR=pe(hf),HR=be(n=>typeof n=="function"),ff=class extends Oe{constructor(e){super(),this.shape=e}check(e,t){let r=Aa(this.shape,s=>s.check(e,t));return!r&&t?.extend(null,"Intersectinon",typeof e),r}};var H2=pe(ff,n=>n.shape.length>0),no=class extends Oe{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let r=Ui(this.shape,s=>s.check(e,t));return t?.extend(null,"Union",typeof e),r}},vs=(...n)=>n.findIndex(e=>Ga.check(e))>=0?vs(...n.map(e=>ro(e)).map(e=>Ga.check(e)?e.shape:[e]).flat(1)):n.length===1?n[0]:new no(n),Ga=pe(no),jk=()=>!0,Xa=be(jk),WR=pe(to,n=>n.shape===jk),mf=be(n=>typeof n=="bigint"),jR=be(n=>n===mf),qk=be(n=>typeof n=="symbol"),W2=be(n=>n===qk),bs=be(n=>typeof n=="number"),Jk=be(n=>n===bs),Ss=be(n=>typeof n=="string"),Kk=be(n=>n===Ss),Za=be(n=>typeof n=="boolean"),qR=be(n=>n===Za),Yk=Qa(void 0),j2=pe(xs,n=>n.shape.length===1&&n.shape[0]===void 0),q2=Qa(void 0);var ec=Qa(null),JR=pe(xs,n=>n.shape.length===1&&n.shape[0]===null),J2=pe(Uint8Array),K2=pe(eo,n=>n.shape===Uint8Array),KR=vs(bs,Ss,ec,Yk,mf,Za,qk),Y2=(()=>{let n=Wk(Xa),e=Hk(Ss,Xa),t=vs(bs,Ss,ec,Za,n,e);return n.shape=t,e.shape.values=t,t})(),ro=n=>{if(FR.check(n))return n;if(LR.check(n)){let e={};for(let t in n)e[t]=ro(n[t]);return OR(e)}else{if($R.check(n))return vs(...n.map(ro));if(KR.check(n))return Qa(n);if(HR.check(n))return pe(n)}Ee()},Uk=Dk?()=>{}:(n,e)=>{let t=new cf;if(!e.check(n,t))throw at(`Expected value to be of type ${e.constructor.name}. +${t.toString()}`)},pf=class{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:ro(e),h:t}),this}else(e){return this.if(Xa,e)}done(){return(e,t)=>{for(let r=0;rnew pf(n),Gk=YR(Xa).if(Jk,(n,e)=>Fa(e,Fh,cs)).if(Kk,(n,e)=>$k(e)).if(qR,(n,e)=>of(e)).if(jR,(n,e)=>BigInt(Fa(e,Fh,cs))).if(Ga,(n,e)=>ks(e,Va(e,n.shape))).if(PR,(n,e)=>{let t={};for(let r in n.shape){let s=n.shape[r];if(DR.check(s)){if(of(e))continue;s=s.shape}t[r]=Gk(s,e)}return t}).if(zR,(n,e)=>{let t=[],r=lf(e,0,42);for(let s=0;sVa(e,n.shape)).if(JR,(n,e)=>null).if(VR,(n,e)=>{let t=ks(e,n.res);return()=>t}).if(WR,(n,e)=>ks(e,Va(e,[bs,Ss,ec,Yk,mf,Za,Wk(bs),Hk(vs("a","b","c"),bs)]))).if(_R,(n,e)=>{let t={},r=Fa(e,0,3);for(let s=0;sGk(ro(e),n);var gn=typeof document<"u"?document:{};var G2=be(n=>n.nodeType===eN);var X2=typeof DOMParser<"u"?new DOMParser:null;var Q2=be(n=>n.nodeType===XR);var Z2=be(n=>n.nodeType===QR);var Xk=n=>ek(n,(e,t)=>`${t}:${e};`).join("");var XR=gn.ELEMENT_NODE,QR=gn.TEXT_NODE,e$=gn.CDATA_SECTION_NODE,t$=gn.COMMENT_NODE,ZR=gn.DOCUMENT_NODE,n$=gn.DOCUMENT_TYPE_NODE,eN=gn.DOCUMENT_FRAGMENT_NODE,r$=be(n=>n.nodeType===ZR);var tc=n=>class{constructor(t){this._=t}destroy(){n(this._)}},tN=tc(clearTimeout),gf=(n,e)=>new tN(setTimeout(e,n)),i$=tc(clearInterval);var o$=tc(n=>typeof requestAnimationFrame<"u"&&cancelAnimationFrame(n));var l$=tc(n=>typeof cancelIdleCallback<"u"&&cancelIdleCallback(n));var jt=Symbol;var so=jt(),io=jt(),yf=jt(),wf=jt(),kf=jt(),oo=jt(),bf=jt(),Cs=jt(),xf=jt(),Zk=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=0;for(;r0&&t.push(e.join(""));r{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=ye(),s=[],i=0;for(;i0||a.length>0?(e.push("%c"+o),t.push(a)):e.push(o)}else break}}for(i>0&&(s=t,s.unshift(e.join("")));i{console.log(...eb(n)),nb.forEach(e=>e.print(n))},Sf=(...n)=>{console.warn(...eb(n)),n.unshift(Cs),nb.forEach(e=>e.print(n))};var nb=tt();var rb=n=>({[Symbol.iterator](){return this},next:n}),sb=(n,e)=>rb(()=>{let t;do t=n.next();while(!t.done&&!e(t.value));return t}),nc=(n,e)=>rb(()=>{let{done:t,value:r}=n.next();return{done:t,value:t?void 0:e(r)}});var As=class{constructor(e,t){this.clock=e,this.len=t}},$n=class{constructor(){this.clients=new Map}},yn=(n,e,t)=>e.clients.forEach((r,s)=>{let i=n.doc.store.clients.get(s);if(i!=null){let o=i[i.length-1],l=o.id.clock+o.length;for(let a=0,c=r[a];a{let t=0,r=n.length-1;for(;t<=r;){let s=we((t+r)/2),i=n[s],o=i.clock;if(o<=e){if(e{let t=n.clients.get(e.client);return t!==void 0&&dN(t,e.clock)!==null},Ff=n=>{n.clients.forEach(e=>{e.sort((s,i)=>s.clock-i.clock);let t,r;for(t=1,r=1;t=i.clock?e[r-1]=new As(s.clock,xt(s.len,i.clock+i.len-s.clock)):(r{let e=new $n;for(let t=0;t{if(!e.clients.has(s)){let i=r.slice();for(let o=t+1;o{Ge(n.clients,e,()=>[]).push(new As(t,r))},bc=()=>new $n,xb=n=>{let e=bc();return n.clients.forEach((t,r)=>{let s=[];for(let i=0;i0&&e.clients.set(r,s)}),e},Ds=(n,e)=>{D(n.restEncoder,e.clients.size),Ct(e.clients.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{n.resetDsCurVal(),D(n.restEncoder,t);let s=r.length;D(n.restEncoder,s);for(let i=0;i{let e=new $n,t=L(n.restDecoder);for(let r=0;r0){let o=Ge(e.clients,s,()=>[]);for(let l=0;l{let r=new $n,s=L(n.restDecoder);for(let i=0;i0){let i=new wn;return D(i.restEncoder,0),Ds(i,r),i.toUint8Array()}return null};var Sb=Jh,qt=class n extends mr{constructor({guid:e=wk(),collectionid:t=null,gc:r=!0,gcFilter:s=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=s,this.clientID=Sb(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new fc,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Kh(c=>{this.on("load",()=>{this.isLoaded=!0,c(this)})});let a=()=>Kh(c=>{let u=d=>{(d===void 0||d===!0)&&(this.off("sync",u),c())};this.on("sync",u)});this.on("sync",c=>{c===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=c===void 0||c===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=a()}load(){let e=this._item;e!==null&&!this.shouldLoad&&G(e.parent.doc,t=>{t.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ct(this.subdocs).map(e=>e.guid))}transact(e,t=null){return G(this,e,t)}get(e,t=me){let r=Ge(this.share,e,()=>{let i=new t;return i._integrate(this,null),i}),s=r.constructor;if(t!==me&&s!==t)if(s===me){let i=new t;i._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=r._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=r._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,yc)}getText(e=""){return this.get(e,kn)}getMap(e=""){return this.get(e,po)}getXmlElement(e=""){return this.get(e,Fe)}getXmlFragment(e=""){return this.get(e,Tr)}toJSON(){let e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Ct(this.subdocs).forEach(t=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new n({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,G(e.parent.doc,r=>{let s=t.doc;e.deleted||r.subdocsAdded.add(s),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},cc=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return L(this.restDecoder)}readDsLen(){return L(this.restDecoder)}},uc=class extends cc{readLeftID(){return z(L(this.restDecoder),L(this.restDecoder))}readRightID(){return z(L(this.restDecoder),L(this.restDecoder))}readClient(){return L(this.restDecoder)}readInfo(){return kr(this.restDecoder)}readString(){return At(this.restDecoder)}readParentInfo(){return L(this.restDecoder)===1}readTypeRef(){return L(this.restDecoder)}readLen(){return L(this.restDecoder)}readAny(){return ms(this.restDecoder)}readBuf(){return Bk(ke(this.restDecoder))}readJSON(){return JSON.parse(At(this.restDecoder))}readKey(){return At(this.restDecoder)}},Tf=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=L(this.restDecoder),this.dsCurrVal}readDsLen(){let e=L(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Un=class extends Tf{constructor(e){super(e),this.keys=[],L(e),this.keyClockDecoder=new gs(ke(e)),this.clientDecoder=new br(ke(e)),this.leftClockDecoder=new gs(ke(e)),this.rightClockDecoder=new gs(ke(e)),this.infoDecoder=new Ji(ke(e),kr),this.stringDecoder=new Pa(ke(e)),this.parentInfoDecoder=new Ji(ke(e),kr),this.typeRefDecoder=new br(ke(e)),this.lenDecoder=new br(ke(e))}readLeftID(){return new zn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new zn(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ms(this.restDecoder)}readBuf(){return ke(this.restDecoder)}readJSON(){return ms(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e{r=xt(r,e[0].id.clock);let s=St(e,r);D(n.restEncoder,e.length-s),n.writeClient(t),D(n.restEncoder,r);let i=e[s];i.write(n,r-i.id.clock);for(let o=s+1;o{let r=new Map;t.forEach((s,i)=>{oe(e,i)>s&&r.set(i,s)}),bo(e).forEach((s,i)=>{t.has(i)||r.set(i,0)}),D(n.restEncoder,r.size),Ct(r.entries()).sort((s,i)=>i[0]-s[0]).forEach(([s,i])=>{hN(n,e.clients.get(s),s,i)})},fN=(n,e)=>{let t=ye(),r=L(n.restDecoder);for(let s=0;s{let r=[],s=Ct(t.keys()).sort((f,p)=>f-p);if(s.length===0)return null;let i=()=>{if(s.length===0)return null;let f=t.get(s[s.length-1]);for(;f.refs.length===f.i;)if(s.pop(),s.length>0)f=t.get(s[s.length-1]);else return null;return f},o=i();if(o===null)return null;let l=new fc,a=new Map,c=(f,p)=>{let m=a.get(f);(m==null||m>p)&&a.set(f,p)},u=o.refs[o.i++],d=new Map,h=()=>{for(let f of r){let p=f.id.client,m=t.get(p);m?(m.i--,l.clients.set(p,m.refs.slice(m.i)),t.delete(p),m.i=0,m.refs=[]):l.clients.set(p,[f]),s=s.filter(g=>g!==p)}r.length=0};for(;;){if(u.constructor!==it){let p=Ge(d,u.id.client,()=>oe(e,u.id.client))-u.id.clock;if(p<0)r.push(u),c(u.id.client,u.id.clock-1),h();else{let m=u.getMissing(n,e);if(m!==null){r.push(u);let g=t.get(m)||{refs:[],i:0};if(g.refs.length===g.i)c(m,oe(e,m)),h();else{u=g.refs[g.i++];continue}}else(p===0||p0)u=r.pop();else if(o!==null&&o.i0){let f=new wn;return Hf(f,l,new Map),D(f.restEncoder,0),{missing:a,update:f.toUint8Array()}}return null},mN=(n,e)=>Hf(n,e.doc.store,e.beforeState),gN=(n,e,t,r=new Un(n))=>G(e,s=>{s.local=!1;let i=!1,o=s.doc,l=o.store,a=fN(r,o),c=pN(s,l,a),u=l.pendingStructs;if(u){for(let[h,f]of u.missing)if(ff)&&u.missing.set(h,f)}u.update=pc([u.update,c.update])}}else l.pendingStructs=c;let d=lb(r,s,l);if(l.pendingDs){let h=new Un(Et(l.pendingDs));L(h.restDecoder);let f=lb(h,s,l);d&&f?l.pendingDs=pc([d,f]):l.pendingDs=d||f}else l.pendingDs=d;if(i){let h=l.pendingStructs.update;l.pendingStructs=null,ko(s.doc,h)}},t,!1);var ko=(n,e,t,r=Un)=>{let s=Et(e);gN(s,n,t,new r(s))},vb=(n,e,t)=>ko(n,e,t,uc),yN=(n,e,t=new Map)=>{Hf(n,e.store,t),Ds(n,xb(e.store))},wN=(n,e=new Uint8Array([0]),t=new wn)=>{let r=Tb(e);yN(t,n,r);let s=[t.toUint8Array()];if(n.store.pendingDs&&s.push(n.store.pendingDs),n.store.pendingStructs&&s.push(IN(n.store.pendingStructs.update,e)),s.length>1){if(t.constructor===vr)return RN(s.map((i,o)=>o===0?i:ON(i)));if(t.constructor===wn)return pc(s)}return s[0]},Cb=(n,e)=>wN(n,e,new vr),kN=n=>{let e=new Map,t=L(n.restDecoder);for(let r=0;rkN(new cc(Et(n))),Ab=(n,e)=>(D(n.restEncoder,e.size),Ct(e.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{D(n.restEncoder,t),D(n.restEncoder,r)}),n),bN=(n,e)=>Ab(n,bo(e.store)),xN=(n,e=new hc)=>(n instanceof Map?Ab(e,n):bN(e,n),e.toUint8Array()),Eb=n=>xN(n,new dc),Af=class{constructor(){this.l=[]}},ab=()=>new Af,cb=(n,e)=>n.l.push(e),ub=(n,e)=>{let t=n.l,r=t.length;n.l=t.filter(s=>e!==s),r===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Mb=(n,e,t)=>Qi(n.l,[e,t]),zn=class{constructor(e,t){this.client=e,this.clock=t}},rc=(n,e)=>n===e||n!==null&&e!==null&&n.client===e.client&&n.clock===e.clock,z=(n,e)=>new zn(n,e);var Os=n=>{for(let[e,t]of n.doc.share.entries())if(t===n)return e;throw Ee()},Es=(n,e)=>{for(;e!==null;){if(e.parent===n)return!0;e=e.parent._item}return!1};var Cr=class{constructor(e,t,r,s=0){this.type=e,this.tname=t,this.item=r,this.assoc=s}};var Ef=class{constructor(e,t,r=0){this.type=e,this.index=t,this.assoc=r}},SN=(n,e,t=0)=>new Ef(n,e,t),sc=(n,e,t)=>{let r=null,s=null;return n._item===null?s=Os(n):r=z(n._item.id.client,n._item.id.clock),new Cr(r,s,e,t)},xc=(n,e,t=0)=>{let r=n._start;if(t<0){if(e===0)return sc(n,null,t);e--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>e)return sc(n,z(r.id.client,r.id.clock+e),t);e-=r.length}if(r.right===null&&t<0)return sc(n,r.lastId,t);r=r.right}return sc(n,null,t)};var vN=(n,e)=>{let t=Ts(n,e),r=e.clock-t.id.clock;return{item:t,diff:r}},Rb=(n,e,t=!0)=>{let r=e.store,s=n.item,i=n.type,o=n.tname,l=n.assoc,a=null,c=0;if(s!==null){if(oe(r,s.client)<=s.clock)return null;let u=t?$f(r,s):vN(r,s),d=u.item;if(!(d instanceof q))return null;if(a=d.parent,a._item===null||!a._item.deleted){c=d.deleted||!d.countable?0:u.diff+(l>=0?0:1);let h=d.left;for(;h!==null;)!h.deleted&&h.countable&&(c+=h.length),h=h.left}}else{if(o!==null)a=e.get(o);else if(i!==null){if(oe(r,i.client)<=i.clock)return null;let{item:u}=t?$f(r,i):{item:Ts(r,i)};if(u instanceof q&&u.content instanceof vt)a=u.content.type;else return null}else throw Ee();l>=0?c=a._length:c=0}return SN(a,c,n.assoc)};var Ms=class{constructor(e,t){this.ds=e,this.sv=t}};var Sc=(n,e)=>new Ms(n,e),w$=Sc(bc(),new Map),vc=n=>Sc(xb(n.store),bo(n.store)),Sr=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&(e.sv.get(n.id.client)||0)>n.id.clock&&!Er(e.ds,n.id),Mf=(n,e)=>{let t=Ge(n.meta,Mf,tt),r=n.doc.store;t.has(e)||(e.sv.forEach((s,i)=>{s{}),t.add(e))};var fc=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},bo=n=>{let e=new Map;return n.clients.forEach((t,r)=>{let s=t[t.length-1];e.set(r,s.id.clock+s.length)}),e},oe=(n,e)=>{let t=n.clients.get(e);if(t===void 0)return 0;let r=t[t.length-1];return r.id.clock+r.length},Nb=(n,e)=>{let t=n.clients.get(e.id.client);if(t===void 0)t=[],n.clients.set(e.id.client,t);else{let r=t[t.length-1];if(r.id.clock+r.length!==e.id.clock)throw Ee()}t.push(e)},St=(n,e)=>{let t=0,r=n.length-1,s=n[r],i=s.id.clock;if(i===e)return r;let o=we(e/(i+s.length-1)*r);for(;t<=r;){if(s=n[o],i=s.id.clock,i<=e){if(e{let t=n.clients.get(e.client);return t[St(t,e.clock)]},Ts=CN,Rf=(n,e,t)=>{let r=St(e,t),s=e[r];return s.id.clock{let t=n.doc.store.clients.get(e.client);return t[Rf(n,t,e.clock)]},db=(n,e,t)=>{let r=e.clients.get(t.client),s=St(r,t.clock),i=r[s];return t.clock!==i.id.clock+i.length-1&&i.constructor!==st&&r.splice(s+1,0,kc(n,i,t.clock-i.id.clock+1)),i},TN=(n,e,t)=>{let r=n.clients.get(e.id.client);r[St(r,e.id.clock)]=t},Ib=(n,e,t,r,s)=>{if(r===0)return;let i=t+r,o=Rf(n,e,t),l;do l=e[o++],ie.deleteSet.clients.size===0&&!tk(e.afterState,(t,r)=>e.beforeState.get(r)!==t)?!1:(Ff(e.deleteSet),mN(n,e),Ds(n,e.deleteSet),!0),fb=(n,e,t)=>{let r=e._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ge(n.changed,e,tt).add(t)},lc=(n,e)=>{let t=n[e],r=n[e-1],s=e;for(;s>0;t=r,r=n[--s-1]){if(r.deleted===t.deleted&&r.constructor===t.constructor&&r.mergeWith(t)){t instanceof q&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,r);continue}break}let i=e-s;return i&&n.splice(e+1-i,i),i},AN=(n,e,t)=>{for(let[r,s]of n.clients.entries()){let i=e.clients.get(r);for(let o=s.length-1;o>=0;o--){let l=s[o],a=l.clock+l.len;for(let c=St(i,l.clock),u=i[c];c{n.clients.forEach((t,r)=>{let s=e.clients.get(r);for(let i=t.length-1;i>=0;i--){let o=t[i],l=Tt(s.length-1,1+St(s,o.clock+o.len-1));for(let a=l,c=s[a];a>0&&c.id.clock>=o.clock;c=s[a])a-=1+lc(s,a)}})};var Db=(n,e)=>{if(el.push(()=>{(c._item===null||!c._item.deleted)&&c._callObserver(t,a)})),l.push(()=>{t.changedParentTypes.forEach((a,c)=>{c._dEH.l.length>0&&(c._item===null||!c._item.deleted)&&(a=a.filter(u=>u.target._item===null||!u.target._item.deleted),a.forEach(u=>{u.currentTarget=c,u._path=null}),a.sort((u,d)=>u.path.length-d.path.length),l.push(()=>{Mb(c._dEH,a,t)}))}),l.push(()=>r.emit("afterTransaction",[t,r])),l.push(()=>{t._needFormattingCleanup&&WN(t)})}),Qi(l,[])}finally{r.gc&&AN(i,s,r.gcFilter),EN(i,s),t.afterState.forEach((u,d)=>{let h=t.beforeState.get(d)||0;if(h!==u){let f=s.clients.get(d),p=xt(St(f,h),1);for(let m=f.length-1;m>=p;)m-=1+lc(f,m)}});for(let u=o.length-1;u>=0;u--){let{client:d,clock:h}=o[u].id,f=s.clients.get(d),p=St(f,h);p+11||p>0&&lc(f,p)}if(!t.local&&t.afterState.get(r.clientID)!==t.beforeState.get(r.clientID)&&(tb(Cs,so,"[yjs] ",io,oo,"Changed the client-id because another client seems to be using it."),r.clientID=Sb()),r.emit("afterTransactionCleanup",[t,r]),r._observers.has("update")){let u=new vr;hb(u,t)&&r.emit("update",[u.toUint8Array(),t.origin,r,t])}if(r._observers.has("updateV2")){let u=new wn;hb(u,t)&&r.emit("updateV2",[u.toUint8Array(),t.origin,r,t])}let{subdocsAdded:l,subdocsLoaded:a,subdocsRemoved:c}=t;(l.size>0||c.size>0||a.size>0)&&(l.forEach(u=>{u.clientID=r.clientID,u.collectionid==null&&(u.collectionid=r.collectionid),r.subdocs.add(u)}),c.forEach(u=>r.subdocs.delete(u)),r.emit("subdocs",[{loaded:a,added:l,removed:c},r,t]),c.forEach(u=>u.destroy())),n.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,n])):Db(n,e+1)}}},G=(n,e,t=null,r=!0)=>{let s=n._transactionCleanups,i=!1,o=null;n._transaction===null&&(i=!0,n._transaction=new Nf(n,t,r),s.push(n._transaction),s.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=e(n._transaction)}finally{if(i){let l=n._transaction===s[0];n._transaction=null,l&&Db(s,0)}}return o},If=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},pb=(n,e,t)=>{yn(n,t.deletions,r=>{r instanceof q&&e.scope.some(s=>s===n.doc||Es(s,r))&&Yf(r,!1)})},mb=(n,e,t)=>{let r=null,s=n.doc,i=n.scope;G(s,l=>{for(;e.length>0&&n.currStackItem===null;){let a=s.store,c=e.pop(),u=new Set,d=[],h=!1;yn(l,c.insertions,f=>{if(f instanceof q){if(f.redone!==null){let{item:p,diff:m}=$f(a,f.id);m>0&&(p=rt(l,z(p.id.client,p.id.clock+m))),f=p}!f.deleted&&i.some(p=>p===l.doc||Es(p,f))&&d.push(f)}}),yn(l,c.deletions,f=>{f instanceof q&&i.some(p=>p===l.doc||Es(p,f))&&!Er(c.insertions,f.id)&&u.add(f)}),u.forEach(f=>{h=Gb(l,f,u,c.insertions,n.ignoreRemoteMapChanges,n)!==null||h});for(let f=d.length-1;f>=0;f--){let p=d[f];n.deleteFilter(p)&&(p.delete(l),h=!0)}n.currStackItem=h?c:null}l.changed.forEach((a,c)=>{a.has(null)&&c._searchMarker&&(c._searchMarker.length=0)}),r=l},n);let o=n.currStackItem;if(o!=null){let l=r.changedParentTypes;n.emit("stack-item-popped",[{stackItem:o,type:t,changedParentTypes:l,origin:n},n]),n.currStackItem=null}return o},Rs=class extends mr{constructor(e,{captureTimeout:t=500,captureTransaction:r=a=>!0,deleteFilter:s=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:o=!1,doc:l=hn(e)?e[0].doc:e instanceof qt?e:e.doc}={}){super(),this.scope=[],this.doc=l,this.addToScope(e),this.deleteFilter=s,i.add(this),this.trackedOrigins=i,this.captureTransaction=r,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=o,this.captureTimeout=t,this.afterTransactionHandler=a=>{if(!this.captureTransaction(a)||!this.scope.some(g=>a.changedParentTypes.has(g)||g===this.doc)||!this.trackedOrigins.has(a.origin)&&(!a.origin||!this.trackedOrigins.has(a.origin.constructor)))return;let c=this.undoing,u=this.redoing,d=c?this.redoStack:this.undoStack;c?this.stopCapturing():u||this.clear(!1,!0);let h=new $n;a.afterState.forEach((g,y)=>{let w=a.beforeState.get(y)||0,b=g-w;b>0&&ao(h,y,w,b)});let f=ct(),p=!1;if(this.lastChange>0&&f-this.lastChange0&&!c&&!u){let g=d[d.length-1];g.deletions=Cf([g.deletions,a.deleteSet]),g.insertions=Cf([g.insertions,h])}else d.push(new If(a.deleteSet,h)),p=!0;!c&&!u&&(this.lastChange=f),yn(a,a.deleteSet,g=>{g instanceof q&&this.scope.some(y=>y===a.doc||Es(y,g))&&Yf(g,!0)});let m=[{stackItem:d[d.length-1],origin:a.origin,type:c?"redo":"undo",changedParentTypes:a.changedParentTypes},this];p?this.emit("stack-item-added",m):this.emit("stack-item-updated",m)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=hn(e)?e:[e],e.forEach(r=>{t.has(r)||(t.add(r),(r instanceof me?r.doc!==this.doc:r!==this.doc)&&Sf("[yjs#509] Not same Y.Doc"),this.scope.push(r))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(r=>{e&&(this.undoStack.forEach(s=>pb(r,this,s)),this.undoStack=[]),t&&(this.redoStack.forEach(s=>pb(r,this,s)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=mb(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=mb(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}};function*MN(n){let e=L(n.restDecoder);for(let t=0;tpc(n,uc,vr);var NN=(n,e)=>{if(n.constructor===st){let{client:t,clock:r}=n.id;return new st(z(t,r+e),n.length-e)}else if(n.constructor===it){let{client:t,clock:r}=n.id;return new it(z(t,r+e),n.length-e)}else{let t=n,{client:r,clock:s}=t.id;return new q(z(r,s+e),null,z(r,s+e-1),null,t.rightOrigin,t.parent,t.parentSub,t.content.splice(e))}},pc=(n,e=Un,t=wn)=>{if(n.length===1)return n[0];let r=n.map(u=>new e(Et(u))),s=r.map(u=>new co(u,!0)),i=null,o=new t,l=new uo(o);for(;s=s.filter(h=>h.curr!==null),s.sort((h,f)=>{if(h.curr.id.client===f.curr.id.client){let p=h.curr.id.clock-f.curr.id.clock;return p===0?h.curr.constructor===f.curr.constructor?0:h.curr.constructor===it?1:-1:p}else return f.curr.id.client-h.curr.id.client}),s.length!==0;){let u=s[0],d=u.curr.id.client;if(i!==null){let h=u.curr,f=!1;for(;h!==null&&h.id.clock+h.length<=i.struct.id.clock+i.struct.length&&h.id.client>=i.struct.id.client;)h=u.next(),f=!0;if(h===null||h.id.client!==d||f&&h.id.clock>i.struct.id.clock+i.struct.length)continue;if(d!==i.struct.id.client)_n(l,i.struct,i.offset),i={struct:h,offset:0},u.next();else if(i.struct.id.clock+i.struct.length0&&(i.struct.constructor===it?i.struct.length-=p:h=NN(h,p)),i.struct.mergeWith(h)||(_n(l,i.struct,i.offset),i={struct:h,offset:0},u.next())}}else i={struct:u.curr,offset:0},u.next();for(let h=u.curr;h!==null&&h.id.client===d&&h.id.clock===i.struct.id.clock+i.struct.length&&h.constructor!==it;h=u.next())_n(l,i.struct,i.offset),i={struct:h,offset:0}}i!==null&&(_n(l,i.struct,i.offset),i=null),Wf(l);let a=r.map(u=>Vf(u)),c=Cf(a);return Ds(o,c),o.toUint8Array()},IN=(n,e,t=Un,r=wn)=>{let s=Tb(e),i=new r,o=new uo(i),l=new t(Et(n)),a=new co(l,!1);for(;a.curr;){let u=a.curr,d=u.id.client,h=s.get(d)||0;if(a.curr.constructor===it){a.next();continue}if(u.id.clock+u.length>h)for(_n(o,u,xt(h-u.id.clock,0)),a.next();a.curr&&a.curr.id.client===d;)_n(o,a.curr,0),a.next();else for(;a.curr&&a.curr.id.client===d&&a.curr.id.clock+a.curr.length<=h;)a.next()}Wf(o);let c=Vf(l);return Ds(i,c),i.toUint8Array()};var Ob=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:Y(n.encoder.restEncoder)}),n.encoder.restEncoder=fe(),n.written=0)},_n=(n,e,t)=>{n.written>0&&n.currClient!==e.id.client&&Ob(n),n.written===0&&(n.currClient=e.id.client,n.encoder.writeClient(e.id.client),D(n.encoder.restEncoder,e.id.clock+t)),e.write(n.encoder,t),n.written++},Wf=n=>{Ob(n);let e=n.encoder.restEncoder;D(e,n.clientStructs.length);for(let t=0;t{let s=new t(Et(n)),i=new co(s,!1),o=new r,l=new uo(o);for(let c=i.curr;c!==null;c=i.next())_n(l,e(c),0);Wf(l);let a=Vf(s);return Ds(o,a),o.toUint8Array()};var ON=n=>DN(n,Rk,Un,vr),gb="You must not compute changes after the event-handler fired.",Ns=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=PN(this.currentTarget,this.target))}deletes(e){return Er(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw at(gb);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(s=>{if(s!==null){let i=t._map.get(s),o,l;if(this.adds(i)){let a=i.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(i))if(a!==null&&this.deletes(a))o="delete",l=Ta(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",l=Ta(a.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=Ta(i.content.getContent());else return;e.set(s,{action:o,oldValue:l})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw at(gb);let t=this.target,r=tt(),s=tt(),i=[];if(e={added:r,deleted:s,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let l=null,a=()=>{l&&i.push(l)};for(let c=t._start;c!==null;c=c.right)c.deleted?this.deletes(c)&&!this.adds(c)&&((l===null||l.delete===void 0)&&(a(),l={delete:0}),l.delete+=c.length,s.add(c)):this.adds(c)?((l===null||l.insert===void 0)&&(a(),l={insert:[]}),l.insert=l.insert.concat(c.content.getContent()),r.add(c)):((l===null||l.retain===void 0)&&(a(),l={retain:0}),l.retain+=c.length);l!==null&&l.retain===void 0&&a()}this._changes=e}return e}},PN=(n,e)=>{let t=[];for(;e._item!==null&&e!==n;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else{let r=0,s=e._item.parent._start;for(;s!==e._item&&s!==null;)!s.deleted&&s.countable&&(r+=s.length),s=s.right;t.unshift(r)}e=e._item.parent}return t},Ue=()=>{Sf("Invalid access: Add Yjs type to a document before reading data.")},Pb=80,jf=0,Df=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=jf++}},LN=n=>{n.timestamp=jf++},Lb=(n,e,t)=>{n.p.marker=!1,n.p=e,e.marker=!0,n.index=t,n.timestamp=jf++},_N=(n,e,t)=>{if(n.length>=Pb){let r=n.reduce((s,i)=>s.timestamp{if(n._start===null||e===0||n._searchMarker===null)return null;let t=n._searchMarker.length===0?null:n._searchMarker.reduce((i,o)=>gr(e-i.index)e;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);return t!==null&&gr(t.index-s){for(let r=n.length-1;r>=0;r--){let s=n[r];if(t>0){let i=s.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(s.index-=i.length);if(i===null||i.marker===!0){n.splice(r,1);continue}s.p=i,i.marker=!0}(e0&&e===s.index)&&(s.index=xt(e,s.index+t))}};var Tc=(n,e,t)=>{let r=n,s=e.changedParentTypes;for(;Ge(s,n,()=>[]).push(t),n._item!==null;)n=n._item.parent;Mb(r._eH,t,e)},me=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ab(),this._dEH=ab(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Xe()}clone(){throw Xe()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){cb(this._eH,e)}observeDeep(e){cb(this._dEH,e)}unobserve(e){ub(this._eH,e)}unobserveDeep(e){ub(this._dEH,e)}toJSON(){}},_b=(n,e,t)=>{n.doc??Ue(),e<0&&(e=n._length+e),t<0&&(t=n._length+t);let r=t-e,s=[],i=n._start;for(;i!==null&&r>0;){if(i.countable&&!i.deleted){let o=i.content.getContent();if(o.length<=e)e-=o.length;else{for(let l=e;l0;l++)s.push(o[l]),r--;e=0}}i=i.right}return s},Bb=n=>{n.doc??Ue();let e=[],t=n._start;for(;t!==null;){if(t.countable&&!t.deleted){let r=t.content.getContent();for(let s=0;s{let t=[],r=n._start;for(;r!==null;){if(r.countable&&Sr(r,e)){let s=r.content.getContent();for(let i=0;i{let t=0,r=n._start;for(n.doc??Ue();r!==null;){if(r.countable&&!r.deleted){let s=r.content.getContent();for(let i=0;i{let t=[];return fo(n,(r,s)=>{t.push(e(r,s,n))}),t},BN=n=>{let e=n._start,t=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(t===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};t=e.content.getContent(),r=0,e=e.right}let s=t[r++];return t.length<=r&&(t=null),{done:!1,value:s}}}},$b=(n,e)=>{n.doc??Ue();let t=Cc(n,e),r=n._start;for(t!==null&&(r=t.p,e-=t.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e{let s=t,i=n.doc,o=i.clientID,l=i.store,a=t===null?e._start:t.right,c=[],u=()=>{c.length>0&&(s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new Is(c)),s.integrate(n,0),c=[])};r.forEach(d=>{if(d===null)c.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:c.push(d);break;default:switch(u(),d.constructor){case Uint8Array:case ArrayBuffer:s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new yo(new Uint8Array(d))),s.integrate(n,0);break;case qt:s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new wo(d)),s.integrate(n,0);break;default:if(d instanceof me)s=new q(z(o,oe(l,o)),s,s&&s.lastId,a,a&&a.id,e,null,new vt(d)),s.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},Ub=()=>at("Length exceeded!"),Fb=(n,e,t,r)=>{if(t>e._length)throw Ub();if(t===0)return e._searchMarker&&ho(e._searchMarker,t,r.length),mc(n,e,null,r);let s=t,i=Cc(e,t),o=e._start;for(i!==null&&(o=i.p,t-=i.index,t===0&&(o=o.prev,t+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(t<=o.length){t{let s=(e._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:e._start}).p;if(s)for(;s.right;)s=s.right;return mc(n,e,s,t)},Vb=(n,e,t,r)=>{if(r===0)return;let s=t,i=r,o=Cc(e,t),l=e._start;for(o!==null&&(l=o.p,t-=o.index);l!==null&&t>0;l=l.right)!l.deleted&&l.countable&&(t0&&l!==null;)l.deleted||(r0)throw Ub();e._searchMarker&&ho(e._searchMarker,s,-i+r)},gc=(n,e,t)=>{let r=e._map.get(t);r!==void 0&&r.delete(n)},Jf=(n,e,t,r)=>{let s=e._map.get(t)||null,i=n.doc,o=i.clientID,l;if(r==null)l=new Is([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Is([r]);break;case Uint8Array:l=new yo(r);break;case qt:l=new wo(r);break;default:if(r instanceof me)l=new vt(r);else throw new Error("Unexpected content type")}new q(z(o,oe(i.store,o)),s,s&&s.lastId,null,null,e,t,l).integrate(n,0)},Kf=(n,e)=>{n.doc??Ue();let t=n._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},Hb=n=>{let e={};return n.doc??Ue(),n._map.forEach((t,r)=>{t.deleted||(e[r]=t.content.getContent()[t.length-1])}),e},Wb=(n,e)=>{n.doc??Ue();let t=n._map.get(e);return t!==void 0&&!t.deleted};var $N=(n,e)=>{let t={};return n._map.forEach((r,s)=>{let i=r;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&Sr(i,e)&&(t[s]=i.content.getContent()[i.length-1])}),t},ic=n=>(n.doc??Ue(),sb(n._map.entries(),e=>!e[1].deleted)),Of=class extends Ns{},yc=class n extends me{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){let t=new n;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof me?t.clone():t)),e}get length(){return this.doc??Ue(),this._length}_callObserver(e,t){super._callObserver(e,t),Tc(this,e,new Of(this,e))}insert(e,t){this.doc!==null?G(this.doc,r=>{Fb(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){this.doc!==null?G(this.doc,t=>{zN(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc!==null?G(this.doc,r=>{Vb(r,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return $b(this,e)}toArray(){return Bb(this)}slice(e=0,t=this.length){return _b(this,e,t)}toJSON(){return this.map(e=>e instanceof me?e.toJSON():e)}map(e){return zb(this,e)}forEach(e){fo(this,e)}[Symbol.iterator](){return BN(this)}_write(e){e.writeTypeRef(lI)}},UN=n=>new yc,Pf=class extends Ns{constructor(e,t,r){super(e,t),this.keysChanged=r}},po=class n extends me{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((r,s)=>{this.set(s,r)}),this._prelimContent=null}_copy(){return new n}clone(){let e=new n;return this.forEach((t,r)=>{e.set(r,t instanceof me?t.clone():t)}),e}_callObserver(e,t){Tc(this,e,new Pf(this,e,t))}toJSON(){this.doc??Ue();let e={};return this._map.forEach((t,r)=>{if(!t.deleted){let s=t.content.getContent()[t.length-1];e[r]=s instanceof me?s.toJSON():s}}),e}get size(){return[...ic(this)].length}keys(){return nc(ic(this),e=>e[0])}values(){return nc(ic(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return nc(ic(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ue(),this._map.forEach((t,r)=>{t.deleted||e(t.content.getContent()[t.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?G(this.doc,t=>{gc(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return this.doc!==null?G(this.doc,r=>{Jf(r,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return Kf(this,e)}has(e){return Wb(this,e)}clear(){this.doc!==null?G(this.doc,e=>{this.forEach(function(t,r,s){gc(e,s,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(aI)}},FN=n=>new po,Bn=(n,e)=>n===e||typeof n=="object"&&typeof e=="object"&&n&&e&&ef(n,e),mo=class{constructor(e,t,r,s){this.left=e,this.right=t,this.index=r,this.currentAttributes=s}forward(){this.right===null&&Ee(),this.right.content.constructor===le?this.right.deleted||Ps(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}},yb=(n,e,t)=>{for(;e.right!==null&&t>0;)e.right.content.constructor===le?e.right.deleted||Ps(e.currentAttributes,e.right.content):e.right.deleted||(t{let s=new Map,i=r?Cc(e,t):null;if(i){let o=new mo(i.p.left,i.p,i.index,s);return yb(n,o,t-i.index)}else{let o=new mo(null,e._start,0,s);return yb(n,o,t)}},jb=(n,e,t,r)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===le&&Bn(r.get(t.right.content.key),t.right.content.value));)t.right.deleted||r.delete(t.right.content.key),t.forward();let s=n.doc,i=s.clientID;r.forEach((o,l)=>{let a=t.left,c=t.right,u=new q(z(i,oe(s.store,i)),a,a&&a.lastId,c,c&&c.id,e,null,new le(l,o));u.integrate(n,0),t.right=u,t.forward()})},Ps=(n,e)=>{let{key:t,value:r}=e;r===null?n.delete(t):n.set(t,r)},qb=(n,e)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===le&&Bn(e[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},Jb=(n,e,t,r)=>{let s=n.doc,i=s.clientID,o=new Map;for(let l in r){let a=r[l],c=t.currentAttributes.get(l)??null;if(!Bn(c,a)){o.set(l,c);let{left:u,right:d}=t;t.right=new q(z(i,oe(s.store,i)),u,u&&u.lastId,d,d&&d.id,e,null,new le(l,a)),t.right.integrate(n,0),t.forward()}}return o},vf=(n,e,t,r,s)=>{t.currentAttributes.forEach((h,f)=>{s[f]===void 0&&(s[f]=null)});let i=n.doc,o=i.clientID;qb(t,s);let l=Jb(n,e,t,s),a=r.constructor===String?new Mt(r):r instanceof me?new vt(r):new Ar(r),{left:c,right:u,index:d}=t;e._searchMarker&&ho(e._searchMarker,t.index,a.getLength()),u=new q(z(o,oe(i.store,o)),c,c&&c.lastId,u,u&&u.id,e,null,a),u.integrate(n,0),t.right=u,t.index=d,t.forward(),jb(n,e,t,l)},wb=(n,e,t,r,s)=>{let i=n.doc,o=i.clientID;qb(t,s);let l=Jb(n,e,t,s);e:for(;t.right!==null&&(r>0||l.size>0&&(t.right.deleted||t.right.content.constructor===le));){if(!t.right.deleted)switch(t.right.content.constructor){case le:{let{key:a,value:c}=t.right.content,u=s[a];if(u!==void 0){if(Bn(u,c))l.delete(a);else{if(r===0)break e;l.set(a,c)}t.right.delete(n)}else t.currentAttributes.set(a,c);break}default:r0){let a="";for(;r>0;r--)a+=` +`;t.right=new q(z(o,oe(i.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new Mt(a)),t.right.integrate(n,0),t.forward()}jb(n,e,t,l)},Kb=(n,e,t,r,s)=>{let i=e,o=ye();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===le){let c=i.content;o.set(c.key,c)}i=i.right}let l=0,a=!1;for(;e!==i;){if(t===e&&(a=!0),!e.deleted){let c=e.content;if(c.constructor===le){let{key:u,value:d}=c,h=r.get(u)??null;(o.get(u)!==c||h===d)&&(e.delete(n),l++,!a&&(s.get(u)??null)===d&&h!==d&&(h===null?s.delete(u):s.set(u,h))),!a&&!e.deleted&&Ps(s,c)}}e=e.right}return l},VN=(n,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;let t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===le){let r=e.content.key;t.has(r)?e.delete(n):t.add(r)}e=e.left}},HN=n=>{let e=0;return G(n.doc,t=>{let r=n._start,s=n._start,i=ye(),o=Ca(i);for(;s;)s.deleted===!1&&(s.content.constructor===le?Ps(o,s.content):(e+=Kb(t,r,s,i,o),i=Ca(o),r=s)),s=s.right}),e},WN=n=>{let e=new Set,t=n.doc;for(let[r,s]of n.afterState.entries()){let i=n.beforeState.get(r)||0;s!==i&&Ib(n,t.store.clients.get(r),i,s,o=>{!o.deleted&&o.content.constructor===le&&o.constructor!==st&&e.add(o.parent)})}G(t,r=>{yn(n,n.deleteSet,s=>{if(s instanceof st||!s.parent._hasFormatting||e.has(s.parent))return;let i=s.parent;s.content.constructor===le?e.add(i):VN(r,s)});for(let s of e)HN(s)})},kb=(n,e,t)=>{let r=t,s=Ca(e.currentAttributes),i=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case vt:case Ar:case Mt:t{s===null?this.childListChanged=!0:this.keysChanged.add(s)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];G(e,r=>{let s=new Map,i=new Map,o=this.target._start,l=null,a={},c="",u=0,d=0,h=()=>{if(l!==null){let f=null;switch(l){case"delete":d>0&&(f={delete:d}),d=0;break;case"insert":(typeof c=="object"||c.length>0)&&(f={insert:c},s.size>0&&(f.attributes={},s.forEach((p,m)=>{p!==null&&(f.attributes[m]=p)}))),c="";break;case"retain":u>0&&(f={retain:u},Mk(a)||(f.attributes=Tk({},a))),u=0;break}f&&t.push(f),l=null}};for(;o!==null;){switch(o.content.constructor){case vt:case Ar:this.adds(o)?this.deletes(o)||(h(),l="insert",c=o.content.getContent()[0],h()):this.deletes(o)?(l!=="delete"&&(h(),l="delete"),d+=1):o.deleted||(l!=="retain"&&(h(),l="retain"),u+=1);break;case Mt:this.adds(o)?this.deletes(o)||(l!=="insert"&&(h(),l="insert"),c+=o.content.str):this.deletes(o)?(l!=="delete"&&(h(),l="delete"),d+=o.length):o.deleted||(l!=="retain"&&(h(),l="retain"),u+=o.length);break;case le:{let{key:f,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){let m=s.get(f)??null;Bn(m,p)?p!==null&&o.delete(r):(l==="retain"&&h(),Bn(p,i.get(f)??null)?delete a[f]:a[f]=p)}}else if(this.deletes(o)){i.set(f,p);let m=s.get(f)??null;Bn(m,p)||(l==="retain"&&h(),a[f]=m)}else if(!o.deleted){i.set(f,p);let m=a[f];m!==void 0&&(Bn(m,p)?m!==null&&o.delete(r):(l==="retain"&&h(),p===null?delete a[f]:a[f]=p))}o.deleted||(l==="insert"&&h(),Ps(s,o.content));break}}o=o.right}for(h();t.length>0;){let f=t[t.length-1];if(f.retain!==void 0&&f.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},kn=class n extends me{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ue(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new n}clone(){let e=new n;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);let r=new Lf(this,e,t);Tc(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ue();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Mt&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?G(this.doc,r=>{let s=new mo(null,this._start,0,new Map);for(let i=0;i0)&&vf(r,this,s,l,o.attributes||{})}else o.retain!==void 0?wb(r,this,s,o.retain,o.attributes||{}):o.delete!==void 0&&kb(r,s,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,r){this.doc??Ue();let s=[],i=new Map,o=this.doc,l="",a=this._start;function c(){if(l.length>0){let d={},h=!1;i.forEach((p,m)=>{h=!0,d[m]=p});let f={insert:l};h&&(f.attributes=d),s.push(f),l=""}}let u=()=>{for(;a!==null;){if(Sr(a,e)||t!==void 0&&Sr(a,t))switch(a.content.constructor){case Mt:{let d=i.get("ychange");e!==void 0&&!Sr(a,e)?(d===void 0||d.user!==a.id.client||d.type!=="removed")&&(c(),i.set("ychange",r?r("removed",a.id):{type:"removed"})):t!==void 0&&!Sr(a,t)?(d===void 0||d.user!==a.id.client||d.type!=="added")&&(c(),i.set("ychange",r?r("added",a.id):{type:"added"})):d!==void 0&&(c(),i.delete("ychange")),l+=a.content.str;break}case vt:case Ar:{c();let d={insert:a.content.getContent()[0]};if(i.size>0){let h={};d.attributes=h,i.forEach((f,p)=>{h[p]=f})}s.push(d);break}case le:Sr(a,e)&&(c(),Ps(i,a.content));break}a=a.right}c()};return e||t?G(o,d=>{e&&Mf(d,e),t&&Mf(d,t),u()},"cleanup"):u(),s}insert(e,t,r){if(t.length<=0)return;let s=this.doc;s!==null?G(s,i=>{let o=oc(i,this,e,!r);r||(r={},o.currentAttributes.forEach((l,a)=>{r[a]=l})),vf(i,this,o,t,r)}):this._pending.push(()=>this.insert(e,t,r))}insertEmbed(e,t,r){let s=this.doc;s!==null?G(s,i=>{let o=oc(i,this,e,!r);vf(i,this,o,t,r||{})}):this._pending.push(()=>this.insertEmbed(e,t,r||{}))}delete(e,t){if(t===0)return;let r=this.doc;r!==null?G(r,s=>{kb(s,oc(s,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,r){if(t===0)return;let s=this.doc;s!==null?G(s,i=>{let o=oc(i,this,e,!1);o.right!==null&&wb(i,this,o,t,r)}):this._pending.push(()=>this.format(e,t,r))}removeAttribute(e){this.doc!==null?G(this.doc,t=>{gc(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){this.doc!==null?G(this.doc,r=>{Jf(r,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return Kf(this,e)}getAttributes(){return Hb(this)}_write(e){e.writeTypeRef(cI)}},jN=n=>new kn,lo=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ue()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Fe||t.constructor===Tr)&&t._start!==null)e=t._start;else for(;e!==null;){let r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},Tr=class n extends me{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof me?t.clone():t)),e}get length(){return this.doc??Ue(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new lo(this,e)}querySelector(e){e=e.toUpperCase();let r=new lo(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Ct(new lo(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Tc(this,e,new _f(this,t,e))}toString(){return zb(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},r){let s=e.createDocumentFragment();return r!==void 0&&r._createAssociation(s,this),fo(this,i=>{s.insertBefore(i.toDOM(e,t,r),null)}),s}insert(e,t){this.doc!==null?G(this.doc,r=>{Fb(r,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)G(this.doc,r=>{let s=e&&e instanceof me?e._item:e;mc(r,this,s,t)});else{let r=this._prelimContent,s=e===null?0:r.findIndex(i=>i===e)+1;if(s===0&&e!==null)throw at("Reference item not found");r.splice(s,0,...t)}}delete(e,t=1){this.doc!==null?G(this.doc,r=>{Vb(r,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Bb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return $b(this,e)}slice(e=0,t=this.length){return _b(this,e,t)}forEach(e){fo(this,e)}_write(e){e.writeTypeRef(dI)}},qN=n=>new Tr,Fe=class n extends Tr{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,s)=>{this.setAttribute(s,r)}),this._prelimAttrs=null}_copy(){return new n(this.nodeName)}clone(){let e=new n(this.nodeName),t=this.getAttributes();return Ak(t,(r,s)=>{e.setAttribute(s,r)}),e.insert(0,this.toArray().map(r=>r instanceof me?r.clone():r)),e}toString(){let e=this.getAttributes(),t=[],r=[];for(let l in e)r.push(l);r.sort();let s=r.length;for(let l=0;l0?" "+t.join(" "):"";return`<${i}${o}>${super.toString()}`}removeAttribute(e){this.doc!==null?G(this.doc,t=>{gc(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){this.doc!==null?G(this.doc,r=>{Jf(r,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return Kf(this,e)}hasAttribute(e){return Wb(this,e)}getAttributes(e){return e?$N(this,e):Hb(this)}toDOM(e=document,t={},r){let s=e.createElement(this.nodeName),i=this.getAttributes();for(let o in i){let l=i[o];typeof l=="string"&&s.setAttribute(o,l)}return fo(this,o=>{s.appendChild(o.toDOM(e,t,r))}),r!==void 0&&r._createAssociation(s,this),s}_write(e){e.writeTypeRef(uI),e.writeKey(this.nodeName)}},JN=n=>new Fe(n.readKey()),_f=class extends Ns{constructor(e,t,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}},Bf=class n extends po{constructor(e){super(),this.hookName=e}_copy(){return new n(this.hookName)}clone(){let e=new n(this.hookName);return this.forEach((t,r)=>{e.set(r,t)}),e}toDOM(e=document,t={},r){let s=t[this.hookName],i;return s!==void 0?i=s.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(hI),e.writeKey(this.hookName)}},KN=n=>new Bf(n.readKey()),ut=class n extends kn{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new n}clone(){let e=new n;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,r){let s=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(s,this),s}toString(){return this.toDelta().map(e=>{let t=[];for(let s in e.attributes){let i=[];for(let o in e.attributes[s])i.push({key:o,value:e.attributes[s][o]});i.sort((o,l)=>o.keys.nodeName=0;s--)r+=``;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(fI)}},YN=n=>new ut,go=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Xe()}mergeWith(e){return!1}write(e,t,r){throw Xe()}integrate(e,t){throw Xe()}},GN=0,st=class extends go{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Nb(e.doc.store,this)}write(e,t){e.writeInfo(GN),e.writeLen(this.length-t)}getMissing(e,t){return null}},yo=class n{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new n(this.content)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},XN=n=>new yo(n.readBuf()),wc=class n{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new n(this.len)}splice(e){let t=new n(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){ao(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},QN=n=>new wc(n.readLen()),Yb=(n,e)=>new qt({guid:n,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),wo=class n{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new n(Yb(this.doc.guid,this.opts))}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},ZN=n=>new wo(Yb(n.readString(),n.readAny())),Ar=class n{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new n(this.embed)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},eI=n=>new Ar(n.readJSON()),le=class n{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new n(this.key,this.value)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){let r=t.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},tI=n=>new le(n.readKey(),n.readJSON()),zf=class n{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new n(this.arr)}splice(e){let t=new n(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let r=this.arr.length;e.writeLen(r-t);for(let s=t;s{let e=n.readLen(),t=[];for(let r=0;r{let e=n.readLen(),t=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",t.str="\uFFFD"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}},iI=n=>new Mt(n.readString()),oI=[UN,FN,jN,JN,qN,KN,YN],lI=0,aI=1,cI=2,uI=3,dI=4,hI=5,fI=6,vt=class n{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new n(this.type._copy())}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},pI=n=>new vt(oI[n.readTypeRef()](n)),$f=(n,e)=>{let t=e,r=0,s;do r>0&&(t=z(t.client,t.clock+r)),s=Ts(n,t),r=t.clock-s.id.clock,t=s.redone;while(t!==null&&s instanceof q);return{item:s,diff:r}},Yf=(n,e)=>{for(;n!==null&&n.keep!==e;)n.keep=e,n=n.parent._item},kc=(n,e,t)=>{let{client:r,clock:s}=e.id,i=new q(z(r,s+t),e,z(r,s+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&i.markDeleted(),e.keep&&(i.keep=!0),e.redone!==null&&(i.redone=z(e.redone.client,e.redone.clock+t)),e.right=i,i.right!==null&&(i.right.left=i),n._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),e.length=t,i},bb=(n,e)=>Ui(n,t=>Er(t.deletions,e)),Gb=(n,e,t,r,s,i)=>{let o=n.doc,l=o.store,a=o.clientID,c=e.redone;if(c!==null)return rt(n,c);let u=e.parent._item,d=null,h;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!t.has(u)||Gb(n,u,t,r,s,i)===null))return null;for(;u.redone!==null;)u=rt(n,u.redone)}let f=u===null?e.parent:u.content.type;if(e.parentSub===null){for(d=e.left,h=e;d!==null;){let y=d;for(;y!==null&&y.parent._item!==u;)y=y.redone===null?null:rt(n,y.redone);if(y!==null&&y.parent._item===u){d=y;break}d=d.left}for(;h!==null;){let y=h;for(;y!==null&&y.parent._item!==u;)y=y.redone===null?null:rt(n,y.redone);if(y!==null&&y.parent._item===u){h=y;break}h=h.right}}else{if(h=null,e.right&&!s){for(d=e;d!==null&&d.right!==null&&(d.right.redone||Er(r,d.right.id)||bb(i.undoStack,d.right.id)||bb(i.redoStack,d.right.id));)for(d=d.right;d.redone;)d=rt(n,d.redone);if(d&&d.right!==null)return null}else d=f._map.get(e.parentSub)||null;d!==null&&d.parent._item!==u&&(d=f._map.get(e.parentSub)||null)}let p=oe(l,a),m=z(a,p),g=new q(m,d,d&&d.lastId,h,h&&h.id,f,e.parentSub,e.content.copy());return e.redone=m,Yf(g,!0),g.integrate(n,0),g},q=class n extends go{constructor(e,t,r,s,i,o,l,a){super(e,a.getLength()),this.origin=r,this.left=t,this.right=s,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=oe(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=oe(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===zn&&this.id.client!==this.parent.client&&this.parent.clock>=oe(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=db(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=rt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===st||this.right&&this.right.constructor===st)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===n?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===n&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===zn){let r=Ts(t,this.parent);r.constructor===st?this.parent=null:this.parent=r.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=db(e,e.doc.store,z(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,s;if(r!==null)s=r.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;let i=new Set,o=new Set;for(;s!==null&&s!==this.right;){if(o.add(s),i.add(s),rc(this.origin,s.origin)){if(s.id.client{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),ao(e.deleteSet,this.id.client,this.id.clock,this.length),fb(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Ee();this.content.gc(e),t?TN(e,this,new st(this.id,this.length)):this.content=new wc(this.length)}write(e,t){let r=t>0?z(this.id.client,this.id.clock+t-1):this.origin,s=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&31|(r===null?0:128)|(s===null?0:64)|(i===null?0:32);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),s!==null&&e.writeRightID(s),r===null&&s===null){let l=this.parent;if(l._item!==void 0){let a=l._item;if(a===null){let c=Os(l);e.writeParentInfo(!0),e.writeString(c)}else e.writeParentInfo(!1),e.writeLeftID(a.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===zn?(e.writeParentInfo(!1),e.writeLeftID(l)):Ee();i!==null&&e.writeString(i)}this.content.write(e,t)}},Xb=(n,e)=>mI[e&31](n),mI=[()=>{Ee()},QN,nI,XN,iI,eI,tI,pI,sI,ZN,()=>{Ee()}],gI=10,it=class extends go{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){Ee()}write(e,t){e.writeInfo(gI),D(e.restEncoder,this.length-t)}getMissing(e,t){return null}},Qb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Zb="__ $YJS$ __";Qb[Zb]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Qb[Zb]=!0;var Xf=3e4,Ac=class extends Ea{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let t=ct();this.getLocalState()!==null&&Xf/2<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let r=[];this.meta.forEach((s,i)=>{i!==this.clientID&&Xf<=t-s.lastUpdated&&this.states.has(i)&&r.push(i)}),r.length>0&&Ec(this,r,"timeout")},we(Xf/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,r=this.meta.get(t),s=r===void 0?0:r.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:s,lastUpdated:ct()});let o=[],l=[],a=[],c=[];e===null?c.push(t):i==null?e!=null&&o.push(t):(l.push(t),Ln(i,e)||a.push(t)),(o.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:o,updated:a,removed:c},"local"]),this.emit("update",[{added:o,updated:l,removed:c},"local"])}setLocalStateField(e,t){let r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:t})}getStates(){return this.states}},Ec=(n,e,t)=>{let r=[];for(let s=0;s0&&(n.emit("change",[{added:[],updated:[],removed:r},t]),n.emit("update",[{added:[],updated:[],removed:r},t]))},Ls=(n,e,t=n.states)=>{let r=e.length,s=fe();D(s,r);for(let i=0;i{let r=Et(e),s=ct(),i=[],o=[],l=[],a=[],c=L(r);for(let u=0;u0||l.length>0||a.length>0)&&n.emit("change",[{added:i,updated:l,removed:a},t]),(i.length>0||o.length>0||a.length>0)&&n.emit("update",[{added:i,updated:o,removed:a},t])};var tx=()=>{let n=!0;return(e,t)=>{if(n){n=!1;try{e()}finally{n=!0}}else t!==void 0&&t()}};var wI=/[\uD800-\uDBFF]/,kI=/[\uDC00-\uDFFF]/,bI=(n,e)=>{let t=0,r=0;for(;t0&&wI.test(n[t-1])&&t--;r+t0&&kI.test(n[n.length-r])&&r--,{index:t,remove:n.length-t-r,insert:e.slice(t,e.length-r)}},nx=bI;var Jt=(n,e)=>n>>>e|n<<32-e,xI=n=>Jt(n,2)^Jt(n,13)^Jt(n,22),SI=n=>Jt(n,6)^Jt(n,11)^Jt(n,25),vI=n=>Jt(n,7)^Jt(n,18)^n>>>3,CI=n=>Jt(n,17)^Jt(n,19)^n>>>10,TI=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),AI=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qf=class{constructor(){let e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(AI),this._W=new Uint32Array(e,64,64)}_updateHash(){let e=this._H,t=this._W;for(let d=16;d<64;d++)t[d]=CI(t[d-2])+t[d-7]+vI(t[d-15])+t[d-16];let r=e[0],s=e[1],i=e[2],o=e[3],l=e[4],a=e[5],c=e[6],u=e[7];for(let d=0,h,f;d<64;d++)h=u+SI(l)+(l&a^~l&c)+TI[d]+t[d]>>>0,f=xI(r)+(r&s^r&i^s&i)>>>0,u=c,c=a,a=l,l=o+h>>>0,o=i,i=s,s=r,r=h+f>>>0;e[0]+=r,e[1]+=s,e[2]+=i,e[3]+=o,e[4]+=l,e[5]+=a,e[6]+=c,e[7]+=u}digest(e){let t=0;for(;t+56<=e.length;){let o=0;for(;o<16&&t+3=0&&t>>(3-l)*8;return i}},rx=n=>new Qf().digest(n);var ee=new P("y-sync"),Kt=new P("y-undo"),N$=new P("yjs-cursor"),MI=n=>{for(let t=6;tUa(MI(rx(zk(n))));var Rc=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&e.sv.get(n.id.client)>n.id.clock&&!Er(e.ds,n.id),NI=[{light:"#ecd44433",dark:"#ecd444"}],II=(n,e,t)=>{if(!n.has(t)){if(n.sizer.add(s)),e=e.filter(s=>!r.has(s))}n.set(t,yk(e))}return n.get(t)},ox=(n,{colors:e=NI,colorMapping:t=new Map,permanentUserData:r=null,onFirstRender:s=()=>{},mapping:i}={})=>{let o=!1,l=new ep(n,i),a=new O({props:{editable:c=>{let u=ee.getState(c);return u.snapshot==null&&u.prevSnapshot==null}},key:ee,state:{init:(c,u)=>({type:n,doc:n.doc,binding:l,snapshot:null,prevSnapshot:null,isChangeOrigin:!1,isUndoRedoOperation:!1,addToHistory:!0,colors:e,colorMapping:t,permanentUserData:r}),apply:(c,u)=>{let d=c.getMeta(ee);if(d!==void 0){u=Object.assign({},u);for(let h in d)u[h]=d[h]}return u.addToHistory=c.getMeta("addToHistory")!==!1,u.isChangeOrigin=d!==void 0&&!!d.isChangeOrigin,u.isUndoRedoOperation=d!==void 0&&!!d.isChangeOrigin&&!!d.isUndoRedoOperation,l.prosemirrorView!==null&&d!==void 0&&(d.snapshot!=null||d.prevSnapshot!=null)&&gf(0,()=>{l.prosemirrorView!=null&&(d.restore==null?l._renderSnapshot(d.snapshot,d.prevSnapshot,u):(l._renderSnapshot(d.snapshot,d.snapshot,u),delete u.restore,delete u.snapshot,delete u.prevSnapshot,l.mux(()=>{l._prosemirrorChanged(l.prosemirrorView.state.doc)})))}),u}},view:c=>(l.initView(c),i==null&&l._forceRerender(),s(),{update:()=>{let u=a.getState(c.state);if(u.snapshot==null&&u.prevSnapshot==null&&(o||c.state.doc.content.findDiffStart(c.state.doc.type.createAndFill().content)!==null)){if(o=!0,u.addToHistory===!1&&!u.isChangeOrigin){let d=Kt.getState(c.state),h=d&&d.undoManager;h&&h.stopCapturing()}l.mux(()=>{u.doc.transact(d=>{d.meta.set("addToHistory",u.addToHistory),l._prosemirrorChanged(c.state.doc)},ee)})}},destroy:()=>{l.destroy()}})});return a},DI=(n,e,t)=>{if(e!==null&&e.anchor!==null&&e.head!==null)if(e.type==="all")n.setSelection(new Ne(n.doc));else if(e.type==="node"){let r=Mr(t.doc,t.type,e.anchor,t.mapping);r!==null&&n.setSelection(OI(n,r))}else if(e.type==="nodeRange"){let r=Mr(t.doc,t.type,e.anchor,t.mapping),s=Mr(t.doc,t.type,e.head,t.mapping),i=PI(n,r,s,e.depth);i!==null&&n.setSelection(i)}else{let r=Mr(t.doc,t.type,e.anchor,t.mapping),s=Mr(t.doc,t.type,e.head,t.mapping);r!==null&&s!==null&&n.setSelection(A.between(n.doc.resolve(r),n.doc.resolve(s)))}},OI=(n,e)=>{let t=n.doc.resolve(e);return t.nodeAfter?M.create(n.doc,e):A.near(t)},PI=(n,e,t,r)=>{if(e===null||t===null)return null;let s=Math.min(Math.max(e,0),n.doc.content.size),i=Math.min(Math.max(t,0),n.doc.content.size);try{let o=N.fromJSON(n.doc,{type:"nodeRange",anchor:s,head:i,depth:r});return o.ranges.length?o:A.near(n.doc.resolve(s))}catch{return A.near(n.doc.resolve(s))}},Zf=(n,e)=>{let t=e.selection.jsonID;return{type:t,depth:t==="nodeRange"?e.selection.depth:void 0,anchor:Ic(e.selection.anchor,n.type,n.mapping),head:Ic(e.selection.head,n.type,n.mapping)}},ep=class{constructor(e,t=new Map){this.type=e,this.prosemirrorView=null,this.mux=tx(),this.mapping=t,this.isOMark=new Map,this._observeFunction=this._typeChanged.bind(this),this.doc=e.doc,this.beforeTransactionSelection=null,this.beforeAllTransactions=()=>{this.beforeTransactionSelection===null&&this.prosemirrorView!=null&&(this.beforeTransactionSelection=Zf(this,this.prosemirrorView.state))},this.afterAllTransactions=()=>{this.beforeTransactionSelection=null},this._domSelectionInView=null}get _tr(){return this.prosemirrorView.state.tr.setMeta("addToHistory",!1)}_isLocalCursorInView(){return this.prosemirrorView.hasFocus()?(ys&&this._domSelectionInView===null&&(gf(0,()=>{this._domSelectionInView=null}),this._domSelectionInView=this._isDomSelectionInView()),this._domSelectionInView):!1}_isDomSelectionInView(){let e=this.prosemirrorView._root.getSelection();if(e==null||e.anchorNode==null)return!1;let t=this.prosemirrorView._root.createRange();t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.getClientRects().length===0&&t.startContainer&&t.collapsed&&t.selectNodeContents(t.startContainer);let s=t.getBoundingClientRect(),i=gn.documentElement;return s.bottom>=0&&s.right>=0&&s.left<=(window.innerWidth||i.clientWidth||0)&&s.top<=(window.innerHeight||i.clientHeight||0)}renderSnapshot(e,t){t||(t=Sc(bc(),new Map)),this.prosemirrorView.dispatch(this._tr.setMeta(ee,{snapshot:e,prevSnapshot:t}))}unrenderSnapshot(){this.mapping.clear(),this.mux(()=>{let e=this.type.toArray().map(r=>Mc(r,this.prosemirrorView.state.schema,this)).filter(r=>r!==null),t=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(e),0,0));t.setMeta(ee,{snapshot:null,prevSnapshot:null}),this.prosemirrorView.dispatch(t)})}_forceRerender(){this.mapping.clear(),this.mux(()=>{let e=this.beforeTransactionSelection!==null?null:this.prosemirrorView.state.selection,t=this.type.toArray().map(s=>Mc(s,this.prosemirrorView.state.schema,this)).filter(s=>s!==null),r=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(t),0,0));if(e){let s=Tt(xt(e.anchor,0),r.doc.content.size),i=Tt(xt(e.head,0),r.doc.content.size);r.setSelection(A.create(r.doc,s,i))}this.prosemirrorView.dispatch(r.setMeta(ee,{isChangeOrigin:!0,binding:this}))})}_renderSnapshot(e,t,r){let s=this.doc,i=this.type;if(e||(e=vc(this.doc)),e instanceof Uint8Array||t instanceof Uint8Array)if((!(e instanceof Uint8Array)||!(t instanceof Uint8Array))&&Ee(),s=new qt({gc:!1}),ko(s,t),t=vc(s),ko(s,e),e=vc(s),i._item===null){let o=Array.from(this.doc.share.keys()).find(l=>this.doc.share.get(l)===this.type);i=s.getXmlFragment(o)}else{let o=s.store.clients.get(i._item.id.client)??[],l=St(o,i._item.id.clock);i=o[l].content.type}this.mapping.clear(),this.mux(()=>{s.transact(o=>{let l=r.permanentUserData;l&&l.dss.forEach(d=>{yn(o,d,h=>{})});let a=(d,h)=>{let f=d==="added"?l.getUserByClientId(h.client):l.getUserByDeletedId(h);return{user:f,type:d,color:II(r.colorMapping,r.colors,f)}},c=qf(i,new Ms(t.ds,e.sv)).map(d=>!d._item.deleted||Rc(d._item,e)||Rc(d._item,t)?Mc(d,this.prosemirrorView.state.schema,{mapping:new Map,isOMark:new Map},e,t,a):null).filter(d=>d!==null),u=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(c),0,0));this.prosemirrorView.dispatch(u.setMeta(ee,{isChangeOrigin:!0}))},ee)})}_typeChanged(e,t){if(this.prosemirrorView==null)return;let r=ee.getState(this.prosemirrorView.state);if(e.length===0||r.snapshot!=null||r.prevSnapshot!=null){this.renderSnapshot(r.snapshot,r.prevSnapshot);return}this.mux(()=>{let s=(l,a)=>this.mapping.delete(a);yn(t,t.deleteSet,l=>{if(l.constructor===q){let a=l.content.type;a&&this.mapping.delete(a)}}),t.changed.forEach(s),t.changedParentTypes.forEach(s);let i=this.type.toArray().map(l=>lx(l,this.prosemirrorView.state.schema,this)).filter(l=>l!==null),o=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new S(k.from(i),0,0));DI(o,this.beforeTransactionSelection,this),o=o.setMeta(ee,{isChangeOrigin:!0,isUndoRedoOperation:t.origin instanceof Rs}),this.beforeTransactionSelection!==null&&this._isLocalCursorInView()&&o.scrollIntoView(),this.prosemirrorView.dispatch(o)})}_prosemirrorChanged(e){this.doc.transact(()=>{np(this.doc,this.type,e,this),this.beforeTransactionSelection=Zf(this,this.prosemirrorView.state)},ee)}initView(e){this.prosemirrorView!=null&&this.destroy(),this.prosemirrorView=e,this.doc.on("beforeAllTransactions",this.beforeAllTransactions),this.doc.on("afterAllTransactions",this.afterAllTransactions),this.type.observeDeep(this._observeFunction)}destroy(){this.prosemirrorView!=null&&(this.prosemirrorView=null,this.type.unobserveDeep(this._observeFunction),this.doc.off("beforeAllTransactions",this.beforeAllTransactions),this.doc.off("afterAllTransactions",this.afterAllTransactions))}},lx=(n,e,t,r,s,i)=>{let o=t.mapping.get(n);if(o===void 0){if(n instanceof Fe)return Mc(n,e,t,r,s,i);throw Xe()}return o},Mc=(n,e,t,r,s,i)=>{let o=[],l=a=>{if(a instanceof Fe){let c=lx(a,e,t,r,s,i);c!==null&&o.push(c)}else{let c=a._item.right?.content?.type;c instanceof kn&&!c._item.deleted&&c._item.id.client===c.doc.clientID&&(a.applyDelta([{retain:a.length},...c.toDelta()]),c.doc.transact(d=>{c._item.delete(d)}));let u=LI(a,e,t,r,s,i);u!==null&&u.forEach(d=>{d!==null&&o.push(d)})}};r===void 0||s===void 0?n.toArray().forEach(l):qf(n,new Ms(s.ds,r.sv)).forEach(l);try{let a=n.getAttributes(r);r!==void 0&&(Rc(n._item,r)?Rc(n._item,s)||(a.ychange=i?i("added",n._item.id):{type:"added"}):a.ychange=i?i("removed",n._item.id):{type:"removed"});let c=e.node(n.nodeName,a,o);return t.mapping.set(n,c),c}catch{return n.doc.transact(c=>{n._item.delete(c)},ee),t.mapping.delete(n),null}},LI=(n,e,t,r,s,i)=>{let o=[],l=n.toDelta(r,s,i);try{for(let a=0;a{n._item.delete(c)},ee),null}return o},_I=(n,e)=>{let t=new ut,r=n.map(s=>({insert:s.text,attributes:ux(s.marks,e)}));return t.applyDelta(r),e.mapping.set(t,n),t},BI=(n,e)=>{let t=new Fe(n.type.name);for(let r in n.attrs){let s=n.attrs[r];s!==null&&r!=="ychange"&&t.setAttribute(r,s)}return t.insert(0,Dc(n).map(r=>tp(r,e))),e.mapping.set(t,n),t},tp=(n,e)=>n instanceof Array?_I(n,e):BI(n,e),sx=n=>typeof n=="object"&&n!==null,sp=(n,e)=>{let t=Object.keys(n).filter(s=>n[s]!==null),r=t.length===Object.keys(e).filter(s=>e[s]!==null).length;for(let s=0;s{let e=n.content.content,t=[];for(let r=0;r{let t=n.toDelta();return t.length===e.length&&t.every((r,s)=>r.insert===e[s].text&&Zh(r.attributes||{}).length===e[s].marks.length&&Pn(r.attributes,(i,o)=>{let l=cx(o),a=e[s].marks;return a.find(u=>u.type.name===l)?sp(i,a.find(u=>u.type.name===l)?.attrs):!1}))},xo=(n,e)=>{if(n instanceof Fe&&!(e instanceof Array)&&rp(n,e)){let t=Dc(e);return n._length===t.length&&sp(n.getAttributes(),e.attrs)&&n.toArray().every((r,s)=>xo(r,t[s]))}return n instanceof ut&&e instanceof Array&&ax(n,e)},Nc=(n,e)=>n===e||n instanceof Array&&e instanceof Array&&n.length===e.length&&n.every((t,r)=>e[r]===t),ix=(n,e,t)=>{let r=n.toArray(),s=Dc(e),i=s.length,o=r.length,l=Tt(o,i),a=0,c=0,u=!1;for(;a{let e="",t=n._start,r={};for(;t!==null;)t.deleted||(t.countable&&t.content instanceof Mt?e+=t.content.str:t.content instanceof le&&(r[t.content.key]=null)),t=t.right;return{str:e,nAttrs:r}},$I=(n,e,t)=>{t.mapping.set(n,e);let{nAttrs:r,str:s}=zI(n),i=e.map(c=>({insert:c.text,attributes:Object.assign({},r,ux(c.marks,t))})),{insert:o,remove:l,index:a}=nx(s,i.map(c=>c.insert).join(""));n.delete(a,l),n.insert(a,o),n.applyDelta(i.map(c=>({retain:c.insert.length,attributes:c.attributes})))},UI=/(.*)(--[a-zA-Z0-9+/=]{8})$/,cx=n=>UI.exec(n)?.[1]??n,FI=(n,e)=>{let t=[];for(let r in n)t.push(e.mark(cx(r),n[r]));return t},ux=(n,e)=>{let t={};return n.forEach(r=>{if(r.type.name!=="ychange"){let s=Ge(e.isOMark,r.type,()=>!r.type.excludes(r.type));t[s?`${r.type.name}--${RI(r.toJSON())}`:r.type.name]=r.attrs}}),t},np=(n,e,t,r)=>{if(e instanceof Fe&&e.nodeName!==t.type.name)throw new Error("node name mismatch!");if(r.mapping.set(e,t),e instanceof Fe){let d=e.getAttributes(),h=t.attrs;for(let f in h)h[f]!==null?d[f]!==h[f]&&f!=="ychange"&&e.setAttribute(f,h[f]):e.removeAttribute(f);for(let f in d)h[f]===void 0&&e.removeAttribute(f)}let s=Dc(t),i=s.length,o=e.toArray(),l=o.length,a=Tt(i,l),c=0,u=0;for(;c{for(;l-c-u>0&&i-c-u>0;){let h=o[c],f=s[c],p=o[l-u-1],m=s[i-u-1];if(h instanceof ut&&f instanceof Array)ax(h,f)||$I(h,f,r),c+=1;else{let g=h instanceof Fe&&rp(h,f),y=p instanceof Fe&&rp(p,m);if(g&&y){let w=ix(h,f,r),b=ix(p,m,r);w.foundMappedChild&&!b.foundMappedChild?y=!1:!w.foundMappedChild&&b.foundMappedChild||w.equalityFactor0&&(e.slice(c,c+d).forEach(h=>r.mapping.delete(h)),e.delete(c,d)),c+u!(e instanceof Array)&&n.nodeName===e.type.name;var Ic=(n,e,t)=>{if(n===0)return xc(e,0,-1);let r=e._first===null?null:e._first.content.type;for(;r!==null&&e!==r;){if(r instanceof ut){if(r._length>=n)return xc(r,n,-1);if(n-=r._length,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{do r=r._item===null?null:r._item.parent,n--;while(r!==e&&r!==null&&r._item!==null&&r._item.next===null);r!==null&&r!==e&&(r=r._item===null?null:r._item.next.content.type)}}else{let s=(t.get(r)||{nodeSize:0}).nodeSize;if(r._first!==null&&n1)return new Cr(r._item===null?null:r._item.id,r._item===null?Os(r):null,null);if(n-=s,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{if(n===0)return r=r._item===null?r:r._item.parent,new Cr(r._item===null?null:r._item.id,r._item===null?Os(r):null,null);do r=r._item.parent,n--;while(r!==e&&r._item.next===null);r!==e&&(r=r._item.next.content.type)}}}if(r===null)throw Ee();if(n===0&&r.constructor!==ut&&r!==e)return VI(r._item.parent,r._item)}return xc(e,e._length,-1)},VI=(n,e)=>{let t=null,r=null;return n._item===null?r=Os(n):t=z(n._item.id.client,n._item.id.clock),new Cr(t,r,e.id)},Mr=(n,e,t,r)=>{let s=Rb(t,n);if(s===null||s.type!==e&&!Es(e,s.type._item))return null;let i=s.type,o=0;if(i.constructor===ut)o=s.index;else if(i._item===null||!i._item.deleted){let l=i._first,a=0;for(;a{let e=Kt.getState(n).undoManager;if(e!=null)return e.undo(),!0},hx=n=>{let e=Kt.getState(n).undoManager;if(e!=null)return e.redo(),!0},HI=new Set(["paragraph"]),WI=(n,e)=>!(n instanceof q)||!(n.content instanceof vt)||!(n.content.type instanceof kn||n.content.type instanceof Fe&&e.has(n.content.type.nodeName))||n.content.type._length===0,fx=({protectedNodes:n=HI,trackedOrigins:e=[],undoManager:t=null}={})=>new O({key:Kt,state:{init:(r,s)=>{let i=ee.getState(s),o=t;if(!o){let l=i.doc,a=new Set(l?l._observers.get("destroy"):[]);o=new Rs(i.type,{trackedOrigins:new Set([ee].concat(e)),deleteFilter:u=>WI(u,n),captureTransaction:u=>u.meta.get("addToHistory")!==!1});let c=l?l._observers.get("destroy"):new Set;o._yTiptapDocDestroyListeners=Array.from(c||[]).filter(u=>!a.has(u))}return{undoManager:o,prevSel:null,hasUndoOps:o.undoStack.length>0,hasRedoOps:o.redoStack.length>0}},apply:(r,s,i,o)=>{let l=ee.getState(o).binding,a=s.undoManager,c=a.undoStack.length>0,u=a.redoStack.length>0;return l?{undoManager:a,prevSel:Zf(l,i),hasUndoOps:c,hasRedoOps:u}:c!==s.hasUndoOps||u!==s.hasRedoOps?Object.assign({},s,{hasUndoOps:a.undoStack.length>0,hasRedoOps:a.redoStack.length>0}):s}},view:r=>{let s=ee.getState(r.state),i=Kt.getState(r.state).undoManager;return i.on("stack-item-added",({stackItem:o})=>{let l=s.binding;l&&o.meta.set(l,Kt.getState(r.state).prevSel)}),i.on("stack-item-popped",({stackItem:o})=>{let l=s.binding;l&&(l.beforeTransactionSelection=o.meta.get(l)||l.beforeTransactionSelection)}),{destroy:()=>{i.destroy();let o=i._yTiptapDocDestroyListeners;o&&i.doc&&(o.forEach(l=>i.doc.off("destroy",l)),i._yTiptapDocDestroyListeners=null)}}}});function px(n){return!!n.getMeta(ee)}function jI(n,e){let t=ee.getState(n);return Mr(t.doc,t.type,e,t.binding.mapping)||0}function mx(n,e){let t=ee.getState(n);return Ic(e,t.type,t.binding.mapping)}var Oc=class gx extends vl{constructor(e,t){super(e),this.yRelativePosition=t}static fromJSON(e){return new gx(e.position,e.yRelativePosition)}toJSON(){return{position:this.position,yRelativePosition:this.yRelativePosition}}};function qI(n,e){let t=mx(e,n);return new Oc(n,t)}function JI(n,e,t){let r=n instanceof Oc?n.yRelativePosition:null;if(px(e)&&r){let o=jI(t,r);return{position:new Oc(o,r),mapResult:null}}let s=_d(n,e),i=s.position.position;return{position:new Oc(i,r??mx(t,i)),mapResult:s.mapResult}}var KI=F.create({name:"collaboration",priority:1e3,addOptions(){return{document:null,field:"default",fragment:null,provider:null}},addStorage(){return{isDisabled:!1}},onCreate(){this.editor.extensionManager.extensions.find(n=>n.name==="undoRedo")&&console.warn('[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-undo-redo".')},onBeforeCreate(){this.editor.utils.getUpdatedPosition=(n,e)=>JI(n,e,this.editor.state),this.editor.utils.createMappablePosition=n=>qI(n,this.editor.state)},addCommands(){return{undo:()=>({tr:n,state:e,dispatch:t})=>(n.setMeta("preventDispatch",!0),Kt.getState(e).undoManager.undoStack.length===0?!1:t?dx(e):!0),redo:()=>({tr:n,state:e,dispatch:t})=>(n.setMeta("preventDispatch",!0),Kt.getState(e).undoManager.redoStack.length===0?!1:t?hx(e):!0)}},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Mod-y":()=>this.editor.commands.redo(),"Shift-Mod-z":()=>this.editor.commands.redo()}},addProseMirrorPlugins(){let n=this.options.fragment?this.options.fragment:this.options.document.getXmlFragment(this.options.field),e=fx(this.options.yUndoOptions),t=e.spec.view;e.spec.view=i=>{let{undoManager:o}=Kt.getState(i.state);o.restore&&(o.restore(),o.restore=()=>{});let l=t?t(i):void 0;return{destroy:()=>{let a=o.trackedOrigins.has(o),c=o._observers;o.restore=()=>{a&&o.trackedOrigins.add(o),o.doc.on("afterTransaction",o.afterTransactionHandler),o._observers=c},l?.destroy&&l.destroy()}}};let r={...this.options.ySyncOptions,onFirstRender:this.options.onFirstRender};return[ox(n,r),e,this.editor.options.enableContentCheck&&new O({key:new P("filterInvalidContent"),filterTransaction:i=>{if(!px(i))return!0;if(this.storage.isDisabled)return!1;if(!i.docChanged)return!0;try{return i.doc.check(),!0}catch(o){return this.storage.isDisabled=!0,this.editor.emit("contentError",{error:o,editor:this.editor,disableCollaboration:()=>{var l;(l=n.doc)==null||l.destroy()}}),!0}}})].filter(Boolean)}}),yx=KI;var wx=Uh;var kx=wa;var bx=ya;var op,lp;if(typeof WeakMap<"u"){let n=new WeakMap;op=e=>n.get(e),lp=(e,t)=>(n.set(e,t),t)}else{let n=[],t=0;op=r=>{for(let s=0;s(t==10&&(t=0),n[t++]=r,n[t++]=s)}var se=class{constructor(n,e,t,r){this.width=n,this.height=e,this.map=t,this.problems=r}findCell(n){for(let e=0;e=t){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:y-b});break}let v=s+b*e;for(let C=0;Cr&&(i+=c.attrs.colspan)}}for(let o=0;o1&&(t=!0)}e==-1?e=i:e!=i&&(e=Math.max(e,i))}return e}function XI(n,e,t){n.problems||(n.problems=[]);let r={};for(let s=0;s0;e--)if(n.node(e).type.spec.tableRole=="row")return n.node(0).resolve(n.before(e+1));return null}function ZI(n){for(let e=n.depth;e>0;e--){let t=n.node(e).type.spec.tableRole;if(t==="cell"||t==="header_cell")return n.node(e)}return null}function Rt(n){let e=n.selection.$head;for(let t=e.depth;t>0;t--)if(e.node(t).type.spec.tableRole=="row")return!0;return!1}function $c(n){let e=n.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;let t=Rr(e.$head)||eD(e.$head);if(t)return t;throw new RangeError(`No cell found around position ${e.head}`)}function eD(n){for(let e=n.nodeAfter,t=n.pos;e;e=e.firstChild,t++){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return n.doc.resolve(t)}for(let e=n.nodeBefore,t=n.pos;e;e=e.lastChild,t--){let r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return n.doc.resolve(t-e.nodeSize)}}function ap(n){return n.parent.type.spec.tableRole=="row"&&!!n.nodeAfter}function tD(n){return n.node(0).resolve(n.pos+n.nodeAfter.nodeSize)}function dp(n,e){return n.depth==e.depth&&n.pos>=e.start(-1)&&n.pos<=e.end(-1)}function Nx(n,e,t){let r=n.node(-1),s=se.get(r),i=n.start(-1),o=s.nextCell(n.pos-i,e,t);return o==null?null:n.node(0).resolve(i+o)}function Nr(n,e,t=1){let r={...n,colspan:n.colspan-t};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,t),r.colwidth.some(s=>s>0)||(r.colwidth=null)),r}function Ix(n,e,t=1){let r={...n,colspan:n.colspan+t};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let s=0;su!=t.pos-i);a.unshift(t.pos-i);let c=a.map(u=>{let d=r.nodeAt(u);if(!d)throw new RangeError(`No cell with offset ${u} found`);let h=i+u+1;return new Wr(l.resolve(h),l.resolve(h+d.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=t}map(e,t){let r=e.resolve(t.map(this.$anchorCell.pos)),s=e.resolve(t.map(this.$headCell.pos));if(ap(r)&&ap(s)&&dp(r,s)){let i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?bn.rowSelection(r,s):i&&this.isColSelection()?bn.colSelection(r,s):new bn(r,s)}return A.between(r,s)}content(){let e=this.$anchorCell.node(-1),t=se.get(e),r=this.$anchorCell.start(-1),s=t.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},o=[];for(let a=s.top;a0||g>0){let y=p.attrs;if(m>0&&(y=Nr(y,0,m)),g>0&&(y=Nr(y,y.colspan-g,g)),f.lefts.bottom){let y={...p.attrs,rowspan:Math.min(f.bottom,s.bottom)-Math.max(f.top,s.top)};f.top0)return!1;let r=e+this.$anchorCell.nodeAfter.attrs.rowspan,s=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,s)==this.$headCell.node(-1).childCount}static colSelection(e,t=e){let r=e.node(-1),s=se.get(r),i=e.start(-1),o=s.findCell(e.pos-i),l=s.findCell(t.pos-i),a=e.node(0);return o.top<=l.top?(o.top>0&&(e=a.resolve(i+s.map[o.left])),l.bottom0&&(t=a.resolve(i+s.map[l.left])),o.bottom0)return!1;let o=s+this.$anchorCell.nodeAfter.attrs.colspan,l=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(o,l)==t.width}eq(e){return e instanceof bn&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,t=e){let r=e.node(-1),s=se.get(r),i=e.start(-1),o=s.findCell(e.pos-i),l=s.findCell(t.pos-i),a=e.node(0);return o.left<=l.left?(o.left>0&&(e=a.resolve(i+s.map[o.top*s.width])),l.right0&&(t=a.resolve(i+s.map[l.top*s.width])),o.right{e.push(de.node(r,r+t.nodeSize,{class:"selectedCell"}))}),X.create(n.doc,e)}function iD({$from:n,$to:e}){if(n.pos==e.pos||n.pos=0&&!(n.after(s+1)=0&&!(e.before(i+1)>e.start(i));i--,r--);return t==r&&/row|table/.test(n.node(s).type.spec.tableRole)}function oD({$from:n,$to:e}){let t,r;for(let s=n.depth;s>0;s--){let i=n.node(s);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){t=i;break}}for(let s=e.depth;s>0;s--){let i=e.node(s);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}return t!==r&&e.parentOffset===0}function lD(n,e,t){let r=(e||n).selection,s=(e||n).doc,i,o;if(r instanceof M&&(o=r.node.type.spec.tableRole)){if(o=="cell"||o=="header_cell")i=K.create(s,r.from);else if(o=="row"){let l=s.resolve(r.from+1);i=K.rowSelection(l,l)}else if(!t){let l=se.get(r.node),a=r.from+1,c=a+l.map[l.width*l.height-1];i=K.create(s,a+1,c)}}else r instanceof A&&iD(r)?i=A.create(s,r.from):r instanceof A&&oD(r)&&(i=A.create(s,r.$from.start(),r.$from.end()));return i&&(e||(e=n.tr)).setSelection(i),e}var aD=new P("fix-tables");function Ox(n,e,t,r){let s=n.childCount,i=e.childCount;e:for(let o=0,l=0;o{s.type.spec.tableRole=="table"&&(t=cD(n,s,i,t))};return e?e.doc!=n.doc&&Ox(e.doc,n.doc,0,r):n.doc.descendants(r),t}function cD(n,e,t,r){let s=se.get(e);if(!s.problems)return r;r||(r=n.tr);let i=[];for(let a=0;a0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);let p=[];for(let g=0;g0?-1:0;nD(e,r,s+i)&&(i=s==0||s==e.width?null:0);for(let o=0;o0&&s0&&e.map[l-1]==a||s0?-1:0;dD(e,r,s+l)&&(l=s==0||s==e.height?null:0);for(let c=0,u=e.width*s;c0&&s0&&d==e.map[u-e.width]){let h=t.nodeAt(d).attrs;n.setNodeMarkup(n.mapping.slice(l).map(d+r),null,{...h,rowspan:h.rowspan-1}),c+=h.colspan-1}else if(s0&&t[i]==t[i-1]||r.right0&&t[s]==t[s-n]||r.bottom0){let u=a+1+c.content.size,d=xx(c)?a+1:u;i.replaceWith(d+r.tableStart,u+r.tableStart,l)}i.setSelection(new K(i.doc.resolve(a+r.tableStart))),e(i)}return!0}function pp(n,e){let t=Ve(n.schema);return pD(({node:r})=>t[r.type.spec.tableRole])(n,e)}function pD(n){return(e,t)=>{let r=e.selection,s,i;if(r instanceof K){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;s=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var o;if(s=ZI(r.$from),!s)return!1;i=(o=Rr(r.$from))===null||o===void 0?void 0:o.pos}if(s==null||i==null||s.attrs.colspan==1&&s.attrs.rowspan==1)return!1;if(t){let l=s.attrs,a=[],c=l.colwidth;l.rowspan>1&&(l={...l,rowspan:1}),l.colspan>1&&(l={...l,colspan:1});let u=Yt(e),d=e.tr;for(let f=0;f{o.attrs[n]!==e&&i.setNodeMarkup(l,null,{...o.attrs,[n]:e})}):i.setNodeMarkup(s.pos,null,{...s.nodeAfter.attrs,[n]:e}),r(i)}return!0}}function mD(n){return function(e,t){if(!Rt(e))return!1;if(t){let r=Ve(e.schema),s=Yt(e),i=e.tr,o=s.map.cellsInRect(n=="column"?{left:s.left,top:0,right:s.right,bottom:s.map.height}:n=="row"?{left:0,top:s.top,right:s.map.width,bottom:s.bottom}:s),l=o.map(a=>s.table.nodeAt(a));for(let a=0;a{let f=h+i.tableStart,p=o.doc.nodeAt(f);p&&o.setNodeMarkup(f,d,p.attrs)}),r(o)}return!0}}var Z$=_s("row",{useDeprecatedLogic:!0}),eU=_s("column",{useDeprecatedLogic:!0}),Hx=_s("cell",{useDeprecatedLogic:!0});function gD(n,e){if(e<0){let t=n.nodeBefore;if(t)return n.pos-t.nodeSize;for(let r=n.index(-1)-1,s=n.before();r>=0;r--){let i=n.node(-1).child(r),o=i.lastChild;if(o)return s-1-o.nodeSize;s-=i.nodeSize}}else{if(n.index()0;r--)if(t.node(r).type.spec.tableRole=="table")return e&&e(n.tr.delete(t.before(r),t.after(r)).scrollIntoView()),!0;return!1}function Pc(n,e){let t=n.selection;if(!(t instanceof K))return!1;if(e){let r=n.tr,s=Ve(n.schema).cell.createAndFill().content;t.forEachCell((i,o)=>{i.content.eq(s)||r.replace(r.mapping.map(o+1),r.mapping.map(o+i.nodeSize-1),new S(s,0,0))}),r.docChanged&&e(r)}return!0}function yD(n){if(n.size===0)return null;let{content:e,openStart:t,openEnd:r}=n;for(;e.childCount==1&&(t>0&&r>0||e.child(0).type.spec.tableRole=="table");)t--,r--,e=e.child(0).content;let s=e.child(0),i=s.type.spec.tableRole,o=s.type.schema,l=[];if(i=="row")for(let a=0;a=0;o--){let{rowspan:l,colspan:a}=i.child(o).attrs;for(let c=s;c=e.length&&e.push(k.empty),t[s]r&&(h=h.type.createChecked(Nr(h.attrs,h.attrs.colspan,u+h.attrs.colspan-r),h.content)),c.push(h),u+=h.attrs.colspan;for(let f=1;fs&&(d=d.type.create({...d.attrs,rowspan:Math.max(1,s-d.attrs.rowspan)},d.content)),a.push(d)}i.push(k.from(a))}t=i,e=s}return{width:n,height:e,rows:t}}function bD(n,e,t,r,s,i,o){let l=n.doc.type.schema,a=Ve(l),c,u;if(s>e.width)for(let d=0,h=0;de.height){let d=[];for(let p=0,m=(e.height-1)*e.width;p=e.width?!1:t.nodeAt(e.map[m+p]).type==a.header_cell;d.push(g?u||(u=a.header_cell.createAndFill()):c||(c=a.cell.createAndFill()))}let h=a.row.create(null,k.from(d)),f=[];for(let p=e.height;p{if(!s)return!1;let i=t.selection;if(i instanceof K)return Bc(t,r,N.near(i.$headCell,e));if(n!="horiz"&&!i.empty)return!1;let o=jx(s,n,e);if(o==null)return!1;if(n=="horiz")return Bc(t,r,N.near(t.doc.resolve(i.head+e),e));{let l=t.doc.resolve(o),a=Nx(l,n,e),c;return a?c=N.near(a,1):e<0?c=N.near(t.doc.resolve(l.before(-1)),-1):c=N.near(t.doc.resolve(l.after(-1)),1),Bc(t,r,c)}}}function _c(n,e){return(t,r,s)=>{if(!s)return!1;let i=t.selection,o;if(i instanceof K)o=i;else{let a=jx(s,n,e);if(a==null)return!1;o=new K(t.doc.resolve(a))}let l=Nx(o.$headCell,n,e);return l?Bc(t,r,new K(o.$anchorCell,l)):!1}}function SD(n,e){let t=n.state.doc,r=Rr(t.resolve(e));return r?(n.dispatch(n.state.tr.setSelection(new K(r))),!0):!1}function vD(n,e,t){if(!Rt(n.state))return!1;let r=yD(t),s=n.state.selection;if(s instanceof K){r||(r={width:1,height:1,rows:[k.from(cp(Ve(n.state.schema).cell,t))]});let i=s.$anchorCell.node(-1),o=s.$anchorCell.start(-1),l=se.get(i).rectBetween(s.$anchorCell.pos-o,s.$headCell.pos-o);return r=kD(r,l.right-l.left,l.bottom-l.top),Tx(n.state,n.dispatch,o,l,r),!0}else if(r){let i=$c(n.state),o=i.start(-1);return Tx(n.state,n.dispatch,o,se.get(i.node(-1)).findCell(i.pos-o),r),!0}else return!1}function CD(n,e){var t;if(e.button!=0||e.ctrlKey||e.metaKey)return;let r=Ax(n,e.target),s;if(e.shiftKey&&n.state.selection instanceof K)i(n.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(s=Rr(n.state.selection.$anchor))!=null&&((t=ip(n,e))===null||t===void 0?void 0:t.pos)!=s.pos)i(s,e),e.preventDefault();else if(!r)return;function i(a,c){let u=ip(n,c),d=Fn.getState(n.state)==null;if(!u||!dp(a,u))if(d)u=a;else return;let h=new K(a,u);if(d||!n.state.selection.eq(h)){let f=n.state.tr.setSelection(h);d&&f.setMeta(Fn,a.pos),n.dispatch(f)}}function o(){n.root.removeEventListener("mouseup",o),n.root.removeEventListener("dragstart",o),n.root.removeEventListener("mousemove",l),Fn.getState(n.state)!=null&&n.dispatch(n.state.tr.setMeta(Fn,-1))}function l(a){let c=a,u=Fn.getState(n.state),d;if(u!=null)d=n.state.doc.resolve(u);else if(Ax(n,c.target)!=r&&(d=ip(n,e),!d))return o();d&&i(d,c)}n.root.addEventListener("mouseup",o),n.root.addEventListener("dragstart",o),n.root.addEventListener("mousemove",l)}function jx(n,e,t){if(!(n.state.selection instanceof A))return null;let{$head:r}=n.state.selection;for(let s=r.depth-1;s>=0;s--){let i=r.node(s);if((t<0?r.index(s):r.indexAfter(s))!=(t<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){let o=r.before(s),l=e=="vert"?t>0?"down":"up":t>0?"right":"left";return n.endOfTextblock(l)?o:null}}return null}function Ax(n,e){for(;e&&e!=n.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function ip(n,e){let t=n.posAtCoords({left:e.clientX,top:e.clientY});if(!t)return null;let{inside:r,pos:s}=t;return r>=0&&Rr(n.state.doc.resolve(r))||Rr(n.state.doc.resolve(s))}var TD=class{constructor(n,e){this.node=n,this.defaultCellMinWidth=e,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${e}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),up(n,this.colgroup,this.table,e),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(n){return n.type!=this.node.type?!1:(this.node=n,up(n,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(n){return n.type=="attributes"&&(n.target==this.table||this.colgroup.contains(n.target))}};function up(n,e,t,r,s,i){let o=0,l=!0,a=e.firstChild,c=n.firstChild;if(c){for(let d=0,h=0;dnew r(d,t,h)),new AD(-1,!1)},apply(o,l){return l.apply(o)}},props:{attributes:o=>{let l=dt.getState(o);return l&&l.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(o,l)=>{ED(o,l,n,s)},mouseleave:o=>{MD(o)},mousedown:(o,l)=>{RD(o,l,e,t)}},decorations:o=>{let l=dt.getState(o);if(l&&l.activeHandle>-1)return PD(o,l.activeHandle)},nodeViews:{}}});return i}var AD=class zc{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(e){let t=this,r=e.getMeta(dt);if(r&&r.setHandle!=null)return new zc(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new zc(t.activeHandle,r.setDragging);if(t.activeHandle>-1&&e.docChanged){let s=e.mapping.map(t.activeHandle,-1);return ap(e.doc.resolve(s))||(s=-1),new zc(s,t.dragging)}return t}};function ED(n,e,t,r){if(!n.editable)return;let s=dt.getState(n.state);if(s&&!s.dragging){let i=ID(e.target),o=-1;if(i){let{left:l,right:a}=i.getBoundingClientRect();e.clientX-l<=t?o=Ex(n,e,"left",t):a-e.clientX<=t&&(o=Ex(n,e,"right",t))}if(o!=s.activeHandle){if(!r&&o!==-1){let l=n.state.doc.resolve(o),a=l.node(-1),c=se.get(a),u=l.start(-1);if(c.colCount(l.pos-u)+l.nodeAfter.attrs.colspan-1==c.width-1)return}Jx(n,o)}}}function MD(n){if(!n.editable)return;let e=dt.getState(n.state);e&&e.activeHandle>-1&&!e.dragging&&Jx(n,-1)}function RD(n,e,t,r){var s;if(!n.editable)return!1;let i=(s=n.dom.ownerDocument.defaultView)!==null&&s!==void 0?s:window,o=dt.getState(n.state);if(!o||o.activeHandle==-1||o.dragging)return!1;let l=n.state.doc.nodeAt(o.activeHandle),a=ND(n,o.activeHandle,l.attrs);n.dispatch(n.state.tr.setMeta(dt,{setDragging:{startX:e.clientX,startWidth:a}}));function c(d){i.removeEventListener("mouseup",c),i.removeEventListener("mousemove",u);let h=dt.getState(n.state);h?.dragging&&(DD(n,h.activeHandle,Mx(h.dragging,d,t)),n.dispatch(n.state.tr.setMeta(dt,{setDragging:null})))}function u(d){if(!d.which)return c(d);let h=dt.getState(n.state);if(h&&h.dragging){let f=Mx(h.dragging,d,t);Rx(n,h.activeHandle,f,r)}}return Rx(n,o.activeHandle,a,r),i.addEventListener("mouseup",c),i.addEventListener("mousemove",u),e.preventDefault(),!0}function ND(n,e,{colspan:t,colwidth:r}){let s=r&&r[r.length-1];if(s)return s;let i=n.domAtPos(e),o=i.node.childNodes[i.offset].offsetWidth,l=t;if(r)for(let a=0;aLD(n),renderHTML:n=>n.align?{style:`text-align: ${n.align}`}:{}}}var Vc=V.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:n=>{var e,t;let r=n.getAttribute("colwidth"),s=r?r.split(",").map(i=>parseInt(i,10)):null;if(!s){let i=(e=n.closest("table"))==null?void 0:e.querySelectorAll("colgroup > col"),o=Array.from(((t=n.parentElement)==null?void 0:t.children)||[]).indexOf(n);if(o&&o>-1&&i&&i[o]){let l=i[o].getAttribute("width");return l?[parseInt(l,10)]:null}}return s}},align:Xx()}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:n}){return["td",B(this.options.HTMLAttributes,n),0]}}),Hc=V.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:n=>{let e=n.getAttribute("colwidth");return e?e.split(",").map(r=>parseInt(r,10)):null}},align:Xx()}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:n}){return["th",B(this.options.HTMLAttributes,n),0]}}),Wc=V.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:n}){return["tr",B(this.options.HTMLAttributes,n),0]}});function gp(n,e){return e?["width",`${Math.max(e,n)}px`]:["min-width",`${n}px`]}function Yx(n,e,t,r,s,i){var o;let l=0,a=!0,c=e.firstChild,u=n.firstChild;if(u!==null)for(let h=0,f=0;h{let r=n.nodes[t];r.spec.tableRole&&(e[r.spec.tableRole]=r)}),n.cached.tableNodeTypes=e,e}function UD(n,e,t,r,s){let i=$D(n),o=[],l=[];for(let c=0;c{let{selection:e}=n.state;if(!FD(e))return!1;let t=0,r=Id(e.ranges[0].$from,i=>i.type.name==="table");return r?.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(t+=1)}),t===e.ranges.length?(n.commands.deleteTable(),!0):!1},VD="";function HD(n){return(n||"").replace(/\s+/g," ").trim()}function WD(n,e,t={}){var r;let s=(r=t.cellLineSeparator)!=null?r:VD;if(!n||!n.content||n.content.length===0)return"";let i=[];n.content.forEach(m=>{let g=[];m.content&&m.content.forEach(y=>{let w="";y.content&&Array.isArray(y.content)&&y.content.length>1?w=y.content.map(E=>e.renderChildren(E)).join(s):w=y.content?e.renderChildren(y.content):"";let b=HD(w),v=y.type==="tableHeader",C=_D(y.attrs);g.push({text:b,isHeader:v,align:C})}),i.push(g)});let o=i.reduce((m,g)=>Math.max(m,g.length),0);if(o===0)return"";let l=Array.from({length:o}).fill(0);i.forEach(m=>{var g;for(let y=0;yl[y]&&(l[y]=b),l[y]<3&&(l[y]=3)}});let a=(m,g)=>m+" ".repeat(Math.max(0,g-m.length)),c=i[0],u=c.some(m=>m.isHeader),d=Array.from({length:o}).fill(null);i.forEach(m=>{var g;for(let y=0;yu&&c[g]&&c[g].text||"");return h+=`| ${f.map((m,g)=>a(m,l[g])).join(" | ")} | `,h+=`| ${l.map((m,g)=>{let y=Math.max(3,m),w=d[g];return w==="left"?`:${"-".repeat(y)}`:w==="right"?`${"-".repeat(y)}:`:w==="center"?`:${"-".repeat(y)}:`:"-".repeat(y)}).join(" | ")} | `,(u?i.slice(1):i).forEach(m=>{h+=`| ${Array.from({length:o}).fill(0).map((g,y)=>a(m[y]&&m[y].text||"",l[y])).join(" | ")} | -`}),h}var FD=UD,mp=V.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:OD,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:n,HTMLAttributes:e}){let{colgroup:t,tableWidth:r,tableMinWidth:s}=PD(n,this.options.cellMinWidth),i=e.style;function o(){return i||(r?`width: ${r}`:`min-width: ${s}`)}let l=["table",B(this.options.HTMLAttributes,e,{style:o()}),t,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},l]:l},parseMarkdown:(n,e)=>{let t=[],r=Array.isArray(n.align)?n.align:[];if(n.header){let s=[];n.header.forEach((i,o)=>{var l;let a=Uc((l=r[o])!=null?l:i.align),c=a?{align:a}:{};s.push(e.createNode("tableHeader",c,[{type:"paragraph",content:e.parseInline(i.tokens)}]))}),t.push(e.createNode("tableRow",{},s))}return n.rows&&n.rows.forEach(s=>{let i=[];s.forEach((o,l)=>{var a;let c=Uc((a=r[l])!=null?a:o.align),u=c?{align:c}:{};i.push(e.createNode("tableCell",u,[{type:"paragraph",content:e.parseInline(o.tokens)}]))}),t.push(e.createNode("tableRow",{},i))}),e.createNode("table",void 0,t)},renderMarkdown:(n,e)=>FD(n,e),addCommands(){return{insertTable:({rows:n=3,cols:e=3,withHeaderRow:t=!0}={})=>({tr:r,dispatch:s,editor:i})=>{let o=_D(i.schema,n,e,t);if(s){let l=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(E.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:n,dispatch:e})=>Ix(n,e),addColumnAfter:()=>({state:n,dispatch:e})=>Dx(n,e),deleteColumn:()=>({state:n,dispatch:e})=>Ox(n,e),addRowBefore:()=>({state:n,dispatch:e})=>Lx(n,e),addRowAfter:()=>({state:n,dispatch:e})=>_x(n,e),deleteRow:()=>({state:n,dispatch:e})=>Bx(n,e),deleteTable:()=>({state:n,dispatch:e})=>Ux(n,e),mergeCells:()=>({state:n,dispatch:e})=>dp(n,e),splitCell:()=>({state:n,dispatch:e})=>hp(n,e),toggleHeaderColumn:()=>({state:n,dispatch:e})=>_s("column")(n,e),toggleHeaderRow:()=>({state:n,dispatch:e})=>_s("row")(n,e),toggleHeaderCell:()=>({state:n,dispatch:e})=>$x(n,e),mergeOrSplit:()=>({state:n,dispatch:e})=>dp(n,e)?!0:hp(n,e),setCellAttribute:(n,e)=>({state:t,dispatch:r})=>zx(n,e)(t,r),goToNextCell:()=>({state:n,dispatch:e})=>fp(1)(n,e),goToPreviousCell:()=>({state:n,dispatch:e})=>fp(-1)(n,e),fixTables:()=>({state:n,dispatch:e})=>(e&&up(n),!0),setCellSelection:n=>({tr:e,dispatch:t})=>{if(t){let r=K.create(e.doc,n.anchorCell,n.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:$c,"Mod-Backspace":$c,Delete:$c,"Mod-Delete":$c}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Vx({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],Wx({allowTableNodeSelection:this.options.allowTableNodeSelection})]},addNodeView(){let n=this.options.resizable&&this.editor.isEditable,e=this.options.View;return n||!e?null:({node:t,view:r,HTMLAttributes:s})=>{let i=B(this.options.HTMLAttributes,s);return new e(t,this.options.cellMinWidth,r,i)}},extendNodeSchema(n){let e={name:n.name,options:n.options,storage:n.storage};return{tableRole:W(N(n,"tableRole",e))}}}),dU=F.create({name:"tableKit",addExtensions(){let n=[];return this.options.table!==!1&&n.push(mp.configure(this.options.table)),this.options.tableCell!==!1&&n.push(Fc.configure(this.options.tableCell)),this.options.tableHeader!==!1&&n.push(Vc.configure(this.options.tableHeader)),this.options.tableRow!==!1&&n.push(Hc.configure(this.options.tableRow)),n}});var Kx=Hc;var Yx=Vc;var Gx=Fc;function kp(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Dr=kp();function sS(n){Dr=n}var Nr={exec:()=>null};function Bs(n){let e=[];return t=>{let r=Math.max(0,Math.min(3,t-1)),s=e[r];return s||(s=n(r),e[r]=s),s}}function H(n,e=""){let t=typeof n=="string"?n:n.source,r={replace:(s,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(He.caret,"$1"),t=t.replace(s,o),r},getRegex:()=>new RegExp(t,e)};return r}var VD=((n="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:n=>new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Bs(n=>new RegExp(`^ {0,${n}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Bs(n=>new RegExp(`^ {0,${n}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}(?:\`\`\`|~~~)`)),headingBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}#`)),htmlBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}>`))},HD=/^(?:[ \t]*(?:\n|$))+/,WD=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,jD=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,vo=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,qD=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bp=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,iS=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,oS=H(iS).replace(/bull/g,bp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),JD=H(iS).replace(/bull/g,bp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),xp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,KD=/^[^\n]+/,Sp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,YD=H(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Sp).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),GD=H(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,bp).getRegex(),Kc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",vp=/|$))/,XD=H("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",vp).replace("tag",Kc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),lS=H(xp).replace("hr",vo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Kc).getRegex(),QD=H(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",lS).getRegex(),Cp={blockquote:QD,code:WD,def:YD,fences:jD,heading:qD,hr:vo,html:XD,lheading:oS,list:GD,newline:HD,paragraph:lS,table:Nr,text:KD},Xx=H("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",vo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Kc).getRegex(),ZD={...Cp,lheading:JD,table:Xx,paragraph:H(xp).replace("hr",vo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Xx).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Kc).getRegex()},eO={...Cp,html:H(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",vp).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Nr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:H(xp).replace("hr",vo).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",oS).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},tO=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,nO=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,aS=/^( {2,}|\\)\n(?!\s*$)/,rO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",VD?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),uS=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,aO=H(uS,"u").replace(/punct/g,zs).getRegex(),cO=H(uS,"u").replace(/punct/g,cS).getRegex(),dS="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",uO=H(dS,"gu").replace(/notPunctSpace/g,Tp).replace(/punctSpace/g,Yc).replace(/punct/g,zs).getRegex(),dO=H(dS,"gu").replace(/notPunctSpace/g,oO).replace(/punctSpace/g,iO).replace(/punct/g,cS).getRegex(),hO=H("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Tp).replace(/punctSpace/g,Yc).replace(/punct/g,zs).getRegex(),fO=H(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,zs).getRegex(),pO="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",mO=H(pO,"gu").replace(/notPunctSpace/g,Tp).replace(/punctSpace/g,Yc).replace(/punct/g,zs).getRegex(),gO=H(/\\(punct)/,"gu").replace(/punct/g,zs).getRegex(),yO=H(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),wO=H(vp).replace("(?:-->|$)","-->").getRegex(),kO=H("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",wO).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),jc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,bO=H(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",jc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),hS=H(/^!?\[(label)\]\[(ref)\]/).replace("label",jc).replace("ref",Sp).getRegex(),fS=H(/^!?\[(ref)\](?:\[\])?/).replace("ref",Sp).getRegex(),xO=H("reflink|nolink(?!\\()","g").replace("reflink",hS).replace("nolink",fS).getRegex(),Qx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ap={_backpedal:Nr,anyPunctuation:gO,autolink:yO,blockSkip:lO,br:aS,code:nO,del:Nr,delLDelim:Nr,delRDelim:Nr,emStrongLDelim:aO,emStrongRDelimAst:uO,emStrongRDelimUnd:hO,escape:tO,link:bO,nolink:fS,punctuation:sO,reflink:hS,reflinkSearch:xO,tag:kO,text:rO,url:Nr},SO={...Ap,link:H(/^!?\[(label)\]\((.*?)\)/).replace("label",jc).getRegex(),reflink:H(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",jc).getRegex()},gp={...Ap,emStrongRDelimAst:dO,emStrongLDelim:cO,delLDelim:fO,delRDelim:mO,url:H(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Qx).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:H(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Zx=n=>CO[n];function Gt(n,e){if(e){if(He.escapeTest.test(n))return n.replace(He.escapeReplace,Zx)}else if(He.escapeTestNoEncode.test(n))return n.replace(He.escapeReplaceNoEncode,Zx);return n}function eS(n){try{n=encodeURI(n).replace(He.percentDecode,"%")}catch{return null}return n}function tS(n,e){let t=n.replace(He.findPipe,(i,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),r=t.split(He.splitPipe),s=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length{let t=[],r=Array.isArray(n.align)?n.align:[];if(n.header){let s=[];n.header.forEach((i,o)=>{var l;let a=Fc((l=r[o])!=null?l:i.align),c=a?{align:a}:{};s.push(e.createNode("tableHeader",c,[{type:"paragraph",content:e.parseInline(i.tokens)}]))}),t.push(e.createNode("tableRow",{},s))}return n.rows&&n.rows.forEach(s=>{let i=[];s.forEach((o,l)=>{var a;let c=Fc((a=r[l])!=null?a:o.align),u=c?{align:c}:{};i.push(e.createNode("tableCell",u,[{type:"paragraph",content:e.parseInline(o.tokens)}]))}),t.push(e.createNode("tableRow",{},i))}),e.createNode("table",void 0,t)},renderMarkdown:(n,e)=>jD(n,e),addCommands(){return{insertTable:({rows:n=3,cols:e=3,withHeaderRow:t=!0}={})=>({tr:r,dispatch:s,editor:i})=>{let o=UD(i.schema,n,e,t);if(s){let l=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(A.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:n,dispatch:e})=>Lx(n,e),addColumnAfter:()=>({state:n,dispatch:e})=>_x(n,e),deleteColumn:()=>({state:n,dispatch:e})=>Bx(n,e),addRowBefore:()=>({state:n,dispatch:e})=>$x(n,e),addRowAfter:()=>({state:n,dispatch:e})=>Ux(n,e),deleteRow:()=>({state:n,dispatch:e})=>Fx(n,e),deleteTable:()=>({state:n,dispatch:e})=>Wx(n,e),mergeCells:()=>({state:n,dispatch:e})=>fp(n,e),splitCell:()=>({state:n,dispatch:e})=>pp(n,e),toggleHeaderColumn:()=>({state:n,dispatch:e})=>_s("column")(n,e),toggleHeaderRow:()=>({state:n,dispatch:e})=>_s("row")(n,e),toggleHeaderCell:()=>({state:n,dispatch:e})=>Hx(n,e),mergeOrSplit:()=>({state:n,dispatch:e})=>fp(n,e)?!0:pp(n,e),setCellAttribute:(n,e)=>({state:t,dispatch:r})=>Vx(n,e)(t,r),goToNextCell:()=>({state:n,dispatch:e})=>mp(1)(n,e),goToPreviousCell:()=>({state:n,dispatch:e})=>mp(-1)(n,e),fixTables:()=>({state:n,dispatch:e})=>(e&&hp(n),!0),setCellSelection:n=>({tr:e,dispatch:t})=>{if(t){let r=K.create(e.doc,n.anchorCell,n.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Uc,"Mod-Backspace":Uc,Delete:Uc,"Mod-Delete":Uc}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[qx({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],Kx({allowTableNodeSelection:this.options.allowTableNodeSelection})]},addNodeView(){let n=this.options.resizable&&this.editor.isEditable,e=this.options.View;return n||!e?null:({node:t,view:r,HTMLAttributes:s})=>{let i=B(this.options.HTMLAttributes,s);return new e(t,this.options.cellMinWidth,r,i)}},extendNodeSchema(n){let e={name:n.name,options:n.options,storage:n.storage};return{tableRole:W(I(n,"tableRole",e))}}}),mU=F.create({name:"tableKit",addExtensions(){let n=[];return this.options.table!==!1&&n.push(yp.configure(this.options.table)),this.options.tableCell!==!1&&n.push(Vc.configure(this.options.tableCell)),this.options.tableHeader!==!1&&n.push(Hc.configure(this.options.tableHeader)),this.options.tableRow!==!1&&n.push(Wc.configure(this.options.tableRow)),n}});var Qx=Wc;var Zx=Hc;var eS=Vc;function xp(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Or=xp();function aS(n){Or=n}var Ir={exec:()=>null};function Bs(n){let e=[];return t=>{let r=Math.max(0,Math.min(3,t-1)),s=e[r];return s||(s=n(r),e[r]=s),s}}function H(n,e=""){let t=typeof n=="string"?n:n.source,r={replace:(s,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(He.caret,"$1"),t=t.replace(s,o),r},getRegex:()=>new RegExp(t,e)};return r}var qD=((n="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:n=>new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Bs(n=>new RegExp(`^ {0,${n}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Bs(n=>new RegExp(`^ {0,${n}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}(?:\`\`\`|~~~)`)),headingBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}#`)),htmlBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Bs(n=>new RegExp(`^ {0,${n}}>`))},JD=/^(?:[ \t]*(?:\n|$))+/,KD=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,YD=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Co=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,GD=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Sp=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,cS=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,uS=H(cS).replace(/bull/g,Sp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),XD=H(cS).replace(/bull/g,Sp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),vp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,QD=/^[^\n]+/,Cp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ZD=H(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Cp).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),eO=H(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Sp).getRegex(),Yc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Tp=/|$))/,tO=H("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Tp).replace("tag",Yc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),dS=H(vp).replace("hr",Co).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Yc).getRegex(),nO=H(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",dS).getRegex(),Ap={blockquote:nO,code:KD,def:ZD,fences:YD,heading:GD,hr:Co,html:tO,lheading:uS,list:eO,newline:JD,paragraph:dS,table:Ir,text:QD},tS=H("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Co).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Yc).getRegex(),rO={...Ap,lheading:XD,table:tS,paragraph:H(vp).replace("hr",Co).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",tS).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Yc).getRegex()},sO={...Ap,html:H(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Tp).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ir,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:H(vp).replace("hr",Co).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",uS).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},iO=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,oO=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,hS=/^( {2,}|\\)\n(?!\s*$)/,lO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",qD?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),pS=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,hO=H(pS,"u").replace(/punct/g,zs).getRegex(),fO=H(pS,"u").replace(/punct/g,fS).getRegex(),mS="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",pO=H(mS,"gu").replace(/notPunctSpace/g,Ep).replace(/punctSpace/g,Gc).replace(/punct/g,zs).getRegex(),mO=H(mS,"gu").replace(/notPunctSpace/g,uO).replace(/punctSpace/g,cO).replace(/punct/g,fS).getRegex(),gO=H("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ep).replace(/punctSpace/g,Gc).replace(/punct/g,zs).getRegex(),yO=H(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,zs).getRegex(),wO="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",kO=H(wO,"gu").replace(/notPunctSpace/g,Ep).replace(/punctSpace/g,Gc).replace(/punct/g,zs).getRegex(),bO=H(/\\(punct)/,"gu").replace(/punct/g,zs).getRegex(),xO=H(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),SO=H(Tp).replace("(?:-->|$)","-->").getRegex(),vO=H("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",SO).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),qc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,CO=H(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",qc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),gS=H(/^!?\[(label)\]\[(ref)\]/).replace("label",qc).replace("ref",Cp).getRegex(),yS=H(/^!?\[(ref)\](?:\[\])?/).replace("ref",Cp).getRegex(),TO=H("reflink|nolink(?!\\()","g").replace("reflink",gS).replace("nolink",yS).getRegex(),nS=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mp={_backpedal:Ir,anyPunctuation:bO,autolink:xO,blockSkip:dO,br:hS,code:oO,del:Ir,delLDelim:Ir,delRDelim:Ir,emStrongLDelim:hO,emStrongRDelimAst:pO,emStrongRDelimUnd:gO,escape:iO,link:CO,nolink:yS,punctuation:aO,reflink:gS,reflinkSearch:TO,tag:vO,text:lO,url:Ir},AO={...Mp,link:H(/^!?\[(label)\]\((.*?)\)/).replace("label",qc).getRegex(),reflink:H(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",qc).getRegex()},wp={...Mp,emStrongRDelimAst:mO,emStrongLDelim:fO,delLDelim:yO,delRDelim:kO,url:H(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",nS).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:H(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},rS=n=>MO[n];function Gt(n,e){if(e){if(He.escapeTest.test(n))return n.replace(He.escapeReplace,rS)}else if(He.escapeTestNoEncode.test(n))return n.replace(He.escapeReplaceNoEncode,rS);return n}function sS(n){try{n=encodeURI(n).replace(He.percentDecode,"%")}catch{return null}return n}function iS(n,e){let t=n.replace(He.findPipe,(i,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),r=t.split(He.splitPipe),s=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length=0&&He.blankLine.test(e[t]);)t--;return e.length-t<=2?n:e.slice(0,t+1).join(` -`)}function TO(n,e){if(n.indexOf(e[1])===-1)return-1;let t=0;for(let r=0;r0?-2:-1}function AO(n,e=0){let t=e,r="";for(let s of n)if(s===" "){let i=4-t%4;r+=" ".repeat(i),t+=i}else r+=s,t++;return r}function rS(n,e,t,r,s){let i=e.href,o=e.title||null,l=n[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:n[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function EO(n,e,t){let r=n.match(t.other.indentCodeCompensation);if(r===null)return e;let s=r[1];return e.split(` +`)}function RO(n,e){if(n.indexOf(e[1])===-1)return-1;let t=0;for(let r=0;r0?-2:-1}function NO(n,e=0){let t=e,r="";for(let s of n)if(s===" "){let i=4-t%4;r+=" ".repeat(i),t+=i}else r+=s,t++;return r}function lS(n,e,t,r,s){let i=e.href,o=e.title||null,l=n[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:n[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function IO(n,e,t){let r=n.match(t.other.indentCodeCompensation);if(r===null)return e;let s=r[1];return e.split(` `).map(i=>{let o=i.match(t.other.beginningSpace);if(o===null)return i;let[l]=o;return l.length>=s.length?i.slice(s.length):i}).join(` -`)}var qc=class{options;rules;lexer;constructor(n){this.options=n||Dr}space(n){let e=this.rules.block.newline.exec(n);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(n){let e=this.rules.block.code.exec(n);if(e){let t=this.options.pedantic?e[0]:nS(e[0]),r=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:r}}}fences(n){let e=this.rules.block.fences.exec(n);if(e){let t=e[0],r=EO(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(n){let e=this.rules.block.heading.exec(n);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let r=Vn(t,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(t=r.trim())}return{type:"heading",raw:Vn(e[0],` +`)}var Jc=class{options;rules;lexer;constructor(n){this.options=n||Or}space(n){let e=this.rules.block.newline.exec(n);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(n){let e=this.rules.block.code.exec(n);if(e){let t=this.options.pedantic?e[0]:oS(e[0]),r=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:r}}}fences(n){let e=this.rules.block.fences.exec(n);if(e){let t=e[0],r=IO(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(n){let e=this.rules.block.heading.exec(n);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let r=Vn(t,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(t=r.trim())}return{type:"heading",raw:Vn(e[0],` `),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(n){let e=this.rules.block.hr.exec(n);if(e)return{type:"hr",raw:Vn(e[0],` `)}}blockquote(n){let e=this.rules.block.blockquote.exec(n);if(e){let t=Vn(e[0],` `).split(` @@ -173,19 +173,19 @@ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo `),m=this.blockquote(p);i[i.length-1]=m,r=r.substring(0,r.length-f.raw.length)+m.raw,s=s.substring(0,s.length-f.text.length)+m.text;break}else if(h?.type==="list"){let f=h,p=f.raw+` `+t.join(` `),m=this.list(p);i[i.length-1]=m,r=r.substring(0,r.length-h.raw.length)+m.raw,s=s.substring(0,s.length-f.raw.length)+m.raw,t=p.substring(i.at(-1).raw.length).split(` -`);continue}}return{type:"blockquote",raw:r,tokens:i,text:s}}}list(n){let e=this.rules.block.list.exec(n);if(e){let t=e[1].trim(),r=t.length>1,s={type:"list",raw:"",ordered:r,start:r?+t.slice(0,-1):"",loose:!1,items:[]};t=r?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=r?t:"[*+-]");let i=this.rules.other.listItemRegex(t),o=!1;for(;n;){let a=!1,c="",u="";if(!(e=i.exec(n))||this.rules.block.hr.test(n))break;c=e[0],n=n.substring(c.length);let d=AO(e[2].split(` +`);continue}}return{type:"blockquote",raw:r,tokens:i,text:s}}}list(n){let e=this.rules.block.list.exec(n);if(e){let t=e[1].trim(),r=t.length>1,s={type:"list",raw:"",ordered:r,start:r?+t.slice(0,-1):"",loose:!1,items:[]};t=r?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=r?t:"[*+-]");let i=this.rules.other.listItemRegex(t),o=!1;for(;n;){let a=!1,c="",u="";if(!(e=i.exec(n))||this.rules.block.hr.test(n))break;c=e[0],n=n.substring(c.length);let d=NO(e[2].split(` `,1)[0],e[1].length),h=n.split(` `,1)[0],f=!d.trim(),p=0;if(this.options.pedantic?(p=2,u=d.trimStart()):f?p=e[1].length+1:(p=d.search(this.rules.other.nonSpaceChar),p=p>4?1:p,u=d.slice(p),p+=e[1].length),f&&this.rules.other.blankLine.test(h)&&(c+=h+` `,n=n.substring(h.length+1),a=!0),!a){let m=this.rules.other.nextBulletRegex(p),g=this.rules.other.hrRegex(p),y=this.rules.other.fencesBeginRegex(p),w=this.rules.other.headingBeginRegex(p),b=this.rules.other.htmlBeginRegex(p),v=this.rules.other.blockquoteBeginRegex(p);for(;n;){let C=n.split(` `,1)[0],R;if(h=C,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),R=h):R=h.replace(this.rules.other.tabCharGlobal," "),y.test(h)||w.test(h)||b.test(h)||v.test(h)||m.test(h)||g.test(h))break;if(R.search(this.rules.other.nonSpaceChar)>=p||!h.trim())u+=` `+R.slice(p);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||y.test(d)||w.test(d)||g.test(d))break;u+=` `+h}f=!h.trim(),c+=C+` -`,n=n.substring(C.length+1),d=R.slice(p)}}s.loose||(o?s.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),s.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),s.raw+=c}let l=s.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let a of s.items){this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]);let c=a.tokens[0];if(a.task&&(c?.type==="text"||c?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(a.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};a.checked=d.checked,s.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}else a.task&&(a.task=!1);if(!s.loose){let u=a.tokens.filter(h=>h.type==="space"),d=u.length>0&&u.some(h=>this.rules.other.anyLine.test(h.raw));s.loose=d}}if(s.loose)for(let a of s.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return s}}html(n){let e=this.rules.block.html.exec(n);if(e){let t=nS(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(n){let e=this.rules.block.def.exec(n);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:Vn(e[0],` -`),href:r,title:s}}}table(n){let e=this.rules.block.table.exec(n);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=tS(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`,n=n.substring(C.length+1),d=R.slice(p)}}s.loose||(o?s.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),s.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),s.raw+=c}let l=s.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let a of s.items){this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]);let c=a.tokens[0];if(a.task&&(c?.type==="text"||c?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(a.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};a.checked=d.checked,s.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}else a.task&&(a.task=!1);if(!s.loose){let u=a.tokens.filter(h=>h.type==="space"),d=u.length>0&&u.some(h=>this.rules.other.anyLine.test(h.raw));s.loose=d}}if(s.loose)for(let a of s.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return s}}html(n){let e=this.rules.block.html.exec(n);if(e){let t=oS(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(n){let e=this.rules.block.def.exec(n);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:Vn(e[0],` +`),href:r,title:s}}}table(n){let e=this.rules.block.table.exec(n);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=iS(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(` `):[],i={type:"table",raw:Vn(e[0],` -`),header:[],align:[],rows:[]};if(t.length===r.length){for(let o of r)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[a]})));return i}}lheading(n){let e=this.rules.block.lheading.exec(n);if(e){let t=e[1].trim();return{type:"heading",raw:Vn(e[0],` +`),header:[],align:[],rows:[]};if(t.length===r.length){for(let o of r)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[a]})));return i}}lheading(n){let e=this.rules.block.lheading.exec(n);if(e){let t=e[1].trim();return{type:"heading",raw:Vn(e[0],` `),depth:e[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(n){let e=this.rules.block.paragraph.exec(n);if(e){let t=e[1].charAt(e[1].length-1)===` -`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(n){let e=this.rules.block.text.exec(n);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(n){let e=this.rules.inline.escape.exec(n);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(n){let e=this.rules.inline.tag.exec(n);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(n){let e=this.rules.inline.link.exec(n);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let i=Vn(t.slice(0,-1),"\\");if((t.length-i.length)%2===0)return}else{let i=TO(e[2],"()");if(i===-2)return;if(i>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let r=e[2],s="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],s=i[3])}else s=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?r=r.slice(1):r=r.slice(1,-1)),rS(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(n,e){let t;if((t=this.rules.inline.reflink.exec(n))||(t=this.rules.inline.nolink.exec(n))){let r=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=e[r.toLowerCase()];if(!s){let i=t[0].charAt(0);return{type:"text",raw:i,text:i}}return rS(t,s,t[0],this.lexer,this.rules)}}emStrong(n,e,t=""){let r=this.rules.inline.emStrongLDelim.exec(n);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!t||this.rules.inline.punctuation.exec(t))){let s=[...r[0]].length-1,i,o,l=s,a=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*n.length+s);(r=c.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(o=[...i].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){a+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let u=[...r[0]][0].length,d=n.slice(0,s+r.index+u+o);if(Math.min(s,o)%2){let f=d.slice(1,-1);return{type:"em",raw:d,text:f,tokens:this.lexer.inlineTokens(f)}}let h=d.slice(2,-2);return{type:"strong",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(n){let e=this.rules.inline.code.exec(n);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(t),s=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return r&&s&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(n){let e=this.rules.inline.br.exec(n);if(e)return{type:"br",raw:e[0]}}del(n,e,t=""){let r=this.rules.inline.delLDelim.exec(n);if(r&&(!r[1]||!t||this.rules.inline.punctuation.exec(t))){let s=[...r[0]].length-1,i,o,l=s,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*n.length+s);(r=a.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(o=[...i].length,o!==s))continue;if(r[3]||r[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...r[0]][0].length,u=n.slice(0,s+r.index+c+o),d=u.slice(s,-s);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(n){let e=this.rules.inline.autolink.exec(n);if(e){let t,r;return e[2]==="@"?(t=e[1],r="mailto:"+t):(t=e[1],r=t),{type:"link",raw:e[0],text:t,href:r,tokens:[{type:"text",raw:t,text:t}]}}}url(n){let e;if(e=this.rules.inline.url.exec(n)){let t,r;if(e[2]==="@")t=e[0],r="mailto:"+t;else{let s;do s=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(s!==e[0]);t=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:t,href:r,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(n){let e=this.rules.inline.text.exec(n);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},Nt=class yp{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Dr,this.options.tokenizer=this.options.tokenizer||new qc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:He,block:Wc.normal,inline:xo.normal};this.options.pedantic?(t.block=Wc.pedantic,t.inline=xo.pedantic):this.options.gfm&&(t.block=Wc.gfm,this.options.breaks?t.inline=xo.breaks:t.inline=xo.gfm),this.tokenizer.rules=t}static get rules(){return{block:Wc,inline:xo}}static lex(e,t){return new yp(t).lex(e)}static lexInline(e,t){return new yp(t).inlineTokens(e)}lex(e){e=e.replace(He.carriageReturn,` +`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(n){let e=this.rules.block.text.exec(n);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(n){let e=this.rules.inline.escape.exec(n);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(n){let e=this.rules.inline.tag.exec(n);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(n){let e=this.rules.inline.link.exec(n);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let i=Vn(t.slice(0,-1),"\\");if((t.length-i.length)%2===0)return}else{let i=RO(e[2],"()");if(i===-2)return;if(i>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let r=e[2],s="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],s=i[3])}else s=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?r=r.slice(1):r=r.slice(1,-1)),lS(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(n,e){let t;if((t=this.rules.inline.reflink.exec(n))||(t=this.rules.inline.nolink.exec(n))){let r=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=e[r.toLowerCase()];if(!s){let i=t[0].charAt(0);return{type:"text",raw:i,text:i}}return lS(t,s,t[0],this.lexer,this.rules)}}emStrong(n,e,t=""){let r=this.rules.inline.emStrongLDelim.exec(n);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!t||this.rules.inline.punctuation.exec(t))){let s=[...r[0]].length-1,i,o,l=s,a=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*n.length+s);(r=c.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(o=[...i].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){a+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let u=[...r[0]][0].length,d=n.slice(0,s+r.index+u+o);if(Math.min(s,o)%2){let f=d.slice(1,-1);return{type:"em",raw:d,text:f,tokens:this.lexer.inlineTokens(f)}}let h=d.slice(2,-2);return{type:"strong",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(n){let e=this.rules.inline.code.exec(n);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(t),s=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return r&&s&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(n){let e=this.rules.inline.br.exec(n);if(e)return{type:"br",raw:e[0]}}del(n,e,t=""){let r=this.rules.inline.delLDelim.exec(n);if(r&&(!r[1]||!t||this.rules.inline.punctuation.exec(t))){let s=[...r[0]].length-1,i,o,l=s,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*n.length+s);(r=a.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(o=[...i].length,o!==s))continue;if(r[3]||r[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...r[0]][0].length,u=n.slice(0,s+r.index+c+o),d=u.slice(s,-s);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(n){let e=this.rules.inline.autolink.exec(n);if(e){let t,r;return e[2]==="@"?(t=e[1],r="mailto:"+t):(t=e[1],r=t),{type:"link",raw:e[0],text:t,href:r,tokens:[{type:"text",raw:t,text:t}]}}}url(n){let e;if(e=this.rules.inline.url.exec(n)){let t,r;if(e[2]==="@")t=e[0],r="mailto:"+t;else{let s;do s=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(s!==e[0]);t=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:t,href:r,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(n){let e=this.rules.inline.text.exec(n);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},Nt=class kp{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Or,this.options.tokenizer=this.options.tokenizer||new Jc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:He,block:jc.normal,inline:So.normal};this.options.pedantic?(t.block=jc.pedantic,t.inline=So.pedantic):this.options.gfm&&(t.block=jc.gfm,this.options.breaks?t.inline=So.breaks:t.inline=So.gfm),this.tokenizer.rules=t}static get rules(){return{block:jc,inline:So}}static lex(e,t){return new kp(t).lex(e)}static lexInline(e,t){return new kp(t).inlineTokens(e)}lex(e){e=e.replace(He.carriageReturn,` `),this.blockTokens(e,this.tokens);for(let t=0;t(i=l.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let l=t.at(-1);i.raw.length===1&&l!==void 0?l.raw+=` `:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(` `)?"":` @@ -199,7 +199,7 @@ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i),r=o.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(` `)?"":` `)+i.raw,l.text+=` -`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let r=e,s=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)i=s[2]?s[2].length:0,r=r.slice(0,s.index+i)+"["+"a".repeat(s[0].length-i-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,l="",a=1/0;for(;e;){if(e.length(c=d.call({lexer:this},e,t))?(e=e.substring(c.raw.length),t.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let d=t.at(-1);c.type==="text"&&d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):t.push(c);continue}if(c=this.tokenizer.emStrong(e,r,l)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.del(e,r,l)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),t.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),t.push(c);continue}let u=e;if(this.options.extensions?.startInline){let d=1/0,h=e.slice(1),f;this.options.extensions.startInline.forEach(p=>{f=p.call({lexer:this},h),typeof f=="number"&&f>=0&&(d=Math.min(d,f))}),d<1/0&&d>=0&&(u=e.substring(0,d+1))}if(c=this.tokenizer.inlineText(u)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(l=c.raw.slice(-1)),o=!0;let d=t.at(-1);d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):t.push(c);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},Jc=class{options;parser;constructor(n){this.options=n||Dr}space(n){return""}code({text:n,lang:e,escaped:t}){let r=(e||"").match(He.notSpaceStart)?.[0],s=n.replace(He.endingNewline,"")+` +`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let r=e,s=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)i=s[2]?s[2].length:0,r=r.slice(0,s.index+i)+"["+"a".repeat(s[0].length-i-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,l="",a=1/0;for(;e;){if(e.length(c=d.call({lexer:this},e,t))?(e=e.substring(c.raw.length),t.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let d=t.at(-1);c.type==="text"&&d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):t.push(c);continue}if(c=this.tokenizer.emStrong(e,r,l)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.del(e,r,l)){e=e.substring(c.raw.length),t.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),t.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),t.push(c);continue}let u=e;if(this.options.extensions?.startInline){let d=1/0,h=e.slice(1),f;this.options.extensions.startInline.forEach(p=>{f=p.call({lexer:this},h),typeof f=="number"&&f>=0&&(d=Math.min(d,f))}),d<1/0&&d>=0&&(u=e.substring(0,d+1))}if(c=this.tokenizer.inlineText(u)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(l=c.raw.slice(-1)),o=!0;let d=t.at(-1);d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):t.push(c);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},Kc=class{options;parser;constructor(n){this.options=n||Or}space(n){return""}code({text:n,lang:e,escaped:t}){let r=(e||"").match(He.notSpaceStart)?.[0],s=n.replace(He.endingNewline,"")+` `;return r?'
'+(t?s:Gt(s,!0))+`
`:"
"+(t?s:Gt(s,!0))+`
`}blockquote({tokens:n}){return`
@@ -217,23 +217,23 @@ ${this.parser.parse(n)}
`}tablerow({text:n}){return` ${n} `}tablecell(n){let e=this.parser.parseInline(n.tokens),t=n.header?"th":"td";return(n.align?`<${t} align="${n.align}">`:`<${t}>`)+e+` -`}strong({tokens:n}){return`${this.parser.parseInline(n)}`}em({tokens:n}){return`${this.parser.parseInline(n)}`}codespan({text:n}){return`${Gt(n,!0)}`}br(n){return"
"}del({tokens:n}){return`${this.parser.parseInline(n)}`}link({href:n,title:e,tokens:t}){let r=this.parser.parseInline(t),s=eS(n);if(s===null)return r;n=s;let i='
",i}image({href:n,title:e,text:t,tokens:r}){r&&(t=this.parser.parseInline(r,this.parser.textRenderer));let s=eS(n);if(s===null)return Gt(t);n=s;let i=`${Gt(t)}{let o=s[i].flat(1/0);t=t.concat(this.walkTokens(o,e))}):s.tokens&&(t=t.concat(this.walkTokens(s.tokens,e)))}}return t}use(...n){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(t=>{let r={...t};if(r.async=this.defaults.async||r.async||!1,t.extensions&&(t.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let i=e.renderers[s.name];i?e.renderers[s.name]=function(...o){let l=s.renderer.apply(this,o);return l===!1&&(l=i.apply(this,o)),l}:e.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[s.level];i?i.unshift(s.tokenizer):e[s.level]=[s.tokenizer],s.start&&(s.level==="block"?e.startBlock?e.startBlock.push(s.start):e.startBlock=[s.start]:s.level==="inline"&&(e.startInline?e.startInline.push(s.start):e.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(e.childTokens[s.name]=s.childTokens)}),r.extensions=e),t.renderer){let s=this.defaults.renderer||new Jc(this.defaults);for(let i in t.renderer){if(!(i in s))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,l=t.renderer[o],a=s[o];s[o]=(...c)=>{let u=l.apply(s,c);return u===!1&&(u=a.apply(s,c)),u||""}}r.renderer=s}if(t.tokenizer){let s=this.defaults.tokenizer||new qc(this.defaults);for(let i in t.tokenizer){if(!(i in s))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,l=t.tokenizer[o],a=s[o];s[o]=(...c)=>{let u=l.apply(s,c);return u===!1&&(u=a.apply(s,c)),u}}r.tokenizer=s}if(t.hooks){let s=this.defaults.hooks||new So;for(let i in t.hooks){if(!(i in s))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,l=t.hooks[o],a=s[o];So.passThroughHooks.has(i)?s[o]=c=>{if(this.defaults.async&&So.passThroughHooksRespectAsync.has(i))return(async()=>{let d=await l.call(s,c);return a.call(s,d)})();let u=l.call(s,c);return a.call(s,u)}:s[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await l.apply(s,c);return d===!1&&(d=await a.apply(s,c)),d})();let u=l.apply(s,c);return u===!1&&(u=a.apply(s,c)),u}}r.hooks=s}if(t.walkTokens){let s=this.defaults.walkTokens,i=t.walkTokens;r.walkTokens=function(o){let l=[];return l.push(i.call(this,o)),s&&(l=l.concat(s.call(this,o))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(n){return this.defaults={...this.defaults,...n},this}lexer(n,e){return Nt.lex(n,e??this.defaults)}parser(n,e){return It.parse(n,e??this.defaults)}parseMarkdown(n){return(e,t)=>{let r={...t},s={...this.defaults,...r},i=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=n),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(e):e,l=await(s.hooks?await s.hooks.provideLexer(n):n?Nt.lex:Nt.lexInline)(o,s),a=s.hooks?await s.hooks.processAllTokens(l):l;s.walkTokens&&await Promise.all(this.walkTokens(a,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser(n):n?It.parse:It.parseInline)(a,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(i);try{s.hooks&&(e=s.hooks.preprocess(e));let o=(s.hooks?s.hooks.provideLexer(n):n?Nt.lex:Nt.lexInline)(e,s);s.hooks&&(o=s.hooks.processAllTokens(o)),s.walkTokens&&this.walkTokens(o,s.walkTokens);let l=(s.hooks?s.hooks.provideParser(n):n?It.parse:It.parseInline)(o,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(o){return i(o)}}}onError(n,e){return t=>{if(t.message+=` -Please report this to https://github.com/markedjs/marked.`,n){let r="

An error occurred:

"+Gt(t.message+"",!0)+"
";return e?Promise.resolve(r):r}if(e)return Promise.reject(t);throw t}}},Ir=new MO;function J(n,e){return Ir.parse(n,e)}J.options=J.setOptions=function(n){return Ir.setOptions(n),J.defaults=Ir.defaults,sS(J.defaults),J};J.getDefaults=kp;J.defaults=Dr;J.use=function(...n){return Ir.use(...n),J.defaults=Ir.defaults,sS(J.defaults),J};J.walkTokens=function(n,e){return Ir.walkTokens(n,e)};J.parseInline=Ir.parseInline;J.Parser=It;J.parser=It.parse;J.Renderer=Jc;J.TextRenderer=Ep;J.Lexer=Nt;J.lexer=Nt.lex;J.Tokenizer=qc;J.Hooks=So;J.parse=J;var vU=J.options,CU=J.setOptions,TU=J.use,AU=J.walkTokens,EU=J.parseInline;var MU=It.parse,RU=Nt.lex;function RO(n){for(var e=1;e0&&n[e-1]===` -`;)e--;return n.substring(0,e)}function wS(n){return yS(gS(n))}var NO=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function Dp(n){return Op(n,NO)}var kS=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function bS(n){return Op(n,kS)}function IO(n){return SS(n,kS)}var xS=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function DO(n){return Op(n,xS)}function OO(n){return SS(n,xS)}function Op(n,e){return e.indexOf(n.nodeName)>=0}function SS(n,e){return n.getElementsByTagName&&e.some(function(t){return n.getElementsByTagName(t).length})}var PO=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function vS(n){return PO.reduce(function(e,t){return e.replace(t[0],t[1])},n)}var We={};We.paragraph={filter:"p",replacement:function(n){return` +`}strong({tokens:n}){return`${this.parser.parseInline(n)}`}em({tokens:n}){return`${this.parser.parseInline(n)}`}codespan({text:n}){return`${Gt(n,!0)}`}br(n){return"
"}del({tokens:n}){return`${this.parser.parseInline(n)}`}link({href:n,title:e,tokens:t}){let r=this.parser.parseInline(t),s=sS(n);if(s===null)return r;n=s;let i='
",i}image({href:n,title:e,text:t,tokens:r}){r&&(t=this.parser.parseInline(r,this.parser.textRenderer));let s=sS(n);if(s===null)return Gt(t);n=s;let i=`${Gt(t)}{let o=s[i].flat(1/0);t=t.concat(this.walkTokens(o,e))}):s.tokens&&(t=t.concat(this.walkTokens(s.tokens,e)))}}return t}use(...n){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(t=>{let r={...t};if(r.async=this.defaults.async||r.async||!1,t.extensions&&(t.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let i=e.renderers[s.name];i?e.renderers[s.name]=function(...o){let l=s.renderer.apply(this,o);return l===!1&&(l=i.apply(this,o)),l}:e.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[s.level];i?i.unshift(s.tokenizer):e[s.level]=[s.tokenizer],s.start&&(s.level==="block"?e.startBlock?e.startBlock.push(s.start):e.startBlock=[s.start]:s.level==="inline"&&(e.startInline?e.startInline.push(s.start):e.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(e.childTokens[s.name]=s.childTokens)}),r.extensions=e),t.renderer){let s=this.defaults.renderer||new Kc(this.defaults);for(let i in t.renderer){if(!(i in s))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,l=t.renderer[o],a=s[o];s[o]=(...c)=>{let u=l.apply(s,c);return u===!1&&(u=a.apply(s,c)),u||""}}r.renderer=s}if(t.tokenizer){let s=this.defaults.tokenizer||new Jc(this.defaults);for(let i in t.tokenizer){if(!(i in s))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,l=t.tokenizer[o],a=s[o];s[o]=(...c)=>{let u=l.apply(s,c);return u===!1&&(u=a.apply(s,c)),u}}r.tokenizer=s}if(t.hooks){let s=this.defaults.hooks||new vo;for(let i in t.hooks){if(!(i in s))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,l=t.hooks[o],a=s[o];vo.passThroughHooks.has(i)?s[o]=c=>{if(this.defaults.async&&vo.passThroughHooksRespectAsync.has(i))return(async()=>{let d=await l.call(s,c);return a.call(s,d)})();let u=l.call(s,c);return a.call(s,u)}:s[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await l.apply(s,c);return d===!1&&(d=await a.apply(s,c)),d})();let u=l.apply(s,c);return u===!1&&(u=a.apply(s,c)),u}}r.hooks=s}if(t.walkTokens){let s=this.defaults.walkTokens,i=t.walkTokens;r.walkTokens=function(o){let l=[];return l.push(i.call(this,o)),s&&(l=l.concat(s.call(this,o))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(n){return this.defaults={...this.defaults,...n},this}lexer(n,e){return Nt.lex(n,e??this.defaults)}parser(n,e){return It.parse(n,e??this.defaults)}parseMarkdown(n){return(e,t)=>{let r={...t},s={...this.defaults,...r},i=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=n),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(e):e,l=await(s.hooks?await s.hooks.provideLexer(n):n?Nt.lex:Nt.lexInline)(o,s),a=s.hooks?await s.hooks.processAllTokens(l):l;s.walkTokens&&await Promise.all(this.walkTokens(a,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser(n):n?It.parse:It.parseInline)(a,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(i);try{s.hooks&&(e=s.hooks.preprocess(e));let o=(s.hooks?s.hooks.provideLexer(n):n?Nt.lex:Nt.lexInline)(e,s);s.hooks&&(o=s.hooks.processAllTokens(o)),s.walkTokens&&this.walkTokens(o,s.walkTokens);let l=(s.hooks?s.hooks.provideParser(n):n?It.parse:It.parseInline)(o,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(o){return i(o)}}}onError(n,e){return t=>{if(t.message+=` +Please report this to https://github.com/markedjs/marked.`,n){let r="

An error occurred:

"+Gt(t.message+"",!0)+"
";return e?Promise.resolve(r):r}if(e)return Promise.reject(t);throw t}}},Dr=new DO;function J(n,e){return Dr.parse(n,e)}J.options=J.setOptions=function(n){return Dr.setOptions(n),J.defaults=Dr.defaults,aS(J.defaults),J};J.getDefaults=xp;J.defaults=Or;J.use=function(...n){return Dr.use(...n),J.defaults=Dr.defaults,aS(J.defaults),J};J.walkTokens=function(n,e){return Dr.walkTokens(n,e)};J.parseInline=Dr.parseInline;J.Parser=It;J.parser=It.parse;J.Renderer=Kc;J.TextRenderer=Rp;J.Lexer=Nt;J.lexer=Nt.lex;J.Tokenizer=Jc;J.Hooks=vo;J.parse=J;var EU=J.options,MU=J.setOptions,RU=J.use,NU=J.walkTokens,IU=J.parseInline;var DU=It.parse,OU=Nt.lex;function OO(n){for(var e=1;e0&&n[e-1]===` +`;)e--;return n.substring(0,e)}function SS(n){return xS(bS(n))}var PO=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function Pp(n){return Lp(n,PO)}var vS=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function CS(n){return Lp(n,vS)}function LO(n){return AS(n,vS)}var TS=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function _O(n){return Lp(n,TS)}function BO(n){return AS(n,TS)}function Lp(n,e){return e.indexOf(n.nodeName)>=0}function AS(n,e){return n.getElementsByTagName&&e.some(function(t){return n.getElementsByTagName(t).length})}var zO=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function ES(n){return zO.reduce(function(e,t){return e.replace(t[0],t[1])},n)}var We={};We.paragraph={filter:"p",replacement:function(n){return` `+n+` `}};We.lineBreak={filter:"br",replacement:function(n,e,t){return t.br+` -`}};We.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(n,e,t){var r=Number(e.nodeName.charAt(1));if(t.headingStyle==="setext"&&r<3){var s=Ip(r===1?"=":"-",n.length);return` +`}};We.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(n,e,t){var r=Number(e.nodeName.charAt(1));if(t.headingStyle==="setext"&&r<3){var s=Op(r===1?"=":"-",n.length);return` `+n+` `+s+` `}else return` -`+Ip("#",r)+" "+n+` +`+Op("#",r)+" "+n+` -`}};We.blockquote={filter:"blockquote",replacement:function(n){return n=wS(n).replace(/^/gm,"> "),` +`}};We.blockquote={filter:"blockquote",replacement:function(n){return n=SS(n).replace(/^/gm,"> "),` `+n+` @@ -242,7 +242,7 @@ Please report this to https://github.com/markedjs/marked.`,n){let r="

An error `+n+` -`}};We.listItem={filter:"li",replacement:function(n,e,t){var r=t.bulletListMarker+" ",s=e.parentNode;if(s.nodeName==="OL"){var i=s.getAttribute("start"),o=Array.prototype.indexOf.call(s.children,e);r=(i?Number(i)+o:o+1)+". "}var l=/\n$/.test(n);return n=wS(n)+(l?` +`}};We.listItem={filter:"li",replacement:function(n,e,t){var r=t.bulletListMarker+" ",s=e.parentNode;if(s.nodeName==="OL"){var i=s.getAttribute("start"),o=Array.prototype.indexOf.call(s.children,e);r=(i?Number(i)+o:o+1)+". "}var l=/\n$/.test(n);return n=SS(n)+(l?` `:""),n=n.replace(/\n/gm,` `+" ".repeat(r.length)),r+n+(e.nextSibling?` `:"")}};We.indentedCodeBlock={filter:function(n,e){return e.codeBlockStyle==="indented"&&n.nodeName==="PRE"&&n.firstChild&&n.firstChild.nodeName==="CODE"},replacement:function(n,e,t){return` @@ -250,7 +250,7 @@ Please report this to https://github.com/markedjs/marked.`,n){let r="

An error `+e.firstChild.textContent.replace(/\n/g,` `)+` -`}};We.fencedCodeBlock={filter:function(n,e){return e.codeBlockStyle==="fenced"&&n.nodeName==="PRE"&&n.firstChild&&n.firstChild.nodeName==="CODE"},replacement:function(n,e,t){for(var r=e.firstChild.getAttribute("class")||"",s=(r.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,o=t.fence.charAt(0),l=3,a=new RegExp("^"+o+"{3,}","gm"),c;c=a.exec(i);)c[0].length>=l&&(l=c[0].length+1);var u=Ip(o,l);return` +`}};We.fencedCodeBlock={filter:function(n,e){return e.codeBlockStyle==="fenced"&&n.nodeName==="PRE"&&n.firstChild&&n.firstChild.nodeName==="CODE"},replacement:function(n,e,t){for(var r=e.firstChild.getAttribute("class")||"",s=(r.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,o=t.fence.charAt(0),l=3,a=new RegExp("^"+o+"{3,}","gm"),c;c=a.exec(i);)c[0].length>=l&&(l=c[0].length+1);var u=Op(o,l);return` `+u+s+` `+i.replace(/\n$/,"")+` @@ -260,13 +260,13 @@ Please report this to https://github.com/markedjs/marked.`,n){let r="

An error `+t.hr+` -`}};We.inlineLink={filter:function(n,e){return e.linkStyle==="inlined"&&n.nodeName==="A"&&n.getAttribute("href")},replacement:function(n,e){var t=Pp(e.getAttribute("href")),r=Lp(Gc(e.getAttribute("title"))),s=r?' "'+r+'"':"";return"["+n+"]("+t+s+")"}};We.referenceLink={filter:function(n,e){return e.linkStyle==="referenced"&&n.nodeName==="A"&&n.getAttribute("href")},replacement:function(n,e,t){var r=Pp(e.getAttribute("href")),s=Gc(e.getAttribute("title"));s&&(s=' "'+Lp(s)+'"');var i,o;switch(t.linkReferenceStyle){case"collapsed":i="["+n+"][]",o="["+n+"]: "+r+s;break;case"shortcut":i="["+n+"]",o="["+n+"]: "+r+s;break;default:var l=this.references.length+1;i="["+n+"]["+l+"]",o="["+l+"]: "+r+s}return this.references.push(o),i},references:[],append:function(n){var e="";return this.references.length&&(e=` +`}};We.inlineLink={filter:function(n,e){return e.linkStyle==="inlined"&&n.nodeName==="A"&&n.getAttribute("href")},replacement:function(n,e){var t=_p(e.getAttribute("href")),r=Bp(Xc(e.getAttribute("title"))),s=r?' "'+r+'"':"";return"["+n+"]("+t+s+")"}};We.referenceLink={filter:function(n,e){return e.linkStyle==="referenced"&&n.nodeName==="A"&&n.getAttribute("href")},replacement:function(n,e,t){var r=_p(e.getAttribute("href")),s=Xc(e.getAttribute("title"));s&&(s=' "'+Bp(s)+'"');var i,o;switch(t.linkReferenceStyle){case"collapsed":i="["+n+"][]",o="["+n+"]: "+r+s;break;case"shortcut":i="["+n+"]",o="["+n+"]: "+r+s;break;default:var l=this.references.length+1;i="["+n+"]["+l+"]",o="["+l+"]: "+r+s}return this.references.push(o),i},references:[],append:function(n){var e="";return this.references.length&&(e=` `+this.references.join(` `)+` -`,this.references=[]),e}};We.emphasis={filter:["em","i"],replacement:function(n,e,t){return n.trim()?t.emDelimiter+n+t.emDelimiter:""}};We.strong={filter:["strong","b"],replacement:function(n,e,t){return n.trim()?t.strongDelimiter+n+t.strongDelimiter:""}};We.code={filter:function(n){var e=n.previousSibling||n.nextSibling,t=n.parentNode.nodeName==="PRE"&&!e;return n.nodeName==="CODE"&&!t},replacement:function(n){if(!n)return"";n=n.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(n)?" ":"",t="`",r=n.match(/`+/gm)||[];r.indexOf(t)!==-1;)t=t+"`";return t+e+n+e+t}};We.image={filter:"img",replacement:function(n,e){var t=vS(Gc(e.getAttribute("alt"))),r=Pp(e.getAttribute("src")||""),s=Gc(e.getAttribute("title")),i=s?' "'+Lp(s)+'"':"";return r?"!["+t+"]("+r+i+")":""}};function Gc(n){return n?n.replace(/(\n+\s*)+/g,` -`):""}function Pp(n){var e=n.replace(/([<>()])/g,"\\$1");return e.indexOf(" ")>=0?"<"+e+">":e}function Lp(n){return n.replace(/"/g,'\\"')}function CS(n){this.options=n,this._keep=[],this._remove=[],this.blankRule={replacement:n.blankReplacement},this.keepReplacement=n.keepReplacement,this.defaultRule={replacement:n.defaultReplacement},this.array=[];for(var e in n.rules)this.array.push(n.rules[e])}CS.prototype={add:function(n,e){this.array.unshift(e)},keep:function(n){this._keep.unshift({filter:n,replacement:this.keepReplacement})},remove:function(n){this._remove.unshift({filter:n,replacement:function(){return""}})},forNode:function(n){if(n.isBlank)return this.blankRule;var e;return(e=Mp(this.array,n,this.options))||(e=Mp(this._keep,n,this.options))||(e=Mp(this._remove,n,this.options))?e:this.defaultRule},forEach:function(n){for(var e=0;e-1)return!0}else if(typeof r=="function"){if(r.call(n,e,t))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function _O(n){var e=n.element,t=n.isBlock,r=n.isVoid,s=n.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||s(e))){for(var i=null,o=!1,l=null,a=pS(l,e,s);a!==e;){if(a.nodeType===3||a.nodeType===4){var c=a.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!o&&c[0]===" "&&(c=c.substr(1)),!c){a=Rp(a);continue}a.data=c,i=a}else if(a.nodeType===1)t(a)||a.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,o=!1):r(a)||s(a)?(i=null,o=!0):i&&(o=!1);else{a=Rp(a);continue}var u=pS(l,a,s);l=a,a=u}i&&(i.data=i.data.replace(/ $/,""),i.data||Rp(i))}}function Rp(n){var e=n.nextSibling||n.parentNode;return n.parentNode.removeChild(n),e}function pS(n,e,t){return n&&n.parentNode===e||t(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}var _p=typeof window<"u"?window:{};function BO(){var n=_p.DOMParser,e=!1;try{new n().parseFromString("","text/html")&&(e=!0)}catch{}return e}function zO(){var n=function(){};return $O()?n.prototype.parseFromString=function(e){var t=new window.ActiveXObject("htmlfile");return t.designMode="on",t.open(),t.write(e),t.close(),t}:n.prototype.parseFromString=function(e){var t=document.implementation.createHTMLDocument("");return t.open(),t.write(e),t.close(),t},n}function $O(){var n=!1;try{document.implementation.createHTMLDocument("").open()}catch{_p.ActiveXObject&&(n=!0)}return n}var UO=BO()?_p.DOMParser:zO();function FO(n,e){var t;if(typeof n=="string"){var r=VO().parseFromString(''+n+"","text/html");t=r.getElementById("turndown-root")}else t=n.cloneNode(!0);return _O({element:t,isBlock:Dp,isVoid:bS,isPre:e.preformattedCode?HO:null}),t}var Np;function VO(){return Np=Np||new UO,Np}function HO(n){return n.nodeName==="PRE"||n.nodeName==="CODE"}function WO(n,e){return n.isBlock=Dp(n),n.isCode=n.nodeName==="CODE"||n.parentNode.isCode,n.isBlank=jO(n),n.flankingWhitespace=qO(n,e),n}function jO(n){return!bS(n)&&!DO(n)&&/^\s*$/i.test(n.textContent)&&!IO(n)&&!OO(n)}function qO(n,e){if(n.isBlock||e.preformattedCode&&n.isCode)return{leading:"",trailing:""};var t=JO(n.textContent);return t.leadingAscii&&mS("left",n,e)&&(t.leading=t.leadingNonAscii),t.trailingAscii&&mS("right",n,e)&&(t.trailing=t.trailingNonAscii),{leading:t.leading,trailing:t.trailing}}function JO(n){var e=n.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function mS(n,e,t){var r,s,i;return n==="left"?(r=e.previousSibling,s=/ $/):(r=e.nextSibling,s=/^ /),r&&(r.nodeType===3?i=s.test(r.nodeValue):t.preformattedCode&&r.nodeName==="CODE"?i=!1:r.nodeType===1&&!Dp(r)&&(i=s.test(r.textContent))),i}var KO=Array.prototype.reduce;function Co(n){if(!(this instanceof Co))return new Co(n);var e={rules:We,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(t,r){return r.isBlock?` +`,this.references=[]),e}};We.emphasis={filter:["em","i"],replacement:function(n,e,t){return n.trim()?t.emDelimiter+n+t.emDelimiter:""}};We.strong={filter:["strong","b"],replacement:function(n,e,t){return n.trim()?t.strongDelimiter+n+t.strongDelimiter:""}};We.code={filter:function(n){var e=n.previousSibling||n.nextSibling,t=n.parentNode.nodeName==="PRE"&&!e;return n.nodeName==="CODE"&&!t},replacement:function(n){if(!n)return"";n=n.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(n)?" ":"",t="`",r=n.match(/`+/gm)||[];r.indexOf(t)!==-1;)t=t+"`";return t+e+n+e+t}};We.image={filter:"img",replacement:function(n,e){var t=ES(Xc(e.getAttribute("alt"))),r=_p(e.getAttribute("src")||""),s=Xc(e.getAttribute("title")),i=s?' "'+Bp(s)+'"':"";return r?"!["+t+"]("+r+i+")":""}};function Xc(n){return n?n.replace(/(\n+\s*)+/g,` +`):""}function _p(n){var e=n.replace(/([<>()])/g,"\\$1");return e.indexOf(" ")>=0?"<"+e+">":e}function Bp(n){return n.replace(/"/g,'\\"')}function MS(n){this.options=n,this._keep=[],this._remove=[],this.blankRule={replacement:n.blankReplacement},this.keepReplacement=n.keepReplacement,this.defaultRule={replacement:n.defaultReplacement},this.array=[];for(var e in n.rules)this.array.push(n.rules[e])}MS.prototype={add:function(n,e){this.array.unshift(e)},keep:function(n){this._keep.unshift({filter:n,replacement:this.keepReplacement})},remove:function(n){this._remove.unshift({filter:n,replacement:function(){return""}})},forNode:function(n){if(n.isBlank)return this.blankRule;var e;return(e=Np(this.array,n,this.options))||(e=Np(this._keep,n,this.options))||(e=Np(this._remove,n,this.options))?e:this.defaultRule},forEach:function(n){for(var e=0;e-1)return!0}else if(typeof r=="function"){if(r.call(n,e,t))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function UO(n){var e=n.element,t=n.isBlock,r=n.isVoid,s=n.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||s(e))){for(var i=null,o=!1,l=null,a=wS(l,e,s);a!==e;){if(a.nodeType===3||a.nodeType===4){var c=a.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!o&&c[0]===" "&&(c=c.substr(1)),!c){a=Ip(a);continue}a.data=c,i=a}else if(a.nodeType===1)t(a)||a.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,o=!1):r(a)||s(a)?(i=null,o=!0):i&&(o=!1);else{a=Ip(a);continue}var u=wS(l,a,s);l=a,a=u}i&&(i.data=i.data.replace(/ $/,""),i.data||Ip(i))}}function Ip(n){var e=n.nextSibling||n.parentNode;return n.parentNode.removeChild(n),e}function wS(n,e,t){return n&&n.parentNode===e||t(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}var zp=typeof window<"u"?window:{};function FO(){var n=zp.DOMParser,e=!1;try{new n().parseFromString("","text/html")&&(e=!0)}catch{}return e}function VO(){var n=function(){};return HO()?n.prototype.parseFromString=function(e){var t=new window.ActiveXObject("htmlfile");return t.designMode="on",t.open(),t.write(e),t.close(),t}:n.prototype.parseFromString=function(e){var t=document.implementation.createHTMLDocument("");return t.open(),t.write(e),t.close(),t},n}function HO(){var n=!1;try{document.implementation.createHTMLDocument("").open()}catch{zp.ActiveXObject&&(n=!0)}return n}var WO=FO()?zp.DOMParser:VO();function jO(n,e){var t;if(typeof n=="string"){var r=qO().parseFromString(''+n+"","text/html");t=r.getElementById("turndown-root")}else t=n.cloneNode(!0);return UO({element:t,isBlock:Pp,isVoid:CS,isPre:e.preformattedCode?JO:null}),t}var Dp;function qO(){return Dp=Dp||new WO,Dp}function JO(n){return n.nodeName==="PRE"||n.nodeName==="CODE"}function KO(n,e){return n.isBlock=Pp(n),n.isCode=n.nodeName==="CODE"||n.parentNode.isCode,n.isBlank=YO(n),n.flankingWhitespace=GO(n,e),n}function YO(n){return!CS(n)&&!_O(n)&&/^\s*$/i.test(n.textContent)&&!LO(n)&&!BO(n)}function GO(n,e){if(n.isBlock||e.preformattedCode&&n.isCode)return{leading:"",trailing:""};var t=XO(n.textContent);return t.leadingAscii&&kS("left",n,e)&&(t.leading=t.leadingNonAscii),t.trailingAscii&&kS("right",n,e)&&(t.trailing=t.trailingNonAscii),{leading:t.leading,trailing:t.trailing}}function XO(n){var e=n.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function kS(n,e,t){var r,s,i;return n==="left"?(r=e.previousSibling,s=/ $/):(r=e.nextSibling,s=/^ /),r&&(r.nodeType===3?i=s.test(r.nodeValue):t.preformattedCode&&r.nodeName==="CODE"?i=!1:r.nodeType===1&&!Pp(r)&&(i=s.test(r.textContent))),i}var QO=Array.prototype.reduce;function To(n){if(!(this instanceof To))return new To(n);var e={rules:We,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(t,r){return r.isBlock?` `:""},keepReplacement:function(t,r){return r.isBlock?` @@ -276,34 +276,34 @@ Please report this to https://github.com/markedjs/marked.`,n){let r="

An error `+t+` -`:t}};this.options=RO({},e,n),this.rules=new CS(this.options)}Co.prototype={turndown:function(n){if(!XO(n))throw new TypeError(n+" is not a string, or an element/document/fragment node.");if(n==="")return"";var e=TS.call(this,new FO(n,this.options));return YO.call(this,e)},use:function(n){if(Array.isArray(n))for(var e=0;et.key===e&&this.onmessage!==null&&this.onmessage({data:Dk(t.newValue||"")}),yk(this._onChange)}postMessage(e){_a.setItem(this.room,$a(Ik(e)))}close(){wk(this._onChange)}},iP=typeof BroadcastChannel>"u"?zp:BroadcastChannel,$p=n=>Ge(NS,n,()=>{let e=tt(),t=new iP(n);return t.onmessage=r=>e.forEach(s=>s(r.data,"broadcastchannel")),{bc:t,subs:e}}),IS=(n,e)=>($p(n).subs.add(e),e),DS=(n,e)=>{let t=$p(n),r=t.subs.delete(e);return r&&t.subs.size===0&&(t.bc.close(),NS.delete(n)),r},Or=(n,e,t=null)=>{let r=$p(n);r.bc.postMessage(e),r.subs.forEach(s=>s(e,t))};var OS=0,Xc=1,PS=2,Qc=(n,e)=>{D(n,OS);let t=vb(e);Z(n,t)},Up=(n,e,t)=>{D(n,Xc),Z(n,bb(e,t))},lP=(n,e,t)=>Up(e,t,ke(n)),LS=(n,e,t,r)=>{try{kb(e,ke(n),t)}catch(s){r?.(s),console.error("Caught error while handling a Yjs update",s)}},_S=(n,e)=>{D(n,PS),Z(n,e)},aP=LS,BS=(n,e,t,r,s)=>{let i=L(n);switch(i){case OS:lP(n,e,t);break;case Xc:LS(n,t,r,s);break;case PS:aP(n,t,r,s);break;default:throw new Error("Unknown message type")}return i};var uP=0;var zS=(n,e,t)=>{L(n)===uP&&t(e,At(n))};var $S=n=>vk(n,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&");var Pr=0,FS=3,Us=1,fP=2,To=[];To[Pr]=(n,e,t,r,s)=>{D(n,Pr);let i=BS(e,n,t.doc,t);r&&i===Xc&&!t.synced&&(t.synced=!0)};To[FS]=(n,e,t,r,s)=>{D(n,Us),Z(n,Ls(t.awareness,Array.from(t.awareness.getStates().keys())))};To[Us]=(n,e,t,r,s)=>{Gb(t.awareness,ke(e),t)};To[fP]=(n,e,t,r,s)=>{zS(e,t.doc,(i,o)=>pP(t,o))};var US=3e4,pP=(n,e)=>console.warn(`Permission denied to access ${n.url}. -${e}`),VS=(n,e,t)=>{let r=Et(e),s=fe(),i=L(r),o=n.messageHandlers[i];return o?o(s,r,n,t,i):console.error("Unable to compute message"),s},Vp=(n,e,t)=>{e===n.ws&&(n.emit("connection-close",[t,n]),n.ws=null,e.close(),n.wsconnecting=!1,n.wsconnected?(n.wsconnected=!1,n.synced=!1,Ac(n.awareness,Array.from(n.awareness.getStates().keys()).filter(r=>r!==n.doc.clientID),n),n.emit("status",[{status:"disconnected"}])):n.wsUnsuccessfulReconnects++,setTimeout(HS,Tt(ek(2,n.wsUnsuccessfulReconnects)*100,n.maxBackoffTime),n))},HS=n=>{if(n.shouldConnect&&n.ws===null){let e=new n._WS(n.url,n.protocols);e.binaryType="arraybuffer",n.ws=e,n.wsconnecting=!0,n.wsconnected=!1,n.synced=!1,e.onmessage=t=>{n.wsLastMessageReceived=ct();let r=VS(n,new Uint8Array(t.data),!0);Ra(r)>1&&e.send(Y(r))},e.onerror=t=>{n.emit("connection-error",[t,n])},e.onclose=t=>{Vp(n,e,t)},e.onopen=()=>{n.wsLastMessageReceived=ct(),n.wsconnecting=!1,n.wsconnected=!0,n.wsUnsuccessfulReconnects=0,n.emit("status",[{status:"connected"}]);let t=fe();if(D(t,Pr),Qc(t,n.doc),e.send(Y(t)),n.awareness.getLocalState()!==null){let r=fe();D(r,Us),Z(r,Ls(n.awareness,[n.doc.clientID])),e.send(Y(r))}},n.emit("status",[{status:"connecting"}])}},Fp=(n,e)=>{let t=n.ws;n.wsconnected&&t&&t.readyState===t.OPEN&&t.send(e),n.bcconnected&&Or(n.bcChannel,e,n)},Zc=class extends mr{constructor(e,t,r,{connect:s=!0,awareness:i=new Tc(r),params:o={},protocols:l=[],WebSocketPolyfill:a=WebSocket,resyncInterval:c=-1,maxBackoffTime:u=2500,disableBc:d=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+t,this.maxBackoffTime=u,this.params=o,this.protocols=l,this.roomname=t,this.doc=r,this._WS=a,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=d,this.wsUnsuccessfulReconnects=0,this.messageHandlers=To.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=s,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let h=fe();D(h,Pr),Qc(h,r),this.ws.send(Y(h))}},c)),this._bcSubscriber=(h,f)=>{if(f!==this){let p=VS(this,new Uint8Array(h),!1);Ra(p)>1&&Or(this.bcChannel,Y(p),this)}},this._updateHandler=(h,f)=>{if(f!==this){let p=fe();D(p,Pr),_S(p,h),Fp(this,Y(p))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:h,updated:f,removed:p},m)=>{let g=h.concat(f).concat(p),y=fe();D(y,Us),Z(y,Ls(i,g)),Fp(this,Y(y))},this._exitHandler=()=>{Ac(this.awareness,[r.clientID],"app closed")},pn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&US=300)throw new bn(i.status,o);return o}async rawRequest(e,t,r,s={}){let i={...s.auth===!1||!this.token?{}:{authorization:`Bearer ${this.token}`},...r===void 0?{}:{"content-type":s.contentType??"application/json"}},o=await this.transport.request({method:e,url:`${this.serverUrl.replace(/\/+$/,"")}/api${t}`,headers:i,body:r===void 0?void 0:s.raw?r:JSON.stringify(r)});if(o.status<200||o.status>=300)throw new bn(o.status,WS(o.text));return o}};function WS(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}var eu=class{constructor(e,t){this.adapter=e;this.path=`${t.replace(/\/+$/,"")}/.server-meta.json`}adapter;path;get filePath(){return this.path}async read(){if(!await this.adapter.exists(this.path))return{documents:{},attachments:{}};let e=await this.adapter.read(this.path),t=JSON.parse(e);return{documents:t.documents??{},attachments:t.attachments??{}}}async write(e){await this.adapter.write(this.path,JSON.stringify(e,null,2))}async list(){let e=await this.read();return Object.values(e.documents)}async getByLocalPath(e){let t=await this.read();return Object.values(t.documents).find(r=>r.localPath===e)??null}async upsert(e){let t=await this.read();t.documents[e.documentId]=e,await this.write(t)}async listAttachments(){let e=await this.read();return Object.values(e.attachments??{})}async listAttachmentsForDocument(e){let t=await this.read();return Object.values(t.attachments??{}).filter(r=>r.documentId===e)}async upsertAttachment(e){let t=await this.read();t.attachments??={},t.attachments[e.attachmentId]=e,await this.write(t)}async removeAttachment(e){let t=await this.read();t.attachments&&(delete t.attachments[e],await this.write(t))}};var Dt=require("obsidian");function ht(n){return n.replace(/\r\n/g,` +`}};$s.tableSection={filter:["thead","tbody","tfoot"],replacement:function(n){return n}};function $p(n){var e=n.parentNode;return e.nodeName==="THEAD"||e.firstChild===n&&(e.nodeName==="TABLE"||oP(e))&&iP.call(n.childNodes,function(t){return t.nodeName==="TH"})}function oP(n){var e=n.previousSibling;return n.nodeName==="TBODY"&&(!e||e.nodeName==="THEAD"&&/^\s*$/i.test(e.textContent))}function DS(n,e){var t=sP.call(e.parentNode.childNodes,e),r=" ";return t===0&&(r="| "),r+n+" |"}function lP(n){n.keep(function(t){return t.nodeName==="TABLE"&&!$p(t.rows[0])});for(var e in $s)n.addRule(e,$s[e])}function aP(n){n.addRule("taskListItems",{filter:function(e){return e.type==="checkbox"&&e.parentNode.nodeName==="LI"},replacement:function(e,t){return(t.checked?"[x]":"[ ]")+" "}})}function OS(n){n.use([nP,rP,lP,aP])}var PS=new Map,Up=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&this.onmessage!==null&&this.onmessage({data:_k(t.newValue||"")}),xk(this._onChange)}postMessage(e){Ba.setItem(this.room,Ua(Lk(e)))}close(){Sk(this._onChange)}},cP=typeof BroadcastChannel>"u"?Up:BroadcastChannel,Fp=n=>Ge(PS,n,()=>{let e=tt(),t=new cP(n);return t.onmessage=r=>e.forEach(s=>s(r.data,"broadcastchannel")),{bc:t,subs:e}}),LS=(n,e)=>(Fp(n).subs.add(e),e),_S=(n,e)=>{let t=Fp(n),r=t.subs.delete(e);return r&&t.subs.size===0&&(t.bc.close(),PS.delete(n)),r},Pr=(n,e,t=null)=>{let r=Fp(n);r.bc.postMessage(e),r.subs.forEach(s=>s(e,t))};var BS=0,Qc=1,zS=2,Zc=(n,e)=>{D(n,BS);let t=Eb(e);Z(n,t)},Vp=(n,e,t)=>{D(n,Qc),Z(n,Cb(e,t))},dP=(n,e,t)=>Vp(e,t,ke(n)),$S=(n,e,t,r)=>{try{vb(e,ke(n),t)}catch(s){r?.(s),console.error("Caught error while handling a Yjs update",s)}},US=(n,e)=>{D(n,zS),Z(n,e)},hP=$S,FS=(n,e,t,r,s)=>{let i=L(n);switch(i){case BS:dP(n,e,t);break;case Qc:$S(n,t,r,s);break;case zS:hP(n,t,r,s);break;default:throw new Error("Unknown message type")}return i};var pP=0;var VS=(n,e,t)=>{L(n)===pP&&t(e,At(n))};var HS=n=>Ek(n,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&");var Lr=0,jS=3,Us=1,yP=2,Ao=[];Ao[Lr]=(n,e,t,r,s)=>{D(n,Lr);let i=FS(e,n,t.doc,t);r&&i===Qc&&!t.synced&&(t.synced=!0)};Ao[jS]=(n,e,t,r,s)=>{D(n,Us),Z(n,Ls(t.awareness,Array.from(t.awareness.getStates().keys())))};Ao[Us]=(n,e,t,r,s)=>{ex(t.awareness,ke(e),t)};Ao[yP]=(n,e,t,r,s)=>{VS(e,t.doc,(i,o)=>wP(t,o))};var WS=3e4,wP=(n,e)=>console.warn(`Permission denied to access ${n.url}. +${e}`),qS=(n,e,t)=>{let r=Et(e),s=fe(),i=L(r),o=n.messageHandlers[i];return o?o(s,r,n,t,i):console.error("Unable to compute message"),s},Wp=(n,e,t)=>{e===n.ws&&(n.emit("connection-close",[t,n]),n.ws=null,e.close(),n.wsconnecting=!1,n.wsconnected?(n.wsconnected=!1,n.synced=!1,Ec(n.awareness,Array.from(n.awareness.getStates().keys()).filter(r=>r!==n.doc.clientID),n),n.emit("status",[{status:"disconnected"}])):n.wsUnsuccessfulReconnects++,setTimeout(JS,Tt(sk(2,n.wsUnsuccessfulReconnects)*100,n.maxBackoffTime),n))},JS=n=>{if(n.shouldConnect&&n.ws===null){let e=new n._WS(n.url,n.protocols);e.binaryType="arraybuffer",n.ws=e,n.wsconnecting=!0,n.wsconnected=!1,n.synced=!1,e.onmessage=t=>{n.wsLastMessageReceived=ct();let r=qS(n,new Uint8Array(t.data),!0);Na(r)>1&&e.send(Y(r))},e.onerror=t=>{n.emit("connection-error",[t,n])},e.onclose=t=>{Wp(n,e,t)},e.onopen=()=>{n.wsLastMessageReceived=ct(),n.wsconnecting=!1,n.wsconnected=!0,n.wsUnsuccessfulReconnects=0,n.emit("status",[{status:"connected"}]);let t=fe();if(D(t,Lr),Zc(t,n.doc),e.send(Y(t)),n.awareness.getLocalState()!==null){let r=fe();D(r,Us),Z(r,Ls(n.awareness,[n.doc.clientID])),e.send(Y(r))}},n.emit("status",[{status:"connecting"}])}},Hp=(n,e)=>{let t=n.ws;n.wsconnected&&t&&t.readyState===t.OPEN&&t.send(e),n.bcconnected&&Pr(n.bcChannel,e,n)},eu=class extends mr{constructor(e,t,r,{connect:s=!0,awareness:i=new Ac(r),params:o={},protocols:l=[],WebSocketPolyfill:a=WebSocket,resyncInterval:c=-1,maxBackoffTime:u=2500,disableBc:d=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+t,this.maxBackoffTime=u,this.params=o,this.protocols=l,this.roomname=t,this.doc=r,this._WS=a,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=d,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Ao.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=s,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let h=fe();D(h,Lr),Zc(h,r),this.ws.send(Y(h))}},c)),this._bcSubscriber=(h,f)=>{if(f!==this){let p=qS(this,new Uint8Array(h),!1);Na(p)>1&&Pr(this.bcChannel,Y(p),this)}},this._updateHandler=(h,f)=>{if(f!==this){let p=fe();D(p,Lr),US(p,h),Hp(this,Y(p))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:h,updated:f,removed:p},m)=>{let g=h.concat(f).concat(p),y=fe();D(y,Us),Z(y,Ls(i,g)),Hp(this,Y(y))},this._exitHandler=()=>{Ec(this.awareness,[r.clientID],"app closed")},mn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&WS=300)throw new xn(i.status,o);return o}async rawRequest(e,t,r,s={}){let i={...s.auth===!1||!this.token?{}:{authorization:`Bearer ${this.token}`},...r===void 0?{}:{"content-type":s.contentType??"application/json"}},o=await this.transport.request({method:e,url:`${this.serverUrl.replace(/\/+$/,"")}/api${t}`,headers:i,body:r===void 0?void 0:s.raw?r:JSON.stringify(r)});if(o.status<200||o.status>=300)throw new xn(o.status,KS(o.text));return o}};function KS(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}var tu=class{constructor(e,t){this.adapter=e;this.path=`${t.replace(/\/+$/,"")}/.server-meta.json`}adapter;path;get filePath(){return this.path}async read(){if(!await this.adapter.exists(this.path))return{documents:{},attachments:{}};let e=await this.adapter.read(this.path),t=JSON.parse(e);return{documents:t.documents??{},attachments:t.attachments??{}}}async write(e){await this.adapter.write(this.path,JSON.stringify(e,null,2))}async list(){let e=await this.read();return Object.values(e.documents)}async getByLocalPath(e){let t=await this.read();return Object.values(t.documents).find(r=>r.localPath===e)??null}async upsert(e){let t=await this.read();t.documents[e.documentId]=e,await this.write(t)}async listAttachments(){let e=await this.read();return Object.values(e.attachments??{})}async listAttachmentsForDocument(e){let t=await this.read();return Object.values(t.attachments??{}).filter(r=>r.documentId===e)}async upsertAttachment(e){let t=await this.read();t.attachments??={},t.attachments[e.attachmentId]=e,await this.write(t)}async removeAttachment(e){let t=await this.read();t.attachments&&(delete t.attachments[e],await this.write(t))}};var Dt=require("obsidian");function ht(n){return n.replace(/\r\n/g,` `).replace(/\r/g,` `).replace(/\n*$/,"")+` -`}async function Lr(n){if(!globalThis.crypto?.subtle)throw new Error("Web Crypto is required to compute Pageden checksums.");let e=new TextEncoder().encode(ht(n)),t=await globalThis.crypto.subtle.digest("SHA-256",e);return`sha256:${[...new Uint8Array(t)].map(s=>s.toString(16).padStart(2,"0")).join("")}`}function mP(n,e){let t=e.replace(/^\/+/,""),r=t.endsWith(".md")?t:`${t}.md`;return(0,Dt.normalizePath)(`${n}/${r}`)}async function Jp(n,e){let t=(0,Dt.normalizePath)(e).split("/").filter(Boolean),r="";for(let s of t)r=r?`${r}/${s}`:s,await n.exists(r)||await n.mkdir(r)}async function tu(n,e){let t=await n.api.document(e.id),r=mP(n.remoteDocsFolder,t.path),s=r.split("/").slice(0,-1).join("/");s&&await Jp(n.vault,s);let i=ht(t.content);await n.vault.write(r,i);let o=Ao(t,r);await n.meta.upsert(o);let l=Ro(n)?await Mo(n,o,i):GS();return{localPath:r,meta:o,attachments:l}}async function JS(n,e){let t=await n.meta.getByLocalPath(e);if(!t)throw new Error("This file is not linked to a Pageden document.");if(t.permission==="viewer")return{status:"blocked_viewer"};let r=ht(await n.vault.read(e));try{let s=await n.api.push(t.documentId,{baseVersion:t.baseVersion,checksum:await Lr(r),content:r}),i={...t,baseVersion:s.version,checksum:s.checksum,updatedAt:s.updatedAt};return await n.meta.upsert(i),Ro(n)&&await Mo(n,i,r),{status:"pushed",result:s}}catch(s){if(s instanceof bn&&s.status===409){let i=await n.api.document(t.documentId),o=await Wp(n.vault,e,i);return await n.meta.upsert({...t,baseVersion:i.version??t.baseVersion,checksum:i.checksum??t.checksum,permission:i.permission,updatedAt:i.updatedAt}),{status:"conflict",conflictPath:o,serverPath:i.path}}throw s}}async function Kp(n,e){return await n.meta.getByLocalPath(e)?JS(n,e):KS(n,e)}async function KS(n,e){let t=ht(await n.vault.read(e)),r=await n.api.tree(n.workspaceId),s=yP(n.remoteDocsFolder,e),i=s.documentPath;if(r.documents.some(u=>qp(u.path)===i))throw new Error(`A Pageden document already exists at "${i}". Download it first to link this local note safely.`);let o=await gP(n.api,n.workspaceId,r,s.folderSegments),l=await n.api.createDocument({workspaceId:n.workspaceId,folderId:o.id,title:wP(t)??s.title,slug:s.documentSlug,content:t}),a=await n.api.document(l.id),c=Ao(a,e);return await n.meta.upsert(c),Ro(n)&&await Mo(n,c,t),{status:"created",result:{id:a.id,version:c.baseVersion,checksum:c.checksum,updatedAt:c.updatedAt},meta:c}}async function Wp(n,e,t){let r=e.replace(/\.md$/i,""),s=(0,Dt.normalizePath)(`${r}.conflict.md`);return await n.write(s,ht(t.content)),s}function Ao(n,e){if(!n.version||!n.checksum)throw new Error("Remote document is missing version metadata.");return{documentId:n.id,localPath:e,remotePath:n.path,title:n.title,baseVersion:n.version,checksum:n.checksum,permission:n.permission,updatedAt:n.updatedAt}}async function gP(n,e,t,r){let s=new Map(t.folders.map(l=>[qp(l.path),l])),i=null,o="";for(let l of r){let a=jp(l);o=o?`${o}/${a}`:a;let c=s.get(o);if(c){i=c;continue}let u=await n.createFolder({workspaceId:e,parentFolderId:i?.id??null,name:l,slug:a});i={id:u.id,parentFolderId:i?.id??null,name:l,slug:a,path:qp(u.path),permission:"manager"},s.set(o,i)}if(!i)throw new Error("Create the note inside a folder so Pageden knows where to place it.");return i}function yP(n,e){let t=(0,Dt.normalizePath)(e),r=(0,Dt.normalizePath)(n).replace(/\/+$/,""),i=(t===r?"":t.startsWith(`${r}/`)?t.slice(r.length+1):t).split("/").filter(Boolean),o=i.pop()??"untitled.md",l=i.map(d=>d.replace(/\.md$/i,"")),a=o.replace(/\.md$/i,"")||"Untitled",c=jp(o),u=[...l.map(jp),`${c}.md`].filter(Boolean).join("/");return{folderSegments:l,title:a,documentSlug:c,documentPath:u}}function wP(n){if(!n.startsWith(`--- +`}async function _r(n){if(!globalThis.crypto?.subtle)throw new Error("Web Crypto is required to compute Pageden checksums.");let e=new TextEncoder().encode(ht(n)),t=await globalThis.crypto.subtle.digest("SHA-256",e);return`sha256:${[...new Uint8Array(t)].map(s=>s.toString(16).padStart(2,"0")).join("")}`}function kP(n,e){let t=e.replace(/^\/+/,""),r=t.endsWith(".md")?t:`${t}.md`;return(0,Dt.normalizePath)(`${n}/${r}`)}async function Yp(n,e){let t=(0,Dt.normalizePath)(e).split("/").filter(Boolean),r="";for(let s of t)r=r?`${r}/${s}`:s,await n.exists(r)||await n.mkdir(r)}async function nu(n,e){let t=await n.api.document(e.id),r=kP(n.remoteDocsFolder,t.path),s=r.split("/").slice(0,-1).join("/");s&&await Yp(n.vault,s);let i=ht(t.content);await n.vault.write(r,i);let o=Eo(t,r);await n.meta.upsert(o);let l=No(n)?await Ro(n,o,i):ev();return{localPath:r,meta:o,attachments:l}}async function XS(n,e){let t=await n.meta.getByLocalPath(e);if(!t)throw new Error("This file is not linked to a Pageden document.");if(t.permission==="viewer")return{status:"blocked_viewer"};let r=ht(await n.vault.read(e));try{let s=await n.api.push(t.documentId,{baseVersion:t.baseVersion,checksum:await _r(r),content:r}),i={...t,baseVersion:s.version,checksum:s.checksum,updatedAt:s.updatedAt};return await n.meta.upsert(i),No(n)&&await Ro(n,i,r),{status:"pushed",result:s}}catch(s){if(s instanceof xn&&s.status===409){let i=await n.api.document(t.documentId),o=await qp(n.vault,e,i);return await n.meta.upsert({...t,baseVersion:i.version??t.baseVersion,checksum:i.checksum??t.checksum,permission:i.permission,updatedAt:i.updatedAt}),{status:"conflict",conflictPath:o,serverPath:i.path}}throw s}}async function Gp(n,e){return await n.meta.getByLocalPath(e)?XS(n,e):QS(n,e)}async function QS(n,e){let t=ht(await n.vault.read(e)),r=await n.api.tree(n.workspaceId),s=xP(n.remoteDocsFolder,e),i=s.documentPath;if(r.documents.some(u=>Kp(u.path)===i))throw new Error(`A Pageden document already exists at "${i}". Download it first to link this local note safely.`);let o=await bP(n.api,n.workspaceId,r,s.folderSegments),l=await n.api.createDocument({workspaceId:n.workspaceId,folderId:o.id,title:SP(t)??s.title,slug:s.documentSlug,content:t}),a=await n.api.document(l.id),c=Eo(a,e);return await n.meta.upsert(c),No(n)&&await Ro(n,c,t),{status:"created",result:{id:a.id,version:c.baseVersion,checksum:c.checksum,updatedAt:c.updatedAt},meta:c}}async function qp(n,e,t){let r=e.replace(/\.md$/i,""),s=(0,Dt.normalizePath)(`${r}.conflict.md`);return await n.write(s,ht(t.content)),s}function Eo(n,e){if(!n.version||!n.checksum)throw new Error("Remote document is missing version metadata.");return{documentId:n.id,localPath:e,remotePath:n.path,title:n.title,baseVersion:n.version,checksum:n.checksum,permission:n.permission,updatedAt:n.updatedAt}}async function bP(n,e,t,r){let s=new Map(t.folders.map(l=>[Kp(l.path),l])),i=null,o="";for(let l of r){let a=Jp(l);o=o?`${o}/${a}`:a;let c=s.get(o);if(c){i=c;continue}let u=await n.createFolder({workspaceId:e,parentFolderId:i?.id??null,name:l,slug:a});i={id:u.id,parentFolderId:i?.id??null,name:l,slug:a,path:Kp(u.path),permission:"manager"},s.set(o,i)}if(!i)throw new Error("Create the note inside a folder so Pageden knows where to place it.");return i}function xP(n,e){let t=(0,Dt.normalizePath)(e),r=(0,Dt.normalizePath)(n).replace(/\/+$/,""),i=(t===r?"":t.startsWith(`${r}/`)?t.slice(r.length+1):t).split("/").filter(Boolean),o=i.pop()??"untitled.md",l=i.map(d=>d.replace(/\.md$/i,"")),a=o.replace(/\.md$/i,"")||"Untitled",c=Jp(o),u=[...l.map(Jp),`${c}.md`].filter(Boolean).join("/");return{folderSegments:l,title:a,documentSlug:c,documentPath:u}}function SP(n){if(!n.startsWith(`--- `))return null;let e=n.indexOf(` ---`,4);if(e===-1)return null;let t=n.slice(4,e);for(let r of t.split(` -`)){let s=r.match(/^title:\s*(.+)$/i);if(s?.[1])return s[1].trim().replace(/^['"]|['"]$/g,"")||null}return null}function jp(n){return n.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\.md$/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function qp(n){return n.replace(/^\/+|\/+$/g,"")}function Eo(n){return`${n.replace(/\.md$/i,"")}.conflict.md`}async function kP(n,e){let t={documentId:e.documentId,localPath:e.localPath},r;try{r=await n.api.document(e.documentId)}catch(l){if(l instanceof bn&&l.status===404)return{...t,status:"gone"};throw l}let s=(r.version??"")!==e.baseVersion,i=await n.vault.exists(e.localPath);if(await n.vault.exists(Eo(e.localPath)))return{...t,status:"conflict_pending",conflictPath:Eo(e.localPath)};let o="";if(i&&(o=ht(await n.vault.read(e.localPath)),await Lr(o)!==e.checksum)){if(r.permission==="viewer"){if(s){let c=await Wp(n.vault,e.localPath,r);return await n.meta.upsert(Ao(r,e.localPath)),{...t,status:"conflict",conflictPath:c}}return await n.meta.upsert({...e,permission:"viewer"}),{...t,status:"blocked_viewer"}}let a=await JS(n,e.localPath);return a.status==="pushed"?{...t,status:"pushed"}:a.status==="conflict"?{...t,status:"conflict",conflictPath:a.conflictPath}:{...t,status:"blocked_viewer"}}if(!i)return{...t,status:"missing_local"};if(s){let l=ht(await n.vault.read(e.localPath));if(await Lr(l)!==e.checksum){let a=await Wp(n.vault,e.localPath,r);return await n.meta.upsert(Ao(r,e.localPath)),{...t,status:"conflict",conflictPath:a}}return await bP(n,e.localPath,r),{...t,status:"pulled"}}return r.permission!==e.permission&&await n.meta.upsert({...e,permission:r.permission}),Ro(n)&&await Mo(n,{...e,permission:r.permission},o),{...t,status:"unchanged"}}async function bP(n,e,t){let r=e.split("/").slice(0,-1).join("/");r&&await Jp(n.vault,r);let s=ht(t.content);await n.vault.write(e,s);let i=Ao(t,e);await n.meta.upsert(i),Ro(n)&&await Mo(n,i,s)}async function YS(n,e){let t={unchanged:0,created:0,pulled:0,pushed:0,conflicts:0,conflictsPending:0,blockedViewer:0,missingLocal:0,gone:0,attachmentsDownloaded:0,attachmentsUploaded:0,attachmentsDeleted:0,errors:0},r=await n.meta.list(),s=new Set(r.map(i=>(0,Dt.normalizePath)(i.localPath)));for(let i of r)try{let o=await kP(n,i);switch(e?.(o),o.status){case"unchanged":t.unchanged+=1;break;case"created":t.created+=1;break;case"pulled":t.pulled+=1;break;case"pushed":t.pushed+=1;break;case"conflict":t.conflicts+=1;break;case"conflict_pending":t.conflictsPending+=1;break;case"blocked_viewer":t.blockedViewer+=1;break;case"missing_local":t.missingLocal+=1;break;case"gone":t.gone+=1;break}}catch{t.errors+=1}if(xP(n))for(let i of await n.localMarkdownPaths()){let o=(0,Dt.normalizePath)(i);if(!(s.has(o)||o.endsWith(".conflict.md")))try{let l=await KS(n,o);l.meta&&s.add((0,Dt.normalizePath)(l.meta.localPath)),t.created+=1,e?.({documentId:l.meta?.documentId??"",localPath:o,status:"created"})}catch{t.errors+=1}}return t}function xP(n){return!!(n.workspaceId&&n.localMarkdownPaths&&n.api.tree&&n.api.createFolder&&n.api.createDocument)}async function Mo(n,e,t){let r=SP(n),s=vP(n),i=CP(n),o=GS(),l=await r.attachments(e.documentId),a=await s.listAttachmentsForDocument(e.documentId),c=new Map(a.map(p=>[p.attachmentId,p])),u=new Map(l.attachments.map(p=>[p.id,p])),d=t??(await n.vault.exists(e.localPath)?await n.vault.read(e.localPath):""),h=e.permission==="viewer"?new Set:EP(d,e.localPath);for(let p of a)u.has(p.attachmentId)||await s.removeAttachment(p.attachmentId);if(e.permission!=="viewer")for(let p of a)!u.has(p.attachmentId)||h.has(p.localPath)||await n.vault.exists(p.localPath)||(await r.deleteAttachment(p.attachmentId),await s.removeAttachment(p.attachmentId),u.delete(p.attachmentId),o.deleted+=1);for(let p of l.attachments){if(!u.has(p.id))continue;let m=c.get(p.id)?.localPath??TP(e.localPath,p.filename);(!await n.vault.exists(m)||c.get(p.id)?.sha256!==p.sha256)&&(await AP(n.vault,m),await i.writeBinary(m,await r.downloadAttachment(p.id)),o.downloaded+=1),await s.upsertAttachment(qS(e.documentId,m,p))}if(e.permission==="viewer")return o;let f=new Map((await s.listAttachmentsForDocument(e.documentId)).map(p=>[p.localPath,p]));for(let p of h){if(!await n.vault.exists(p)){o.skipped+=1;continue}let m=await i.readBinary(p),g=await MP(m),y=f.get(p);if(y?.sha256===g){o.skipped+=1;continue}let w=await r.uploadAttachment(e.documentId,p.split("/").pop()??"attachment",m,RP(p));y&&(await r.deleteAttachment(y.attachmentId),await s.removeAttachment(y.attachmentId),o.deleted+=1),await s.upsertAttachment(qS(e.documentId,p,w)),o.uploaded+=1}return o}function GS(){return{downloaded:0,uploaded:0,deleted:0,skipped:0}}function Ro(n){return!!(n.api.attachments&&n.api.uploadAttachment&&n.api.downloadAttachment&&n.api.deleteAttachment&&n.vault.readBinary&&n.vault.writeBinary&&n.meta.listAttachmentsForDocument&&n.meta.upsertAttachment&&n.meta.removeAttachment)}function SP(n){if(!n.api.attachments||!n.api.uploadAttachment||!n.api.downloadAttachment||!n.api.deleteAttachment)throw new Error("Attachment sync requires attachment API methods.");return n.api}function vP(n){if(!n.meta.listAttachmentsForDocument||!n.meta.upsertAttachment||!n.meta.removeAttachment)throw new Error("Attachment sync requires attachment metadata methods.");return n.meta}function CP(n){if(!n.vault.readBinary||!n.vault.writeBinary)throw new Error("Attachment sync requires binary vault methods.");return n.vault}function qS(n,e,t){return{attachmentId:t.id,documentId:n,localPath:e,filename:t.filename,sha256:t.sha256,size:t.size,contentType:t.contentType,createdAt:t.createdAt}}function TP(n,e){let t=n.split("/").slice(0,-1).join("/");return(0,Dt.normalizePath)(`${t}/${e}`)}async function AP(n,e){let t=e.split("/").slice(0,-1).join("/");t&&await Jp(n,t)}function EP(n,e){let t=e.split("/").slice(0,-1).join("/"),r=new Set,s=i=>{let o=i.trim();if(!o||o.startsWith("#")||/^[a-z][a-z0-9+.-]*:/i.test(o)||o.endsWith(".md"))return;let l=o.split(/[?#]/)[0]??"";l&&r.add((0,Dt.normalizePath)(l.startsWith("/")?l.slice(1):`${t}/${l}`))};for(let i of n.matchAll(/!\[[^\]]*]\(([^)]+)\)|\[[^\]]+]\(([^)]+)\)/g))s(i[1]??i[2]??"");for(let i of n.matchAll(/!\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?]]/g))s(i[1]??"");return r}async function MP(n){let e=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function RP(n){let e=n.split(".").pop()?.toLowerCase();return e==="png"?"image/png":e==="jpg"||e==="jpeg"?"image/jpeg":e==="gif"?"image/gif":e==="webp"?"image/webp":e==="svg"?"image/svg+xml":e==="pdf"?"application/pdf":"application/octet-stream"}function XS(n){let e=!1,t=!1;async function r(){if(e){t=!0;return}e=!0;try{do t=!1,await n();while(t)}finally{e=!1}}return{run:r,isRunning:()=>e}}function QS(n){let e=new Map;function t(r){let s=e.get(r);s!==void 0&&(clearTimeout(s),e.delete(r))}return{schedule(r,s){t(r),e.set(r,setTimeout(()=>{e.delete(r),s()},n))},cancel:t,cancelAll(){for(let r of e.values())clearTimeout(r);e.clear()}}}var Vs=require("obsidian");var NP="Imported from Obsidian";function Yp(n,e,t=NP){let r=t1(n),s=Do(t),i=new Set(e.documents.map(a=>Io(a.path))),o=r.notes.map(a=>n1(a.path,s)).filter(a=>i.has(a)).sort(),l=o.length?[`${o.length} note${o.length===1?"":"s"} already exist in Pageden and will be skipped.`]:[];return{targetRootName:t,targetRootSlug:s,notes:r.notes.length,attachments:r.attachments.length,skipped:r.skipped,conflicts:o,warnings:l}}async function e1(n){let e=n.remoteTree??await n.api.tree(n.workspaceId),t=Yp(n.files,e,n.targetRootName),r=t1(n.files),s=OP(r.attachments),i=new Map(e.folders.map(g=>[Io(g.path),g])),o=new Set(e.documents.map(g=>Io(g.path))),l=t.targetRootSlug,a=0,c=0,u=0,d=0,h=[],f=[];async function p(g){let y=g.split("/").filter(Boolean),w=null,b="",v=l;if(w=i.get(v)??null,!w){let C=await n.api.createFolder({workspaceId:n.workspaceId,parentFolderId:null,name:n.targetRootName,slug:l});w=ZS(C.id,null,n.targetRootName,l,C.path),i.set(v,w),a+=1}b=v;for(let C of y){let R=Do(C);b=`${b}/${R}`;let A=i.get(b);if(A){w=A;continue}let _=await n.api.createFolder({workspaceId:n.workspaceId,parentFolderId:w.id,name:C,slug:R});w=ZS(_.id,w.id,C,R,_.path),i.set(b,w),a+=1}return w}let m=0;for(let g of r.notes){m++,n.onProgress?.(m,r.notes.length);let y=n1(g.path,l);if(o.has(y)){u+=1,f.push({path:g.path,status:"skipped",message:"A document with this path already exists."});continue}let w=Gp(g.path),b=await p(w),v=ht(await n.vault.read(g.path)),C=LP(v)??(No(g.path).replace(/\.md$/i,"")||"Untitled"),R=await n.api.createDocument({workspaceId:n.workspaceId,folderId:b.id,title:C,slug:Do(No(g.path).replace(/\.md$/i,"")),content:v});o.add(Io(R.path));let A=await n.api.document(R.id);await n.meta.upsert(BP(A,g.path)),c+=1,f.push({path:g.path,status:"created",message:`Created ${R.path}`});let _=IP(v),U=new Set;for(let ae of _){let ce=PP(ae,g.path,s);if(!(!ce||U.has(ce.path))){if(U.add(ce.path),!n.vault.readBinary){let xe=`Cannot upload ${ce.path}: this vault adapter does not support binary reads.`;h.push(xe),f.push({path:ce.path,status:"warning",message:xe});continue}try{let xe=await n.vault.readBinary(ce.path);await _P(n.api,A.id,No(ce.path),xe,zP(ce.path)),d+=1}catch(xe){let ge=`Could not upload ${ce.path}: ${xe instanceof Error?xe.message:"unknown error"}`;h.push(ge),f.push({path:ce.path,status:"warning",message:ge})}}}}return{...t,foldersCreated:a,documentsCreated:c,documentsSkipped:u,attachmentsUploaded:d,attachmentWarnings:h,rows:f}}function IP(n){let e=new Set,t=/!\[\[([^\]#|]+)(?:[#|][^\]]*)?\]\]/g,r=/!\[[^\]]*]\((?![a-z][a-z0-9+.-]*:)([^)\s]+)(?:\s+"[^"]*")?\)/gi;for(let s of n.matchAll(t))s[1]&&e.add(s[1]);for(let s of n.matchAll(r))s[1]&&e.add(decodeURIComponent(s[1]));return[...e]}function Do(n){return n.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\.md$/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function t1(n){let e=0,t=[],r=[];for(let s of n){let i=(0,Vs.normalizePath)(s.path);if(DP(i)){e+=1;continue}s.extension.toLowerCase()==="md"?i.endsWith(".conflict.md")?e+=1:t.push({...s,path:i}):r.push({...s,path:i})}return t.sort((s,i)=>s.path.localeCompare(i.path)),r.sort((s,i)=>s.path.localeCompare(i.path)),{notes:t,attachments:r,skipped:e}}function DP(n){return n.startsWith(".obsidian/")||n.startsWith(".trash/")||n.startsWith(".git/")}function OP(n){let e=new Map,t=new Map;for(let r of n){e.set(r.path,r);let s=t.get(r.name)??[];s.push(r),t.set(r.name,s)}return{byPath:e,byName:t}}function PP(n,e,t){let r=(0,Vs.normalizePath)(n.replace(/^<|>$/g,"")),s=Gp(e),i=[(0,Vs.normalizePath)(`${s}/${r}`),r];for(let l of i){let a=t.byPath.get(l);if(a)return a}let o=t.byName.get(No(r));return o?.length?o[0]??null:null}function n1(n,e){let t=Gp(n).split("/").filter(Boolean).map(Do).join("/"),r=Do(No(n));return[e,t,`${r}.md`].filter(Boolean).join("/")}function LP(n){if(!n.startsWith(`--- +`)){let s=r.match(/^title:\s*(.+)$/i);if(s?.[1])return s[1].trim().replace(/^['"]|['"]$/g,"")||null}return null}function Jp(n){return n.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\.md$/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Kp(n){return n.replace(/^\/+|\/+$/g,"")}function Mo(n){return`${n.replace(/\.md$/i,"")}.conflict.md`}async function vP(n,e){let t={documentId:e.documentId,localPath:e.localPath},r;try{r=await n.api.document(e.documentId)}catch(l){if(l instanceof xn&&l.status===404)return{...t,status:"gone"};throw l}let s=(r.version??"")!==e.baseVersion,i=await n.vault.exists(e.localPath);if(await n.vault.exists(Mo(e.localPath)))return{...t,status:"conflict_pending",conflictPath:Mo(e.localPath)};let o="";if(i&&(o=ht(await n.vault.read(e.localPath)),await _r(o)!==e.checksum)){if(r.permission==="viewer"){if(s){let c=await qp(n.vault,e.localPath,r);return await n.meta.upsert(Eo(r,e.localPath)),{...t,status:"conflict",conflictPath:c}}return await n.meta.upsert({...e,permission:"viewer"}),{...t,status:"blocked_viewer"}}let a=await XS(n,e.localPath);return a.status==="pushed"?{...t,status:"pushed"}:a.status==="conflict"?{...t,status:"conflict",conflictPath:a.conflictPath}:{...t,status:"blocked_viewer"}}if(!i)return{...t,status:"missing_local"};if(s){let l=ht(await n.vault.read(e.localPath));if(await _r(l)!==e.checksum){let a=await qp(n.vault,e.localPath,r);return await n.meta.upsert(Eo(r,e.localPath)),{...t,status:"conflict",conflictPath:a}}return await CP(n,e.localPath,r),{...t,status:"pulled"}}return r.permission!==e.permission&&await n.meta.upsert({...e,permission:r.permission}),No(n)&&await Ro(n,{...e,permission:r.permission},o),{...t,status:"unchanged"}}async function CP(n,e,t){let r=e.split("/").slice(0,-1).join("/");r&&await Yp(n.vault,r);let s=ht(t.content);await n.vault.write(e,s);let i=Eo(t,e);await n.meta.upsert(i),No(n)&&await Ro(n,i,s)}async function ZS(n,e){let t={unchanged:0,created:0,pulled:0,pushed:0,conflicts:0,conflictsPending:0,blockedViewer:0,missingLocal:0,gone:0,attachmentsDownloaded:0,attachmentsUploaded:0,attachmentsDeleted:0,errors:0},r=await n.meta.list(),s=new Set(r.map(i=>(0,Dt.normalizePath)(i.localPath)));for(let i of r)try{let o=await vP(n,i);switch(e?.(o),o.status){case"unchanged":t.unchanged+=1;break;case"created":t.created+=1;break;case"pulled":t.pulled+=1;break;case"pushed":t.pushed+=1;break;case"conflict":t.conflicts+=1;break;case"conflict_pending":t.conflictsPending+=1;break;case"blocked_viewer":t.blockedViewer+=1;break;case"missing_local":t.missingLocal+=1;break;case"gone":t.gone+=1;break}}catch{t.errors+=1}if(TP(n))for(let i of await n.localMarkdownPaths()){let o=(0,Dt.normalizePath)(i);if(!(s.has(o)||o.endsWith(".conflict.md")))try{let l=await QS(n,o);l.meta&&s.add((0,Dt.normalizePath)(l.meta.localPath)),t.created+=1,e?.({documentId:l.meta?.documentId??"",localPath:o,status:"created"})}catch{t.errors+=1}}return t}function TP(n){return!!(n.workspaceId&&n.localMarkdownPaths&&n.api.tree&&n.api.createFolder&&n.api.createDocument)}async function Ro(n,e,t){let r=AP(n),s=EP(n),i=MP(n),o=ev(),l=await r.attachments(e.documentId),a=await s.listAttachmentsForDocument(e.documentId),c=new Map(a.map(p=>[p.attachmentId,p])),u=new Map(l.attachments.map(p=>[p.id,p])),d=t??(await n.vault.exists(e.localPath)?await n.vault.read(e.localPath):""),h=e.permission==="viewer"?new Set:IP(d,e.localPath);for(let p of a)u.has(p.attachmentId)||await s.removeAttachment(p.attachmentId);if(e.permission!=="viewer")for(let p of a)!u.has(p.attachmentId)||h.has(p.localPath)||await n.vault.exists(p.localPath)||(await r.deleteAttachment(p.attachmentId),await s.removeAttachment(p.attachmentId),u.delete(p.attachmentId),o.deleted+=1);for(let p of l.attachments){if(!u.has(p.id))continue;let m=c.get(p.id)?.localPath??RP(e.localPath,p.filename);(!await n.vault.exists(m)||c.get(p.id)?.sha256!==p.sha256)&&(await NP(n.vault,m),await i.writeBinary(m,await r.downloadAttachment(p.id)),o.downloaded+=1),await s.upsertAttachment(GS(e.documentId,m,p))}if(e.permission==="viewer")return o;let f=new Map((await s.listAttachmentsForDocument(e.documentId)).map(p=>[p.localPath,p]));for(let p of h){if(!await n.vault.exists(p)){o.skipped+=1;continue}let m=await i.readBinary(p),g=await DP(m),y=f.get(p);if(y?.sha256===g){o.skipped+=1;continue}let w=await r.uploadAttachment(e.documentId,p.split("/").pop()??"attachment",m,OP(p));y&&(await r.deleteAttachment(y.attachmentId),await s.removeAttachment(y.attachmentId),o.deleted+=1),await s.upsertAttachment(GS(e.documentId,p,w)),o.uploaded+=1}return o}function ev(){return{downloaded:0,uploaded:0,deleted:0,skipped:0}}function No(n){return!!(n.api.attachments&&n.api.uploadAttachment&&n.api.downloadAttachment&&n.api.deleteAttachment&&n.vault.readBinary&&n.vault.writeBinary&&n.meta.listAttachmentsForDocument&&n.meta.upsertAttachment&&n.meta.removeAttachment)}function AP(n){if(!n.api.attachments||!n.api.uploadAttachment||!n.api.downloadAttachment||!n.api.deleteAttachment)throw new Error("Attachment sync requires attachment API methods.");return n.api}function EP(n){if(!n.meta.listAttachmentsForDocument||!n.meta.upsertAttachment||!n.meta.removeAttachment)throw new Error("Attachment sync requires attachment metadata methods.");return n.meta}function MP(n){if(!n.vault.readBinary||!n.vault.writeBinary)throw new Error("Attachment sync requires binary vault methods.");return n.vault}function GS(n,e,t){return{attachmentId:t.id,documentId:n,localPath:e,filename:t.filename,sha256:t.sha256,size:t.size,contentType:t.contentType,createdAt:t.createdAt}}function RP(n,e){let t=n.split("/").slice(0,-1).join("/");return(0,Dt.normalizePath)(`${t}/${e}`)}async function NP(n,e){let t=e.split("/").slice(0,-1).join("/");t&&await Yp(n,t)}function IP(n,e){let t=e.split("/").slice(0,-1).join("/"),r=new Set,s=i=>{let o=i.trim();if(!o||o.startsWith("#")||/^[a-z][a-z0-9+.-]*:/i.test(o)||o.endsWith(".md"))return;let l=o.split(/[?#]/)[0]??"";l&&r.add((0,Dt.normalizePath)(l.startsWith("/")?l.slice(1):`${t}/${l}`))};for(let i of n.matchAll(/!\[[^\]]*]\(([^)]+)\)|\[[^\]]+]\(([^)]+)\)/g))s(i[1]??i[2]??"");for(let i of n.matchAll(/!\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?]]/g))s(i[1]??"");return r}async function DP(n){let e=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function OP(n){let e=n.split(".").pop()?.toLowerCase();return e==="png"?"image/png":e==="jpg"||e==="jpeg"?"image/jpeg":e==="gif"?"image/gif":e==="webp"?"image/webp":e==="svg"?"image/svg+xml":e==="pdf"?"application/pdf":"application/octet-stream"}function tv(n){let e=!1,t=!1;async function r(){if(e){t=!0;return}e=!0;try{do t=!1,await n();while(t)}finally{e=!1}}return{run:r,isRunning:()=>e}}function nv(n){let e=new Map;function t(r){let s=e.get(r);s!==void 0&&(clearTimeout(s),e.delete(r))}return{schedule(r,s){t(r),e.set(r,setTimeout(()=>{e.delete(r),s()},n))},cancel:t,cancelAll(){for(let r of e.values())clearTimeout(r);e.clear()}}}var Vs=require("obsidian");var PP="Imported from Obsidian";function Xp(n,e,t=PP){let r=iv(n),s=Oo(t),i=new Set(e.documents.map(a=>Do(a.path))),o=r.notes.map(a=>ov(a.path,s)).filter(a=>i.has(a)).sort(),l=o.length?[`${o.length} note${o.length===1?"":"s"} already exist in Pageden and will be skipped.`]:[];return{targetRootName:t,targetRootSlug:s,notes:r.notes.length,attachments:r.attachments.length,skipped:r.skipped,conflicts:o,warnings:l}}async function sv(n){let e=n.remoteTree??await n.api.tree(n.workspaceId),t=Xp(n.files,e,n.targetRootName),r=iv(n.files),s=BP(r.attachments),i=new Map(e.folders.map(g=>[Do(g.path),g])),o=new Set(e.documents.map(g=>Do(g.path))),l=t.targetRootSlug,a=0,c=0,u=0,d=0,h=[],f=[];async function p(g){let y=g.split("/").filter(Boolean),w=null,b="",v=l;if(w=i.get(v)??null,!w){let C=await n.api.createFolder({workspaceId:n.workspaceId,parentFolderId:null,name:n.targetRootName,slug:l});w=rv(C.id,null,n.targetRootName,l,C.path),i.set(v,w),a+=1}b=v;for(let C of y){let R=Oo(C);b=`${b}/${R}`;let E=i.get(b);if(E){w=E;continue}let _=await n.api.createFolder({workspaceId:n.workspaceId,parentFolderId:w.id,name:C,slug:R});w=rv(_.id,w.id,C,R,_.path),i.set(b,w),a+=1}return w}let m=0;for(let g of r.notes){m++,n.onProgress?.(m,r.notes.length);let y=ov(g.path,l);if(o.has(y)){u+=1,f.push({path:g.path,status:"skipped",message:"A document with this path already exists."});continue}let w=Qp(g.path),b=await p(w),v=ht(await n.vault.read(g.path)),C=$P(v)??(Io(g.path).replace(/\.md$/i,"")||"Untitled"),R=await n.api.createDocument({workspaceId:n.workspaceId,folderId:b.id,title:C,slug:Oo(Io(g.path).replace(/\.md$/i,"")),content:v});o.add(Do(R.path));let E=await n.api.document(R.id);await n.meta.upsert(FP(E,g.path)),c+=1,f.push({path:g.path,status:"created",message:`Created ${R.path}`});let _=LP(v),U=new Set;for(let ae of _){let ce=zP(ae,g.path,s);if(!(!ce||U.has(ce.path))){if(U.add(ce.path),!n.vault.readBinary){let xe=`Cannot upload ${ce.path}: this vault adapter does not support binary reads.`;h.push(xe),f.push({path:ce.path,status:"warning",message:xe});continue}try{let xe=await n.vault.readBinary(ce.path);await UP(n.api,E.id,Io(ce.path),xe,VP(ce.path)),d+=1}catch(xe){let ge=`Could not upload ${ce.path}: ${xe instanceof Error?xe.message:"unknown error"}`;h.push(ge),f.push({path:ce.path,status:"warning",message:ge})}}}}return{...t,foldersCreated:a,documentsCreated:c,documentsSkipped:u,attachmentsUploaded:d,attachmentWarnings:h,rows:f}}function LP(n){let e=new Set,t=/!\[\[([^\]#|]+)(?:[#|][^\]]*)?\]\]/g,r=/!\[[^\]]*]\((?![a-z][a-z0-9+.-]*:)([^)\s]+)(?:\s+"[^"]*")?\)/gi;for(let s of n.matchAll(t))s[1]&&e.add(s[1]);for(let s of n.matchAll(r))s[1]&&e.add(decodeURIComponent(s[1]));return[...e]}function Oo(n){return n.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\.md$/i,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function iv(n){let e=0,t=[],r=[];for(let s of n){let i=(0,Vs.normalizePath)(s.path);if(_P(i)){e+=1;continue}s.extension.toLowerCase()==="md"?i.endsWith(".conflict.md")?e+=1:t.push({...s,path:i}):r.push({...s,path:i})}return t.sort((s,i)=>s.path.localeCompare(i.path)),r.sort((s,i)=>s.path.localeCompare(i.path)),{notes:t,attachments:r,skipped:e}}function _P(n){return n.startsWith(".obsidian/")||n.startsWith(".trash/")||n.startsWith(".git/")}function BP(n){let e=new Map,t=new Map;for(let r of n){e.set(r.path,r);let s=t.get(r.name)??[];s.push(r),t.set(r.name,s)}return{byPath:e,byName:t}}function zP(n,e,t){let r=(0,Vs.normalizePath)(n.replace(/^<|>$/g,"")),s=Qp(e),i=[(0,Vs.normalizePath)(`${s}/${r}`),r];for(let l of i){let a=t.byPath.get(l);if(a)return a}let o=t.byName.get(Io(r));return o?.length?o[0]??null:null}function ov(n,e){let t=Qp(n).split("/").filter(Boolean).map(Oo).join("/"),r=Oo(Io(n));return[e,t,`${r}.md`].filter(Boolean).join("/")}function $P(n){if(!n.startsWith(`--- `))return null;let e=n.indexOf(` ---`,4);if(e===-1)return null;let t=n.slice(4,e);for(let r of t.split(` -`)){let s=r.match(/^title:\s*(.+)$/i);if(s?.[1])return s[1].trim().replace(/^['"]|['"]$/g,"")||null}return null}async function _P(n,e,t,r,s){try{await n.uploadAttachment(e,t,r,s)}catch(i){try{await n.uploadAttachment(e,t,r,s)}catch{throw i}}}function ZS(n,e,t,r,s){return{id:n,parentFolderId:e,name:t,slug:r,path:Io(s),permission:"manager"}}function BP(n,e){if(!n.version||!n.checksum)throw new Error("Imported document is missing version metadata.");return{documentId:n.id,localPath:e,remotePath:n.path,title:n.title,baseVersion:n.version,checksum:n.checksum,permission:n.permission,updatedAt:n.updatedAt}}function zP(n){let e=n.split(".").pop()?.toLowerCase();return e==="png"?"image/png":e==="jpg"||e==="jpeg"?"image/jpeg":e==="gif"?"image/gif":e==="webp"?"image/webp":e==="mp4"?"video/mp4":e==="webm"?"video/webm":e==="mov"?"video/quicktime":e==="pdf"?"application/pdf":"application/octet-stream"}function Gp(n){let e=(0,Vs.normalizePath)(n),t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function No(n){return(0,Vs.normalizePath)(n).split("/").filter(Boolean).pop()??""}function Io(n){return n.replace(/^\/+|\/+$/g,"")}var $P=2e3,r1=1500,Xp="pageden-live-document",o1=new Co({bulletListMarker:"-",codeBlockStyle:"fenced",headingStyle:"atx"});o1.use(RS);var Oo={serverUrl:"https://go.pageden.app",token:"",workspaceId:"",remoteDocsFolder:"Remote Docs",autoSyncEnabled:!1,autoSyncIntervalMinutes:5,userName:"",workspaceName:""},nu=class extends T.Plugin{settings=Oo;metaStore;statusBarEl;syncRunner;pushDebouncer;applyingRemoteWrites=new Set;syncIntervalId;lastSummary;async onload(){await this.loadSettings(),this.metaStore=new eu(this.app.vault.adapter,this.pluginDir()),this.addSettingTab(new Qp(this.app,this)),this.registerView(Xp,e=>new ru(e,this)),this.addCommand({id:"validate-connection",name:"Validate connection",callback:()=>{this.validateConnection()}}),this.addCommand({id:"browse-remote-documents",name:"Browse remote documents",callback:()=>{this.openRemoteBrowser()}}),this.addCommand({id:"search-remote-documents",name:"Search remote documents",callback:()=>{this.openRemoteSearch()}}),this.addCommand({id:"import-vault",name:"Import this vault to Pageden",callback:()=>{this.openVaultImport()}}),this.addCommand({id:"open-live-document",name:"Open live document",callback:()=>{this.openLiveDocumentPicker()}}),this.addCommand({id:"device-code-login",name:"Log in with device code",callback:()=>{this.startDeviceLogin()}}),this.addCommand({id:"push-active-document",name:"Push active document",checkCallback:e=>{let t=this.app.workspace.getActiveFile(),r=t instanceof T.TFile&&t.extension==="md";return e?r:(t&&this.pushFile(t),!0)}}),this.addCommand({id:"download-folder",name:"Download a Pageden folder",callback:()=>{this.openFolderDownload()}}),this.addCommand({id:"download-all-documents",name:"Download all Pageden documents",callback:()=>{this.downloadAllDocuments()}}),this.addCommand({id:"resolve-conflict",name:"Resolve conflict for this note",checkCallback:e=>{let t=this.app.workspace.getActiveFile(),r=t instanceof T.TFile&&t.extension==="md"&&!t.path.endsWith(".conflict.md");return e?r:(t&&this.resolveConflict(t),!0)}}),this.statusBarEl=this.addStatusBarItem(),this.syncRunner=XS(()=>this.runSyncPass()),this.pushDebouncer=QS($P),this.addCommand({id:"sync-now",name:"Sync now",callback:()=>{this.syncRunner.run()}}),this.registerEvent(this.app.vault.on("modify",e=>this.onVaultFileChanged(e))),this.registerEvent(this.app.vault.on("create",e=>this.onVaultFileChanged(e))),this.app.workspace.onLayoutReady(()=>this.startAutoSync())}onunload(){this.stopAutoSync()}startAutoSync(){if(this.stopAutoSync(),!this.settings.autoSyncEnabled){this.setStatusIdle();return}let e=Math.max(1,Math.floor(Number(this.settings.autoSyncIntervalMinutes))||Oo.autoSyncIntervalMinutes);this.syncIntervalId=window.setInterval(()=>{this.syncRunner.run()},e*6e4),this.registerInterval(this.syncIntervalId),this.isConfigured()?this.syncRunner.run():this.setStatus("Pageden: not connected")}stopAutoSync(){this.syncIntervalId!==void 0&&(window.clearInterval(this.syncIntervalId),this.syncIntervalId=void 0),this.pushDebouncer?.cancelAll()}isConfigured(){return!!(this.settings.serverUrl.trim()&&this.settings.token.trim()&&this.settings.workspaceId.trim())}async runSyncPass(){if(!(!this.settings.autoSyncEnabled||!this.isConfigured())){this.setStatus("Pageden: syncing\u2026");try{let e=await YS(this.backgroundSyncDeps());this.lastSummary=e,this.renderSummary(e)}catch{this.setStatus("Pageden: offline")}}}onVaultFileChanged(e){if(!this.settings.autoSyncEnabled||!this.isConfigured()||!(e instanceof T.TFile)||e.extension!=="md")return;let t=e.path;t.endsWith(".conflict.md")||this.applyingRemoteWrites.has(t)||this.pushDebouncer.schedule(t,()=>{this.debouncedPush(t)})}async debouncedPush(e){if(this.syncRunner.isRunning()){this.pushDebouncer.schedule(e,()=>{this.debouncedPush(e)});return}try{let t=await this.metaStore.getByLocalPath(e);if(t?.permission==="viewer"||!t&&!s1(this.settings.remoteDocsFolder,e)||await this.app.vault.adapter.exists(Eo(e)))return;let r=ht(await this.app.vault.adapter.read(e));if(t&&await Lr(r)===t.checksum)return;let s=await Kp(this.createSyncDeps(),e);s.status==="conflict"?this.setStatus("Pageden: conflict"):(s.status==="pushed"||s.status==="created")&&this.setStatusIdle()}catch{this.setStatus("Pageden: error")}}backgroundSyncDeps(){let e=this.syncDeps();return{...e,vault:this.guardedVault(e.vault),workspaceId:this.settings.workspaceId,localMarkdownPaths:async()=>this.app.vault.getFiles().filter(t=>t.extension==="md"&&s1(this.settings.remoteDocsFolder,t.path)).map(t=>t.path)}}guardedVault(e){return{...e,write:async(t,r)=>{this.applyingRemoteWrites.add(t);try{await e.write(t,r)}finally{window.setTimeout(()=>this.applyingRemoteWrites.delete(t),r1)}},writeBinary:e.writeBinary?async(t,r)=>{this.applyingRemoteWrites.add(t);try{await e.writeBinary?.(t,r)}finally{window.setTimeout(()=>this.applyingRemoteWrites.delete(t),r1)}}:void 0}}setStatus(e){this.statusBarEl?.setText(e)}setStatusIdle(){let e=this.lastSummary;e&&e.conflicts?this.setStatus(`Pageden: ${e.conflicts} conflict${e.conflicts===1?"":"s"} \u2014 run "Resolve conflict" to fix`):e&&(e.created||e.pulled||e.pushed)?this.setStatus(`Pageden: synced (${e.created} created, ${e.pushed} sent, ${e.pulled} received)`):this.setStatus("Pageden: up to date")}renderSummary(e){e.errors?this.setStatus("Pageden: sync error \u2014 will retry"):e.conflicts?this.setStatus(`Pageden: ${e.conflicts} conflict${e.conflicts===1?"":"s"} \u2014 run "Resolve conflict" to fix`):this.setStatus(`Pageden: synced (${e.created} created, ${e.pushed} sent, ${e.pulled} received)`)}async loadSettings(){this.settings={...Oo,...await this.loadData()}}async saveSettings(){await this.saveData(this.settings)}api(){return new Fs(this.settings.serverUrl,this.settings.token)}liveBaseUrl(){return`${this.settings.serverUrl.replace(/\/+$/,"")}/api/live`}publicApi(){return new Fs(this.settings.serverUrl,"")}async validateConnection(){try{this.requireConfigured(),await this.api().validate(),new T.Notice("Pageden connection is valid.")}catch(e){new T.Notice(je(e))}}async openRemoteBrowser(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);new su(this.app,e,t=>{this.download(t)}).open()}catch(e){new T.Notice(je(e))}}async openRemoteSearch(){try{this.requireConfigured(),new Zp(this.app,this).open()}catch(e){new T.Notice(je(e))}}async openVaultImport(){try{this.requireConfigured();let e=this.vaultImportFiles(),t=await this.api().tree(this.settings.workspaceId);new em(this.app,this,e,t).open()}catch(e){new T.Notice(je(e))}}async openLiveDocumentPicker(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);new su(this.app,e,t=>{this.openLiveDocument(t)},"Open live").open()}catch(e){new T.Notice(je(e))}}async searchRemote(e){return(await this.api().search(this.settings.workspaceId,e)).results}async downloadSearchResult(e){await this.download({id:e.id,folderId:"",title:e.title,path:e.path,permission:e.permission,version:null,checksum:null})}async startDeviceLogin(){try{if(!this.settings.serverUrl.trim())throw new Error("Set a Pageden server URL first.");let e=await this.publicApi().deviceStart();new tm(this.app,this,e).open()}catch(e){new T.Notice(je(e))}}async pollDeviceLogin(e){let t=await this.publicApi().devicePoll(e);if(t.status==="pending")return"pending";if(t.status==="approved"){this.settings.token=t.token;try{let r=await new Fs(this.settings.serverUrl,t.token).me();if(this.settings.userName=r.user.name,r.workspaces.length===1){let s=r.workspaces[0];this.settings.workspaceId=s.id,this.settings.workspaceName=s.name,await this.saveSettings(),this.startAutoSync(),new T.Notice(`Connected! Signed in as ${r.user.name}, workspace "${s.name}".`)}else r.workspaces.length>1?(await this.saveSettings(),new iu(this.app,this,r.workspaces).open()):(await this.saveSettings(),this.startAutoSync(),new T.Notice(`Connected as ${r.user.name}. No workspaces found \u2014 create one in Pageden first.`))}catch{await this.saveSettings(),this.startAutoSync(),new T.Notice("Login approved. Open Settings \u2192 Pageden to select a workspace.")}return"done"}return t.status==="denied"?new T.Notice("Login was cancelled."):t.status==="expired"?new T.Notice("Login code expired. Please try again."):new T.Notice(`Login ${t.status}.`),"done"}async download(e){try{let t=await tu(this.syncDeps(),e);new T.Notice(`Downloaded ${t.localPath}`)}catch(t){new T.Notice(je(t))}}async openLiveDocument(e){try{if(this.requireConfigured(),e.permission==="viewer"){new T.Notice("Live editing requires editor or manager permission.");return}let t=this.app.workspace.getLeaf("tab");await t.setViewState({type:Xp,active:!0}),t.view instanceof ru&&await t.view.openDocument(e.id)}catch(t){new T.Notice(je(t))}}async pushFile(e){try{this.requireConfigured();let t=await Kp(this.createSyncDeps(),e.path);t.status==="blocked_viewer"?new T.Notice("This remote document is viewer-only, so it cannot be pushed."):t.status==="conflict"?new T.Notice(`Your changes conflict with a newer server version. +`)){let s=r.match(/^title:\s*(.+)$/i);if(s?.[1])return s[1].trim().replace(/^['"]|['"]$/g,"")||null}return null}async function UP(n,e,t,r,s){try{await n.uploadAttachment(e,t,r,s)}catch(i){try{await n.uploadAttachment(e,t,r,s)}catch{throw i}}}function rv(n,e,t,r,s){return{id:n,parentFolderId:e,name:t,slug:r,path:Do(s),permission:"manager"}}function FP(n,e){if(!n.version||!n.checksum)throw new Error("Imported document is missing version metadata.");return{documentId:n.id,localPath:e,remotePath:n.path,title:n.title,baseVersion:n.version,checksum:n.checksum,permission:n.permission,updatedAt:n.updatedAt}}function VP(n){let e=n.split(".").pop()?.toLowerCase();return e==="png"?"image/png":e==="jpg"||e==="jpeg"?"image/jpeg":e==="gif"?"image/gif":e==="webp"?"image/webp":e==="mp4"?"video/mp4":e==="webm"?"video/webm":e==="mov"?"video/quicktime":e==="pdf"?"application/pdf":"application/octet-stream"}function Qp(n){let e=(0,Vs.normalizePath)(n),t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Io(n){return(0,Vs.normalizePath)(n).split("/").filter(Boolean).pop()??""}function Do(n){return n.replace(/^\/+|\/+$/g,"")}var HP=2e3,lv=1500,Zp="pageden-live-document",uv=new To({bulletListMarker:"-",codeBlockStyle:"fenced",headingStyle:"atx"});uv.use(OS);var Po={serverUrl:"https://go.pageden.app",token:"",workspaceId:"",remoteDocsFolder:"Remote Docs",autoSyncEnabled:!1,autoSyncIntervalMinutes:5,userName:"",workspaceName:""},ru=class extends T.Plugin{settings=Po;metaStore;statusBarEl;syncRunner;pushDebouncer;applyingRemoteWrites=new Set;syncIntervalId;lastSummary;async onload(){await this.loadSettings(),this.metaStore=new tu(this.app.vault.adapter,this.pluginDir()),this.addSettingTab(new em(this.app,this)),this.registerView(Zp,e=>new su(e,this)),this.addCommand({id:"validate-connection",name:"Validate connection",callback:()=>{this.validateConnection()}}),this.addCommand({id:"browse-remote-documents",name:"Browse remote documents",callback:()=>{this.openRemoteBrowser()}}),this.addCommand({id:"search-remote-documents",name:"Search remote documents",callback:()=>{this.openRemoteSearch()}}),this.addCommand({id:"import-vault",name:"Import this vault to Pageden",callback:()=>{this.openVaultImport()}}),this.addCommand({id:"open-live-document",name:"Open live document",callback:()=>{this.openLiveDocumentPicker()}}),this.addCommand({id:"device-code-login",name:"Log in with device code",callback:()=>{this.startDeviceLogin()}}),this.addCommand({id:"push-active-document",name:"Push active document",checkCallback:e=>{let t=this.app.workspace.getActiveFile(),r=t instanceof T.TFile&&t.extension==="md";return e?r:(t&&this.pushFile(t),!0)}}),this.addCommand({id:"download-folder",name:"Download a Pageden folder",callback:()=>{this.openFolderDownload()}}),this.addCommand({id:"download-all-documents",name:"Download all Pageden documents",callback:()=>{this.downloadAllDocuments()}}),this.addCommand({id:"resolve-conflict",name:"Resolve conflict for this note",checkCallback:e=>{let t=this.app.workspace.getActiveFile(),r=t instanceof T.TFile&&t.extension==="md"&&!t.path.endsWith(".conflict.md");return e?r:(t&&this.resolveConflict(t),!0)}}),this.statusBarEl=this.addStatusBarItem(),this.syncRunner=tv(()=>this.runSyncPass()),this.pushDebouncer=nv(HP),this.addCommand({id:"sync-now",name:"Sync now",callback:()=>{this.syncRunner.run()}}),this.registerEvent(this.app.vault.on("modify",e=>this.onVaultFileChanged(e))),this.registerEvent(this.app.vault.on("create",e=>this.onVaultFileChanged(e))),this.app.workspace.onLayoutReady(()=>this.startAutoSync())}onunload(){this.stopAutoSync()}startAutoSync(){if(this.stopAutoSync(),!this.settings.autoSyncEnabled){this.setStatusIdle();return}let e=Math.max(1,Math.floor(Number(this.settings.autoSyncIntervalMinutes))||Po.autoSyncIntervalMinutes);this.syncIntervalId=window.setInterval(()=>{this.syncRunner.run()},e*6e4),this.registerInterval(this.syncIntervalId),this.isConfigured()?this.syncRunner.run():this.setStatus("Pageden: not connected")}stopAutoSync(){this.syncIntervalId!==void 0&&(window.clearInterval(this.syncIntervalId),this.syncIntervalId=void 0),this.pushDebouncer?.cancelAll()}isConfigured(){return!!(this.settings.serverUrl.trim()&&this.settings.token.trim()&&this.settings.workspaceId.trim())}async runSyncPass(){if(!(!this.settings.autoSyncEnabled||!this.isConfigured())){this.setStatus("Pageden: syncing\u2026");try{let e=await ZS(this.backgroundSyncDeps());this.lastSummary=e,this.renderSummary(e)}catch{this.setStatus("Pageden: offline")}}}onVaultFileChanged(e){if(!this.settings.autoSyncEnabled||!this.isConfigured()||!(e instanceof T.TFile)||e.extension!=="md")return;let t=e.path;t.endsWith(".conflict.md")||this.applyingRemoteWrites.has(t)||this.pushDebouncer.schedule(t,()=>{this.debouncedPush(t)})}async debouncedPush(e){if(this.syncRunner.isRunning()){this.pushDebouncer.schedule(e,()=>{this.debouncedPush(e)});return}try{let t=await this.metaStore.getByLocalPath(e);if(t?.permission==="viewer"||!t&&!av(this.settings.remoteDocsFolder,e)||await this.app.vault.adapter.exists(Mo(e)))return;let r=ht(await this.app.vault.adapter.read(e));if(t&&await _r(r)===t.checksum)return;let s=await Gp(this.createSyncDeps(),e);s.status==="conflict"?this.setStatus("Pageden: conflict"):(s.status==="pushed"||s.status==="created")&&this.setStatusIdle()}catch{this.setStatus("Pageden: error")}}backgroundSyncDeps(){let e=this.syncDeps();return{...e,vault:this.guardedVault(e.vault),workspaceId:this.settings.workspaceId,localMarkdownPaths:async()=>this.app.vault.getFiles().filter(t=>t.extension==="md"&&av(this.settings.remoteDocsFolder,t.path)).map(t=>t.path)}}guardedVault(e){return{...e,write:async(t,r)=>{this.applyingRemoteWrites.add(t);try{await e.write(t,r)}finally{window.setTimeout(()=>this.applyingRemoteWrites.delete(t),lv)}},writeBinary:e.writeBinary?async(t,r)=>{this.applyingRemoteWrites.add(t);try{await e.writeBinary?.(t,r)}finally{window.setTimeout(()=>this.applyingRemoteWrites.delete(t),lv)}}:void 0}}setStatus(e){this.statusBarEl?.setText(e)}setStatusIdle(){let e=this.lastSummary;e&&e.conflicts?this.setStatus(`Pageden: ${e.conflicts} conflict${e.conflicts===1?"":"s"} \u2014 run "Resolve conflict" to fix`):e&&(e.created||e.pulled||e.pushed)?this.setStatus(`Pageden: synced (${e.created} created, ${e.pushed} sent, ${e.pulled} received)`):this.setStatus("Pageden: up to date")}renderSummary(e){e.errors?this.setStatus("Pageden: sync error \u2014 will retry"):e.conflicts?this.setStatus(`Pageden: ${e.conflicts} conflict${e.conflicts===1?"":"s"} \u2014 run "Resolve conflict" to fix`):this.setStatus(`Pageden: synced (${e.created} created, ${e.pushed} sent, ${e.pulled} received)`)}async loadSettings(){this.settings={...Po,...await this.loadData()}}async saveSettings(){await this.saveData(this.settings)}api(){return new Fs(this.settings.serverUrl,this.settings.token)}liveBaseUrl(){return`${this.settings.serverUrl.replace(/\/+$/,"")}/api/live`}publicApi(){return new Fs(this.settings.serverUrl,"")}async validateConnection(){try{this.requireConfigured(),await this.api().validate(),new T.Notice("Pageden connection is valid.")}catch(e){new T.Notice(je(e))}}async openRemoteBrowser(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);new iu(this.app,e,t=>{this.download(t)}).open()}catch(e){new T.Notice(je(e))}}async openRemoteSearch(){try{this.requireConfigured(),new tm(this.app,this).open()}catch(e){new T.Notice(je(e))}}async openVaultImport(){try{this.requireConfigured();let e=this.vaultImportFiles(),t=await this.api().tree(this.settings.workspaceId);new nm(this.app,this,e,t).open()}catch(e){new T.Notice(je(e))}}async openLiveDocumentPicker(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);new iu(this.app,e,t=>{this.openLiveDocument(t)},"Open live").open()}catch(e){new T.Notice(je(e))}}async searchRemote(e){return(await this.api().search(this.settings.workspaceId,e)).results}async downloadSearchResult(e){await this.download({id:e.id,folderId:"",title:e.title,path:e.path,permission:e.permission,version:null,checksum:null})}async startDeviceLogin(){try{if(!this.settings.serverUrl.trim())throw new Error("Set a Pageden server URL first.");let e=await this.publicApi().deviceStart();new rm(this.app,this,e).open()}catch(e){new T.Notice(je(e))}}async pollDeviceLogin(e){let t=await this.publicApi().devicePoll(e);if(t.status==="pending")return"pending";if(t.status==="approved"){this.settings.token=t.token;try{let r=await new Fs(this.settings.serverUrl,t.token).me();if(this.settings.userName=r.user.name,r.workspaces.length===1){let s=r.workspaces[0];this.settings.workspaceId=s.id,this.settings.workspaceName=s.name,await this.saveSettings(),this.startAutoSync(),new T.Notice(`Connected! Signed in as ${r.user.name}, workspace "${s.name}".`)}else r.workspaces.length>1?(await this.saveSettings(),new ou(this.app,this,r.workspaces).open()):(await this.saveSettings(),this.startAutoSync(),new T.Notice(`Connected as ${r.user.name}. No workspaces found \u2014 create one in Pageden first.`))}catch{await this.saveSettings(),this.startAutoSync(),new T.Notice("Login approved. Open Settings \u2192 Pageden to select a workspace.")}return"done"}return t.status==="denied"?new T.Notice("Login was cancelled."):t.status==="expired"?new T.Notice("Login code expired. Please try again."):new T.Notice(`Login ${t.status}.`),"done"}async download(e){try{let t=await nu(this.syncDeps(),e);new T.Notice(`Downloaded ${t.localPath}`)}catch(t){new T.Notice(je(t))}}async openLiveDocument(e){try{if(this.requireConfigured(),e.permission==="viewer"){new T.Notice("Live editing requires editor or manager permission.");return}let t=this.app.workspace.getLeaf("tab");await t.setViewState({type:Zp,active:!0}),t.view instanceof su&&await t.view.openDocument(e.id)}catch(t){new T.Notice(je(t))}}async pushFile(e){try{this.requireConfigured();let t=await Gp(this.createSyncDeps(),e.path);t.status==="blocked_viewer"?new T.Notice("This remote document is viewer-only, so it cannot be pushed."):t.status==="conflict"?new T.Notice(`Your changes conflict with a newer server version. The server version was saved as "${t.conflictPath}". -Use the "Resolve conflict for this note" command to dismiss it.`,8e3):new T.Notice(t.status==="created"?"Created in Pageden.":"Pushed to Pageden.")}catch(t){new T.Notice(je(t))}}async importVault(e,t,r){return this.requireConfigured(),e1({api:this.api(),vault:this.vaultAdapter(),meta:this.metaStore,workspaceId:this.settings.workspaceId,files:e,targetRootName:t,onProgress:r})}async openFolderDownload(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);new nm(this.app,this,e).open()}catch(e){new T.Notice(je(e))}}async downloadFolderDocuments(e,t,r){try{let s=r.documents.filter(l=>l.folderId===e);if(s.length===0){new T.Notice(`No documents found in "${t}".`);return}new T.Notice(`Downloading ${s.length} note${s.length===1?"":"s"} from "${t}"\u2026`,3e3);let i=0,o=0;for(let l of s)try{await tu(this.syncDeps(),l),i++}catch{o++}new T.Notice(o>0?`Downloaded ${i} of ${s.length} notes from "${t}". ${o} failed.`:`Downloaded ${i} note${i===1?"":"s"} from "${t}".`)}catch(s){new T.Notice(je(s))}}async downloadAllDocuments(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);if(e.documents.length===0){new T.Notice("No documents found in your Pageden workspace.");return}new T.Notice(`Downloading ${e.documents.length} note${e.documents.length===1?"":"s"}\u2026`,3e3);let t=0,r=0;for(let s of e.documents)try{await tu(this.syncDeps(),s),t++}catch{r++}new T.Notice(r>0?`Downloaded ${t} of ${e.documents.length} notes. ${r} failed.`:`Downloaded all ${t} note${t===1?"":"s"}.`)}catch(e){new T.Notice(je(e))}}async resolveConflict(e){let t=Eo(e.path);if(!await this.app.vault.adapter.exists(t)){new T.Notice("No conflict file found for this note.");return}await this.app.vault.adapter.remove(t),new T.Notice("Conflict resolved \u2014 the server copy has been removed.")}syncDeps(){return{api:this.api(),vault:this.vaultAdapter(),meta:this.metaStore,remoteDocsFolder:this.settings.remoteDocsFolder}}createSyncDeps(){return{...this.syncDeps(),workspaceId:this.settings.workspaceId}}vaultAdapter(){let e=this.app.vault.adapter;return{read:t=>e.read(t),write:(t,r)=>e.write(t,r),readBinary:t=>e.readBinary(t),writeBinary:(t,r)=>e.writeBinary(t,r),exists:t=>e.exists(t),mkdir:t=>e.mkdir(t)}}vaultImportFiles(){return this.app.vault.getFiles().map(e=>({path:e.path,name:e.name,extension:e.extension}))}pluginDir(){return this.manifest.dir??`.obsidian/plugins/${this.manifest.id}`}requireConfigured(){if(!this.settings.serverUrl.trim())throw new Error("Please set your Pageden server URL in settings.");if(!this.settings.token.trim())throw new Error('Please connect to Pageden first. Open Settings \u2192 Pageden and click "Connect to Pageden".');if(!this.settings.workspaceId.trim())throw new Error('Please select a workspace. Open Settings \u2192 Pageden and click "Connect to Pageden".')}},ru=class extends T.ItemView{constructor(t,r){super(t);this.plugin=r}plugin;editor;provider;ydoc;documentId;baseVersion="";lastSavedMarkdown="";statusEl;titleEl;pathEl;saveTimer;saving=!1;saveAgain=!1;getViewType(){return Xp}getDisplayText(){return this.titleEl?.getText()||"Pageden live document"}async openDocument(t){this.destroyLiveSession(),this.documentId=t,this.contentEl.empty(),this.contentEl.addClass("pageden-live-view");let r=this.contentEl.createDiv({cls:"pageden-live-header"}),s=r.createDiv();this.titleEl=s.createEl("h2",{text:"Loading..."}),this.pathEl=s.createEl("p",{text:"Connecting to Pageden"}),this.statusEl=r.createEl("span",{text:"Connecting",cls:"pageden-live-status"});let i=this.contentEl.createDiv({cls:"pageden-live-toolbar"}),o=this.contentEl.createDiv({cls:"pageden-live-editor"}),l=await this.plugin.api().document(t);if(l.permission==="viewer")throw new Error("Live editing requires editor or manager permission.");this.baseVersion=l.version??"",this.lastSavedMarkdown=l.content,this.titleEl.setText(l.title),this.pathEl.setText(l.path),this.ydoc=new qt,this.provider=new Zc(this.plugin.liveBaseUrl(),t,this.ydoc,{params:{token:this.plugin.settings.token},connect:!0,disableBc:!0}),this.editor=new hw({element:o,extensions:[Y0.configure({link:!1,undoRedo:!1}),fx.configure({document:this.ydoc}),w0.configure({autolink:!0,openOnClick:!1,protocols:["http","https","mailto"]}),px.configure({placeholder:"Start writing..."}),mx,gx.configure({nested:!0}),mp.configure({resizable:!0}),Kx,Yx,Gx],editorProps:{attributes:{class:"pageden-live-prosemirror"}},onUpdate:({editor:a})=>{i1(a.getHTML())!==this.lastSavedMarkdown&&this.scheduleSave()}}),this.renderToolbar(i),this.provider.on("status",a=>this.setStatus(a.status==="connected"?"Live":"Reconnecting")),this.provider.on("sync",a=>{a&&this.seedInitialContent(l.content)}),this.provider.synced&&this.seedInitialContent(l.content)}async onClose(){this.destroyLiveSession()}renderToolbar(t){let r=[["B",()=>this.editor?.chain().focus().toggleBold().run()],["I",()=>this.editor?.chain().focus().toggleItalic().run()],["H1",()=>this.editor?.chain().focus().toggleHeading({level:1}).run()],["H2",()=>this.editor?.chain().focus().toggleHeading({level:2}).run()],["List",()=>this.editor?.chain().focus().toggleBulletList().run()],["Task",()=>this.editor?.chain().focus().toggleTaskList().run()],["Save",()=>{this.persist()}]];for(let[s,i]of r)t.createEl("button",{text:s,cls:"pageden-live-button"}).addEventListener("click",i)}seedInitialContent(t){!this.editor||this.editor.getText().trim()||this.editor.commands.setContent(UP(t),{emitUpdate:!0})}scheduleSave(){if(this.saving){this.saveAgain=!0;return}this.saveTimer!==void 0&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.persist()},1500)}async persist(){if(!this.editor||!this.documentId)return;if(this.saving){this.saveAgain=!0;return}this.saveTimer!==void 0&&(window.clearTimeout(this.saveTimer),this.saveTimer=void 0);let t=i1(this.editor.getHTML());if(t!==this.lastSavedMarkdown){this.saving=!0,this.setStatus("Saving");try{let r=await this.plugin.api().push(this.documentId,{baseVersion:this.baseVersion,checksum:await Lr(t),content:t});this.baseVersion=r.version,this.lastSavedMarkdown=t,this.setStatus("Saved")}catch(r){if(r instanceof bn&&r.status===409&&r.currentVersion){this.baseVersion=r.currentVersion,this.saving=!1,await this.persist();return}throw this.setStatus("Save failed"),r}finally{this.saving=!1,this.saveAgain&&(this.saveAgain=!1,this.scheduleSave())}}}setStatus(t){this.statusEl?.setText(t)}destroyLiveSession(){this.saveTimer!==void 0&&(window.clearTimeout(this.saveTimer),this.saveTimer=void 0),this.editor?.destroy(),this.provider?.destroy(),this.ydoc?.destroy(),this.editor=void 0,this.provider=void 0,this.ydoc=void 0,this.saveAgain=!1}},Qp=class extends T.PluginSettingTab{constructor(t,r){super(t,r);this.plugin=r}plugin;display(){let{containerEl:t}=this;if(t.empty(),t.createEl("h2",{text:"Pageden"}),!this.plugin.isConfigured())t.createEl("p",{text:"Connect your Obsidian vault to Pageden to sync notes and collaborate with your team.",cls:"setting-item-description"}),new T.Setting(t).setName("Connect your vault").setDesc("Click the button below. A login page will open in your browser \u2014 approve it there and you're done.").addButton(s=>s.setButtonText("Connect to Pageden").setCta().onClick(()=>{this.plugin.startDeviceLogin()})),t.createEl("h3",{text:"Server"}),new T.Setting(t).setName("Server URL").setDesc("The address of your Pageden server.").addText(s=>s.setPlaceholder("https://app.example.com").setValue(this.plugin.settings.serverUrl).onChange(async i=>{this.plugin.settings.serverUrl=i.trim(),await this.plugin.saveSettings()}));else{let s=this.plugin.settings.userName||"your account",i=this.plugin.settings.workspaceName||this.plugin.settings.workspaceId;new T.Setting(t).setName(`Signed in as ${s}`).setDesc(`Workspace: ${i}`).addButton(a=>a.setButtonText("Change workspace").onClick(()=>{this.changeWorkspace()})).addButton(a=>a.setButtonText("Disconnect").onClick(async()=>{this.plugin.settings.token="",this.plugin.settings.workspaceId="",this.plugin.settings.userName="",this.plugin.settings.workspaceName="",await this.plugin.saveSettings(),this.plugin.startAutoSync(),this.display()})),t.createEl("h3",{text:"Sync"}),new T.Setting(t).setName("Background sync").setDesc("Automatically pull remote updates and push local edits.").addToggle(a=>a.setValue(this.plugin.settings.autoSyncEnabled).onChange(async c=>{this.plugin.settings.autoSyncEnabled=c,await this.plugin.saveSettings(),this.plugin.startAutoSync()})),new T.Setting(t).setName("Sync interval (minutes)").setDesc("How often background sync runs. Minimum 1 minute.").addText(a=>a.setPlaceholder("5").setValue(String(this.plugin.settings.autoSyncIntervalMinutes)).onChange(async c=>{let u=Math.max(1,Math.floor(Number(c))||Oo.autoSyncIntervalMinutes);this.plugin.settings.autoSyncIntervalMinutes=u,await this.plugin.saveSettings(),this.plugin.startAutoSync()})),new T.Setting(t).setName("Local folder").setDesc("Folder in your vault where downloaded documents are stored.").addText(a=>a.setPlaceholder("Remote Docs").setValue(this.plugin.settings.remoteDocsFolder).onChange(async c=>{this.plugin.settings.remoteDocsFolder=(0,T.normalizePath)(c.trim()||Oo.remoteDocsFolder),await this.plugin.saveSettings()}));let o=t.createEl("details");o.createEl("summary",{text:"Advanced"});let l=o.createDiv();new T.Setting(l).setName("Server URL").addText(a=>a.setPlaceholder("https://app.example.com").setValue(this.plugin.settings.serverUrl).onChange(async c=>{this.plugin.settings.serverUrl=c.trim(),await this.plugin.saveSettings(),this.plugin.startAutoSync()})),new T.Setting(l).setName("Connection").addButton(a=>a.setButtonText("Test connection").onClick(()=>{this.plugin.validateConnection()})).addButton(a=>a.setButtonText("Sign in again").onClick(()=>{this.plugin.startDeviceLogin()}))}}async changeWorkspace(){try{let t=await this.plugin.api().me();if(t.workspaces.length===0){new T.Notice("No workspaces found on this account.");return}new iu(this.app,this.plugin,t.workspaces,()=>this.display()).open()}catch(t){new T.Notice(je(t))}}},su=class extends T.Modal{constructor(t,r,s,i="Download"){super(t);this.tree=r;this.onPick=s;this.buttonText=i}tree;onPick;buttonText;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Pageden documents"});let r=this.tree.documents.filter(s=>s.permission!=="viewer"||s.version);if(r.length===0){t.createEl("p",{text:"No remote documents are available."});return}for(let s of r)new T.Setting(t).setName(s.title).setDesc(s.permission==="viewer"?`${s.path} \xB7 read only`:s.path).addButton(i=>i.setButtonText(this.buttonText).onClick(()=>{this.close(),this.onPick(s)}))}},Zp=class extends T.Modal{constructor(t,r){super(t);this.plugin=r}plugin;query="";resultsEl;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Search Pageden"}),new T.Setting(t).setName("Query").addText(r=>r.setPlaceholder("Search remote documents").onChange(s=>{this.query=s})).addButton(r=>r.setButtonText("Search").onClick(()=>{this.runSearch()})),this.resultsEl=t.createDiv()}async runSearch(){if(!this.resultsEl)return;this.resultsEl.empty();let t=this.query.trim();if(!t){this.resultsEl.createEl("p",{text:"Enter a search query."});return}try{let r=await this.plugin.searchRemote(t);if(r.length===0){this.resultsEl.createEl("p",{text:"No results."});return}for(let s of r)new T.Setting(this.resultsEl).setName(s.title).setDesc(s.permission==="viewer"?`${s.path} \xB7 read only`:s.path).addButton(i=>i.setButtonText("Download").onClick(()=>{this.close(),this.plugin.downloadSearchResult(s)}))}catch(r){this.resultsEl.createEl("p",{text:je(r)})}}},em=class extends T.Modal{constructor(t,r,s,i){super(t);this.plugin=r;this.files=s;this.remoteTree=i}plugin;files;remoteTree;targetRootName="Imported from Obsidian";previewEl;statusEl;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Import Obsidian vault"}),t.createEl("p",{text:"Upload this vault's notes into Pageden. Existing remote documents are skipped, never overwritten."}),new T.Setting(t).setName("Pageden folder").setDesc("Imported folders and notes will be created under this top-level folder.").addText(r=>r.setPlaceholder("Imported from Obsidian").setValue(this.targetRootName).onChange(s=>{this.targetRootName=s.trim()||"Imported from Obsidian",this.renderPreview()})),this.previewEl=t.createDiv(),this.statusEl=t.createEl("p"),this.renderPreview(),new T.Setting(t).addButton(r=>r.setButtonText("Import vault").setCta().onClick(async()=>{r.setDisabled(!0).setButtonText("Importing..."),await this.runImport(),r.setDisabled(!1).setButtonText("Import vault")})).addButton(r=>r.setButtonText("Cancel").onClick(()=>this.close()))}renderPreview(){if(!this.previewEl)return;this.previewEl.empty();let t=Yp(this.files,this.remoteTree,this.targetRootName);this.previewEl.createEl("h3",{text:"Preview"});let r=this.previewEl.createEl("ul");r.createEl("li",{text:`${t.notes} Markdown note${t.notes===1?"":"s"} ready to import.`}),r.createEl("li",{text:`${t.attachments} attachment${t.attachments===1?"":"s"} detected.`}),r.createEl("li",{text:`${t.skipped} internal or unsupported file${t.skipped===1?"":"s"} skipped.`}),t.conflicts.length&&r.createEl("li",{text:`${t.conflicts.length} remote document${t.conflicts.length===1?"":"s"} already exist and will be skipped.`}),this.statusEl?.setText("")}async runImport(){try{this.statusEl?.setText("Starting import\u2026");let t=await this.plugin.importVault(this.files,this.targetRootName,(s,i)=>{this.statusEl?.setText(`Importing note ${s} of ${i}\u2026`)}),r=t.attachmentWarnings.length?` ${t.attachmentWarnings.length} attachment warning${t.attachmentWarnings.length===1?"":"s"}.`:"";this.statusEl?.setText(`Done! Created ${t.foldersCreated} folder${t.foldersCreated===1?"":"s"}, imported ${t.documentsCreated} note${t.documentsCreated===1?"":"s"}, uploaded ${t.attachmentsUploaded} attachment${t.attachmentsUploaded===1?"":"s"}.${r}`),new T.Notice("Vault import complete.")}catch(t){let r=je(t);this.statusEl?.setText(r),new T.Notice(r)}}},tm=class extends T.Modal{constructor(t,r,s){super(t);this.plugin=r;this.request=s}plugin;request;intervalId;statusEl;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Connect to Pageden"}),t.createEl("p",{text:"A login page should have opened in your browser. Enter this code there to approve the connection:"}),t.createEl("h3",{text:this.request.userCode,cls:"pageden-device-code"}),t.createEl("p",{text:"If the browser did not open automatically, use the button below.",cls:"setting-item-description"}),new T.Setting(t).addButton(s=>s.setButtonText("Open browser").onClick(()=>window.open(this.request.verificationUri))).addButton(s=>s.setButtonText("Copy code").onClick(()=>{navigator.clipboard?.writeText(this.request.userCode)})).addButton(s=>s.setButtonText("Check now").onClick(()=>{this.poll()})),this.statusEl=t.createEl("p",{text:"Waiting for you to approve in the browser\u2026"});let r=Math.max(1,this.request.interval)*1e3;this.intervalId=window.setInterval(()=>{this.poll()},r),window.open(this.request.verificationUri)}onClose(){this.intervalId!==void 0&&(window.clearInterval(this.intervalId),this.intervalId=void 0)}async poll(){try{await this.plugin.pollDeviceLogin(this.request.deviceCode)==="pending"?this.statusEl?.setText("Waiting for approval..."):this.close()}catch(t){this.statusEl?.setText(je(t))}}},iu=class extends T.Modal{constructor(t,r,s,i){super(t);this.plugin=r;this.workspaces=s;this.onSelect=i}plugin;workspaces;onSelect;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Choose a workspace"}),t.createEl("p",{text:"Select which Pageden workspace to sync with this vault.",cls:"setting-item-description"});for(let r of this.workspaces)new T.Setting(t).setName(r.name).setDesc(r.role==="admin"?"You are an admin":"Member").addButton(s=>s.setButtonText("Select").setCta().onClick(async()=>{this.plugin.settings.workspaceId=r.id,this.plugin.settings.workspaceName=r.name,await this.plugin.saveSettings(),this.plugin.startAutoSync(),this.close(),new T.Notice(`Workspace set to "${r.name}".`),this.onSelect?.()}))}},nm=class extends T.Modal{constructor(t,r,s){super(t);this.plugin=r;this.tree=s}plugin;tree;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Download a folder"}),t.createEl("p",{text:"Choose a folder to download all its notes to your vault.",cls:"setting-item-description"});let r=this.tree.folders.map(s=>({folder:s,count:this.tree.documents.filter(i=>i.folderId===s.id).length})).filter(({count:s})=>s>0).sort((s,i)=>s.folder.path.localeCompare(i.folder.path));if(r.length===0){t.createEl("p",{text:"No folders with documents found in your workspace."});return}for(let{folder:s,count:i}of r)new T.Setting(t).setName(s.name).setDesc(`${s.path} \xB7 ${i} note${i===1?"":"s"}`).addButton(o=>o.setButtonText("Download all").onClick(()=>{this.close(),this.plugin.downloadFolderDocuments(s.id,s.name,this.tree)}))}};function je(n){return n instanceof Error?n.message:"Pageden request failed."}function s1(n,e){let t=(0,T.normalizePath)(n).replace(/\/+$/,""),r=(0,T.normalizePath)(e);return r===t||r.startsWith(`${t}/`)}function UP(n){return J.parse(n,{async:!1})}function i1(n){let e=o1.turndown(n).trimEnd();return e?`${e} +Use the "Resolve conflict for this note" command to dismiss it.`,8e3):new T.Notice(t.status==="created"?"Created in Pageden.":"Pushed to Pageden.")}catch(t){new T.Notice(je(t))}}async importVault(e,t,r){return this.requireConfigured(),sv({api:this.api(),vault:this.vaultAdapter(),meta:this.metaStore,workspaceId:this.settings.workspaceId,files:e,targetRootName:t,onProgress:r})}async openFolderDownload(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);new sm(this.app,this,e).open()}catch(e){new T.Notice(je(e))}}async downloadFolderDocuments(e,t,r){try{let s=r.documents.filter(l=>l.folderId===e);if(s.length===0){new T.Notice(`No documents found in "${t}".`);return}new T.Notice(`Downloading ${s.length} note${s.length===1?"":"s"} from "${t}"\u2026`,3e3);let i=0,o=0;for(let l of s)try{await nu(this.syncDeps(),l),i++}catch{o++}new T.Notice(o>0?`Downloaded ${i} of ${s.length} notes from "${t}". ${o} failed.`:`Downloaded ${i} note${i===1?"":"s"} from "${t}".`)}catch(s){new T.Notice(je(s))}}async downloadAllDocuments(){try{this.requireConfigured();let e=await this.api().tree(this.settings.workspaceId);if(e.documents.length===0){new T.Notice("No documents found in your Pageden workspace.");return}new T.Notice(`Downloading ${e.documents.length} note${e.documents.length===1?"":"s"}\u2026`,3e3);let t=0,r=0;for(let s of e.documents)try{await nu(this.syncDeps(),s),t++}catch{r++}new T.Notice(r>0?`Downloaded ${t} of ${e.documents.length} notes. ${r} failed.`:`Downloaded all ${t} note${t===1?"":"s"}.`)}catch(e){new T.Notice(je(e))}}async resolveConflict(e){let t=Mo(e.path);if(!await this.app.vault.adapter.exists(t)){new T.Notice("No conflict file found for this note.");return}await this.app.vault.adapter.remove(t),new T.Notice("Conflict resolved \u2014 the server copy has been removed.")}syncDeps(){return{api:this.api(),vault:this.vaultAdapter(),meta:this.metaStore,remoteDocsFolder:this.settings.remoteDocsFolder}}createSyncDeps(){return{...this.syncDeps(),workspaceId:this.settings.workspaceId}}vaultAdapter(){let e=this.app.vault.adapter;return{read:t=>e.read(t),write:(t,r)=>e.write(t,r),readBinary:t=>e.readBinary(t),writeBinary:(t,r)=>e.writeBinary(t,r),exists:t=>e.exists(t),mkdir:t=>e.mkdir(t)}}vaultImportFiles(){return this.app.vault.getFiles().map(e=>({path:e.path,name:e.name,extension:e.extension}))}pluginDir(){return this.manifest.dir??`.obsidian/plugins/${this.manifest.id}`}requireConfigured(){if(!this.settings.serverUrl.trim())throw new Error("Please set your Pageden server URL in settings.");if(!this.settings.token.trim())throw new Error('Please connect to Pageden first. Open Settings \u2192 Pageden and click "Connect to Pageden".');if(!this.settings.workspaceId.trim())throw new Error('Please select a workspace. Open Settings \u2192 Pageden and click "Connect to Pageden".')}},su=class extends T.ItemView{constructor(t,r){super(t);this.plugin=r}plugin;editor;provider;ydoc;documentId;baseVersion="";lastSavedMarkdown="";statusEl;titleEl;pathEl;saveTimer;saving=!1;saveAgain=!1;getViewType(){return Zp}getDisplayText(){return this.titleEl?.getText()||"Pageden live document"}async openDocument(t){this.destroyLiveSession(),this.documentId=t,this.contentEl.empty(),this.contentEl.addClass("pageden-live-view");let r=this.contentEl.createDiv({cls:"pageden-live-header"}),s=r.createDiv();this.titleEl=s.createEl("h2",{text:"Loading..."}),this.pathEl=s.createEl("p",{text:"Connecting to Pageden"}),this.statusEl=r.createEl("span",{text:"Connecting",cls:"pageden-live-status"});let i=this.contentEl.createDiv({cls:"pageden-live-toolbar"}),o=this.contentEl.createDiv({cls:"pageden-live-editor"}),l=await this.plugin.api().document(t);if(l.permission==="viewer")throw new Error("Live editing requires editor or manager permission.");this.baseVersion=l.version??"",this.lastSavedMarkdown=l.content,this.titleEl.setText(l.title),this.pathEl.setText(l.path),this.ydoc=new qt,this.provider=new eu(this.plugin.liveBaseUrl(),t,this.ydoc,{params:{token:this.plugin.settings.token},connect:!0,disableBc:!0}),this.editor=new gw({element:o,extensions:[Z0.configure({link:!1,undoRedo:!1}),yx.configure({document:this.ydoc}),S0.configure({autolink:!0,openOnClick:!1,protocols:["http","https","mailto"]}),wx.configure({placeholder:"Start writing..."}),kx,bx.configure({nested:!0}),yp.configure({resizable:!0}),Qx,Zx,eS],editorProps:{attributes:{class:"pageden-live-prosemirror"}},onUpdate:({editor:a})=>{cv(a.getHTML())!==this.lastSavedMarkdown&&this.scheduleSave()}}),this.renderToolbar(i),this.provider.on("status",a=>this.setStatus(a.status==="connected"?"Live":"Reconnecting")),this.provider.on("sync",a=>{a&&this.seedInitialContent(l.content)}),this.provider.synced&&this.seedInitialContent(l.content)}async onClose(){this.destroyLiveSession()}renderToolbar(t){let r=[["B",()=>this.editor?.chain().focus().toggleBold().run()],["I",()=>this.editor?.chain().focus().toggleItalic().run()],["H1",()=>this.editor?.chain().focus().toggleHeading({level:1}).run()],["H2",()=>this.editor?.chain().focus().toggleHeading({level:2}).run()],["List",()=>this.editor?.chain().focus().toggleBulletList().run()],["Task",()=>this.editor?.chain().focus().toggleTaskList().run()],["Save",()=>{this.persist()}]];for(let[s,i]of r)t.createEl("button",{text:s,cls:"pageden-live-button"}).addEventListener("click",i)}seedInitialContent(t){!this.editor||this.editor.getText().trim()||this.editor.commands.setContent(WP(t),{emitUpdate:!0})}scheduleSave(){if(this.saving){this.saveAgain=!0;return}this.saveTimer!==void 0&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.persist()},1500)}async persist(){if(!this.editor||!this.documentId)return;if(this.saving){this.saveAgain=!0;return}this.saveTimer!==void 0&&(window.clearTimeout(this.saveTimer),this.saveTimer=void 0);let t=cv(this.editor.getHTML());if(t!==this.lastSavedMarkdown){this.saving=!0,this.setStatus("Saving");try{let r=await this.plugin.api().push(this.documentId,{baseVersion:this.baseVersion,checksum:await _r(t),content:t});this.baseVersion=r.version,this.lastSavedMarkdown=t,this.setStatus("Saved")}catch(r){if(r instanceof xn&&r.status===409&&r.currentVersion){this.baseVersion=r.currentVersion,this.saving=!1,await this.persist();return}throw this.setStatus("Save failed"),r}finally{this.saving=!1,this.saveAgain&&(this.saveAgain=!1,this.scheduleSave())}}}setStatus(t){this.statusEl?.setText(t)}destroyLiveSession(){this.saveTimer!==void 0&&(window.clearTimeout(this.saveTimer),this.saveTimer=void 0),this.editor?.destroy(),this.provider?.destroy(),this.ydoc?.destroy(),this.editor=void 0,this.provider=void 0,this.ydoc=void 0,this.saveAgain=!1}},em=class extends T.PluginSettingTab{constructor(t,r){super(t,r);this.plugin=r}plugin;display(){let{containerEl:t}=this;if(t.empty(),t.createEl("h2",{text:"Pageden"}),!this.plugin.isConfigured())t.createEl("p",{text:"Connect your Obsidian vault to Pageden to sync notes and collaborate with your team.",cls:"setting-item-description"}),new T.Setting(t).setName("Connect your vault").setDesc("Click the button below. A login page will open in your browser \u2014 approve it there and you're done.").addButton(s=>s.setButtonText("Connect to Pageden").setCta().onClick(()=>{this.plugin.startDeviceLogin()})),t.createEl("h3",{text:"Server"}),new T.Setting(t).setName("Server URL").setDesc("The address of your Pageden server.").addText(s=>s.setPlaceholder("https://app.example.com").setValue(this.plugin.settings.serverUrl).onChange(async i=>{this.plugin.settings.serverUrl=i.trim(),await this.plugin.saveSettings()}));else{let s=this.plugin.settings.userName||"your account",i=this.plugin.settings.workspaceName||this.plugin.settings.workspaceId;new T.Setting(t).setName(`Signed in as ${s}`).setDesc(`Workspace: ${i}`).addButton(a=>a.setButtonText("Change workspace").onClick(()=>{this.changeWorkspace()})).addButton(a=>a.setButtonText("Disconnect").onClick(async()=>{this.plugin.settings.token="",this.plugin.settings.workspaceId="",this.plugin.settings.userName="",this.plugin.settings.workspaceName="",await this.plugin.saveSettings(),this.plugin.startAutoSync(),this.display()})),t.createEl("h3",{text:"Sync"}),new T.Setting(t).setName("Background sync").setDesc("Automatically pull remote updates and push local edits.").addToggle(a=>a.setValue(this.plugin.settings.autoSyncEnabled).onChange(async c=>{this.plugin.settings.autoSyncEnabled=c,await this.plugin.saveSettings(),this.plugin.startAutoSync()})),new T.Setting(t).setName("Sync interval (minutes)").setDesc("How often background sync runs. Minimum 1 minute.").addText(a=>a.setPlaceholder("5").setValue(String(this.plugin.settings.autoSyncIntervalMinutes)).onChange(async c=>{let u=Math.max(1,Math.floor(Number(c))||Po.autoSyncIntervalMinutes);this.plugin.settings.autoSyncIntervalMinutes=u,await this.plugin.saveSettings(),this.plugin.startAutoSync()})),new T.Setting(t).setName("Local folder").setDesc("Folder in your vault where downloaded documents are stored.").addText(a=>a.setPlaceholder("Remote Docs").setValue(this.plugin.settings.remoteDocsFolder).onChange(async c=>{this.plugin.settings.remoteDocsFolder=(0,T.normalizePath)(c.trim()||Po.remoteDocsFolder),await this.plugin.saveSettings()}));let o=t.createEl("details");o.createEl("summary",{text:"Advanced"});let l=o.createDiv();new T.Setting(l).setName("Server URL").addText(a=>a.setPlaceholder("https://app.example.com").setValue(this.plugin.settings.serverUrl).onChange(async c=>{this.plugin.settings.serverUrl=c.trim(),await this.plugin.saveSettings(),this.plugin.startAutoSync()})),new T.Setting(l).setName("Connection").addButton(a=>a.setButtonText("Test connection").onClick(()=>{this.plugin.validateConnection()})).addButton(a=>a.setButtonText("Sign in again").onClick(()=>{this.plugin.startDeviceLogin()}))}}async changeWorkspace(){try{let t=await this.plugin.api().me();if(t.workspaces.length===0){new T.Notice("No workspaces found on this account.");return}new ou(this.app,this.plugin,t.workspaces,()=>this.display()).open()}catch(t){new T.Notice(je(t))}}},iu=class extends T.Modal{constructor(t,r,s,i="Download"){super(t);this.tree=r;this.onPick=s;this.buttonText=i}tree;onPick;buttonText;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Pageden documents"});let r=this.tree.documents.filter(s=>s.permission!=="viewer"||s.version);if(r.length===0){t.createEl("p",{text:"No remote documents are available."});return}for(let s of r)new T.Setting(t).setName(s.title).setDesc(s.permission==="viewer"?`${s.path} \xB7 read only`:s.path).addButton(i=>i.setButtonText(this.buttonText).onClick(()=>{this.close(),this.onPick(s)}))}},tm=class extends T.Modal{constructor(t,r){super(t);this.plugin=r}plugin;query="";resultsEl;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Search Pageden"}),new T.Setting(t).setName("Query").addText(r=>r.setPlaceholder("Search remote documents").onChange(s=>{this.query=s})).addButton(r=>r.setButtonText("Search").onClick(()=>{this.runSearch()})),this.resultsEl=t.createDiv()}async runSearch(){if(!this.resultsEl)return;this.resultsEl.empty();let t=this.query.trim();if(!t){this.resultsEl.createEl("p",{text:"Enter a search query."});return}try{let r=await this.plugin.searchRemote(t);if(r.length===0){this.resultsEl.createEl("p",{text:"No results."});return}for(let s of r)new T.Setting(this.resultsEl).setName(s.title).setDesc(s.permission==="viewer"?`${s.path} \xB7 read only`:s.path).addButton(i=>i.setButtonText("Download").onClick(()=>{this.close(),this.plugin.downloadSearchResult(s)}))}catch(r){this.resultsEl.createEl("p",{text:je(r)})}}},nm=class extends T.Modal{constructor(t,r,s,i){super(t);this.plugin=r;this.files=s;this.remoteTree=i}plugin;files;remoteTree;targetRootName="Imported from Obsidian";previewEl;statusEl;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Import Obsidian vault"}),t.createEl("p",{text:"Upload this vault's notes into Pageden. Existing remote documents are skipped, never overwritten."}),new T.Setting(t).setName("Pageden folder").setDesc("Imported folders and notes will be created under this top-level folder.").addText(r=>r.setPlaceholder("Imported from Obsidian").setValue(this.targetRootName).onChange(s=>{this.targetRootName=s.trim()||"Imported from Obsidian",this.renderPreview()})),this.previewEl=t.createDiv(),this.statusEl=t.createEl("p"),this.renderPreview(),new T.Setting(t).addButton(r=>r.setButtonText("Import vault").setCta().onClick(async()=>{r.setDisabled(!0).setButtonText("Importing..."),await this.runImport(),r.setDisabled(!1).setButtonText("Import vault")})).addButton(r=>r.setButtonText("Cancel").onClick(()=>this.close()))}renderPreview(){if(!this.previewEl)return;this.previewEl.empty();let t=Xp(this.files,this.remoteTree,this.targetRootName);this.previewEl.createEl("h3",{text:"Preview"});let r=this.previewEl.createEl("ul");r.createEl("li",{text:`${t.notes} Markdown note${t.notes===1?"":"s"} ready to import.`}),r.createEl("li",{text:`${t.attachments} attachment${t.attachments===1?"":"s"} detected.`}),r.createEl("li",{text:`${t.skipped} internal or unsupported file${t.skipped===1?"":"s"} skipped.`}),t.conflicts.length&&r.createEl("li",{text:`${t.conflicts.length} remote document${t.conflicts.length===1?"":"s"} already exist and will be skipped.`}),this.statusEl?.setText("")}async runImport(){try{this.statusEl?.setText("Starting import\u2026");let t=await this.plugin.importVault(this.files,this.targetRootName,(s,i)=>{this.statusEl?.setText(`Importing note ${s} of ${i}\u2026`)}),r=t.attachmentWarnings.length?` ${t.attachmentWarnings.length} attachment warning${t.attachmentWarnings.length===1?"":"s"}.`:"";this.statusEl?.setText(`Done! Created ${t.foldersCreated} folder${t.foldersCreated===1?"":"s"}, imported ${t.documentsCreated} note${t.documentsCreated===1?"":"s"}, uploaded ${t.attachmentsUploaded} attachment${t.attachmentsUploaded===1?"":"s"}.${r}`),new T.Notice("Vault import complete.")}catch(t){let r=je(t);this.statusEl?.setText(r),new T.Notice(r)}}},rm=class extends T.Modal{constructor(t,r,s){super(t);this.plugin=r;this.request=s}plugin;request;intervalId;statusEl;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Connect to Pageden"}),t.createEl("p",{text:"A login page should have opened in your browser. Enter this code there to approve the connection:"}),t.createEl("h3",{text:this.request.userCode,cls:"pageden-device-code"}),t.createEl("p",{text:"If the browser did not open automatically, use the button below.",cls:"setting-item-description"}),new T.Setting(t).addButton(s=>s.setButtonText("Open browser").onClick(()=>window.open(this.request.verificationUri))).addButton(s=>s.setButtonText("Copy code").onClick(()=>{navigator.clipboard?.writeText(this.request.userCode)})).addButton(s=>s.setButtonText("Check now").onClick(()=>{this.poll()})),this.statusEl=t.createEl("p",{text:"Waiting for you to approve in the browser\u2026"});let r=Math.max(1,this.request.interval)*1e3;this.intervalId=window.setInterval(()=>{this.poll()},r),window.open(this.request.verificationUri)}onClose(){this.intervalId!==void 0&&(window.clearInterval(this.intervalId),this.intervalId=void 0)}async poll(){try{await this.plugin.pollDeviceLogin(this.request.deviceCode)==="pending"?this.statusEl?.setText("Waiting for approval..."):this.close()}catch(t){this.statusEl?.setText(je(t))}}},ou=class extends T.Modal{constructor(t,r,s,i){super(t);this.plugin=r;this.workspaces=s;this.onSelect=i}plugin;workspaces;onSelect;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Choose a workspace"}),t.createEl("p",{text:"Select which Pageden workspace to sync with this vault.",cls:"setting-item-description"});for(let r of this.workspaces)new T.Setting(t).setName(r.name).setDesc(r.role==="admin"?"You are an admin":"Member").addButton(s=>s.setButtonText("Select").setCta().onClick(async()=>{this.plugin.settings.workspaceId=r.id,this.plugin.settings.workspaceName=r.name,await this.plugin.saveSettings(),this.plugin.startAutoSync(),this.close(),new T.Notice(`Workspace set to "${r.name}".`),this.onSelect?.()}))}},sm=class extends T.Modal{constructor(t,r,s){super(t);this.plugin=r;this.tree=s}plugin;tree;onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Download a folder"}),t.createEl("p",{text:"Choose a folder to download all its notes to your vault.",cls:"setting-item-description"});let r=this.tree.folders.map(s=>({folder:s,count:this.tree.documents.filter(i=>i.folderId===s.id).length})).filter(({count:s})=>s>0).sort((s,i)=>s.folder.path.localeCompare(i.folder.path));if(r.length===0){t.createEl("p",{text:"No folders with documents found in your workspace."});return}for(let{folder:s,count:i}of r)new T.Setting(t).setName(s.name).setDesc(`${s.path} \xB7 ${i} note${i===1?"":"s"}`).addButton(o=>o.setButtonText("Download all").onClick(()=>{this.close(),this.plugin.downloadFolderDocuments(s.id,s.name,this.tree)}))}};function je(n){return n instanceof Error?n.message:"Pageden request failed."}function av(n,e){let t=(0,T.normalizePath)(n).replace(/\/+$/,""),r=(0,T.normalizePath)(e);return r===t||r.startsWith(`${t}/`)}function WP(n){return J.parse(n,{async:!1})}function cv(n){let e=uv.turndown(n).trimEnd();return e?`${e} `:""} diff --git a/manifest.json b/manifest.json index 5dcebd7..40380d3 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "pageden-sync", "name": "Pageden Sync", - "version": "0.1.4", + "version": "0.1.5", "minAppVersion": "1.5.0", "description": "Edit your team's server-owned Markdown documents from Pageden.", "author": "ccfiel", diff --git a/package.json b/package.json new file mode 100644 index 0000000..d94c10b --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "pageden-sync", + "version": "0.1.5", + "private": true, + "type": "module", + "scripts": { + "build": "node esbuild.config.mjs", + "typecheck": "tsc --noEmit", + "test": "vitest run -c vitest.config.ts" + }, + "dependencies": { + "@tiptap/core": "3.26.0", + "@tiptap/extension-collaboration": "3.26.0", + "@tiptap/extension-link": "3.26.0", + "@tiptap/extension-placeholder": "3.26.0", + "@tiptap/extension-table": "3.26.0", + "@tiptap/extension-table-cell": "3.26.0", + "@tiptap/extension-table-header": "3.26.0", + "@tiptap/extension-table-row": "3.26.0", + "@tiptap/extension-task-item": "3.26.0", + "@tiptap/extension-task-list": "3.26.0", + "@tiptap/pm": "3.26.0", + "@tiptap/starter-kit": "3.26.0", + "marked": "^18.0.5", + "turndown": "^7.2.4", + "turndown-plugin-gfm": "^1.0.2", + "y-websocket": "^3.0.0", + "yjs": "^13.6.31" + }, + "devDependencies": { + "@types/node": "^20", + "@types/turndown": "^5.0.6", + "esbuild": "^0.28.0", + "obsidian": "^1.13.0", + "typescript": "^5.9.3", + "vitest": "^2.0.5" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..3160615 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1869 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@tiptap/core': + specifier: 3.26.0 + version: 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/extension-collaboration': + specifier: 3.26.0 + version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)(@tiptap/y-tiptap@3.0.5(prosemirror-model@1.25.8)(prosemirror-state@1.4.4)(prosemirror-view@1.41.9)(y-protocols@1.0.7(yjs@13.6.31))(yjs@13.6.31))(yjs@13.6.31) + '@tiptap/extension-link': + specifier: 3.26.0 + version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/extension-placeholder': + specifier: 3.26.0 + version: 3.26.0(@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-table': + specifier: 3.26.0 + version: 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/extension-table-cell': + specifier: 3.26.0 + version: 3.26.0(@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-table-header': + specifier: 3.26.0 + version: 3.26.0(@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-table-row': + specifier: 3.26.0 + version: 3.26.0(@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-task-item': + specifier: 3.26.0 + version: 3.26.0(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-task-list': + specifier: 3.26.0 + version: 3.26.0(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/pm': + specifier: 3.26.0 + version: 3.26.0 + '@tiptap/starter-kit': + specifier: 3.26.0 + version: 3.26.0 + marked: + specifier: ^18.0.5 + version: 18.0.5 + turndown: + specifier: ^7.2.4 + version: 7.2.4 + turndown-plugin-gfm: + specifier: ^1.0.2 + version: 1.0.2 + y-websocket: + specifier: ^3.0.0 + version: 3.0.0(yjs@13.6.31) + yjs: + specifier: ^13.6.31 + version: 13.6.31 + devDependencies: + '@types/node': + specifier: ^20 + version: 20.19.43 + '@types/turndown': + specifier: ^5.0.6 + version: 5.0.6 + esbuild: + specifier: ^0.28.0 + version: 0.28.1 + obsidian: + specifier: ^1.13.0 + version: 1.13.1(@codemirror/state@6.5.0)(@codemirror/view@6.38.6) + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^2.0.5 + version: 2.1.9(@types/node@20.19.43) + +packages: + + '@codemirror/state@6.5.0': + resolution: {integrity: sha512-MwBHVK60IiIHDcoMet78lxt6iw5gJOGSbNbOIVBHWVXIH4/Nq1+GQgLLGgI1KlnN86WDXsPudVaqYHKBIx7Eyw==} + + '@codemirror/view@6.38.6': + resolution: {integrity: sha512-qiS0z1bKs5WOvHIAC0Cybmv4AJSkAXgX5aD6Mqd2epSLlVJsQl8NG23jCVouIgkh4All/mrbdsf2UOLFnJw0tw==} + + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.1': + resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.1': + resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.1': + resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.1': + resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.1': + resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.1': + resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.1': + resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.1': + resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.1': + resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.1': + resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.1': + resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.1': + resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.1': + resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.1': + resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.1': + resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.1': + resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.1': + resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.1': + resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.1': + resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.1': + resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.1': + resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.1': + resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.1': + resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.1': + resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.1': + resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.1': + resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@marijn/find-cluster-break@1.0.2': + resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==} + + '@mixmark-io/domino@2.2.0': + resolution: {integrity: sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==} + + '@rollup/rollup-android-arm-eabi@4.62.0': + resolution: {integrity: sha512-IPIQ55ythEHkfEd9jMEi32OQ7SxURsGA43JI22lj01OLZNt2NUbJX8YUHxkVWyQ6daHPNn0truF5nSj3DQp6YQ==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.62.0': + resolution: {integrity: sha512-M6s9cr10MibETyo8JsOkq+Lo1+lU6hcvb1MApnUql5qte/5hMEgzlN8/ReIKNfRV8rrqX50W1BX9zoUhC192RA==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.62.0': + resolution: {integrity: sha512-BqCoMoIbn0keKys+dEAdBa70EtOwV1bEsQCUgU9FdiZmmMge/Zk7LlkYGqbrdHR+Frnt0E1FOanly+rlwvvQzw==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.62.0': + resolution: {integrity: sha512-SIMzST3VFNXDAbeIWDWiFCNM5qncUBDWaEV7NfE7oZbDt2mgfW4MvbKdbYiGOLoM32gbTv608UMd0XktEYSD7w==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.62.0': + resolution: {integrity: sha512-ezjfSQMP7ArdUsbBwbQIfwAlhE84I2iVnzQNCFSveqV42q+BmKlzVpf7mxv5EchLcoWU4y6/heFzVg1F+hodUQ==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.62.0': + resolution: {integrity: sha512-9+qTWGW9AZRhnUgwtTwzNwcPlL87ngkeN0LA+q1bADvmY9aNvWaF2TFW8BZgnQPYxpDI7+rMVLivcd4V737TAQ==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.62.0': + resolution: {integrity: sha512-T1dMEQhXA/jkJ/jyMIw9IovK8bSUq7A8kLIlvZTb/6YIVsp2zLavr4F3oyllHWo7eIVJRyE5n3tUjQJEbE1IuQ==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.62.0': + resolution: {integrity: sha512-2as0LgT7qQpyceQq6VUJYnumUMUrgGQCWIiDIN9DE0/tglsk6o66uCB4f3djRawAltvfCNLyZZrsqbPA6inCsA==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.62.0': + resolution: {integrity: sha512-bVURMg+6eNN9C/yc0aVjooZcwTTtYF4YW3xta5pP0//r3o1V8gXEHXWCndj47w/HhwsFroZrFhR+6uQP5T0n0g==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.62.0': + resolution: {integrity: sha512-Ful8pM/2yYI83PViWdFdpZhdI8HJ5qsXANe5atypbHDf+KIBBDsZsbyy8hbXnULVvW9NsTh5DHwbcBftyLTfiw==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.62.0': + resolution: {integrity: sha512-9Gp/DgrkzfUBmNPVTyPTvay+4xEP7M/clXpj3efXBcm6uTIVIgDg4rqUpqKXvLEuFRVuEpSAOkhgNeecvaZ4Cg==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-loong64-musl@4.62.0': + resolution: {integrity: sha512-m9tsJz54LUXkSYM8+8PG81B9IKK5r+2T0clMq4QrS16xFosufU7firBDAZEsDheDs7wTlP7h3++S7lMsU955HA==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.62.0': + resolution: {integrity: sha512-3UvJ5PNVU16aJf6M3tFI24pWzAl2/ynfbyRN3ICyQajK1lSkrnVYNnLz3v04J32qKa0FczJc22zeToc0lr2A3w==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-ppc64-musl@4.62.0': + resolution: {integrity: sha512-vRWUAbYLGHBZS6Q8Msb2sfnf1fvJf+47t8l/TwOerM2qArzy+IeNMTHrYLHXh95h8MoatPHI5hhSZNs+mGXKPg==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.62.0': + resolution: {integrity: sha512-c00T5SYENHAt86cfW47URaP3Us5vLC/4QO7GYud1G5VNRffCwwCuBspwqYrriuJB+5m0WFzClCn9wed0FBjKvg==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.62.0': + resolution: {integrity: sha512-krrCDilhXOwFkSkO3Wm9I/f9H0L92XHHwy2fwxjukxIbh0dem8gZqOW5Y8BsHrpJv5qwlRBV+Wl4ZFyRWhUpwg==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.62.0': + resolution: {integrity: sha512-7pfYFSTc4/rUC/FtAI0Qp6QthDBCIi6/AuP1xYqFk5vanI6KnL5dWKP60OM/05LOsbwTmIcvr6eXC4CJuJ75IA==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.62.0': + resolution: {integrity: sha512-7SDIalKeIpG0Ifogbbdn58HmSotYMlf23K3dCJEmiVd9Fg36Vmni82iPQec27N3wY4Bvbxftkxz6vSx9OcouTg==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.62.0': + resolution: {integrity: sha512-eRZevouTH2i1HeAVLqJuLnt256krQkGY0TN6WsTmsIhuzbh457HuWDMakKwmi0Cjadux983CoSr8Lim2QhUIFw==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openbsd-x64@4.62.0': + resolution: {integrity: sha512-3oVS7FLGa4U1qcvao9ylGxrjXZyUQqR8UwxEcnUEyPX53O/C/mKDZegNXTdHCP+h3e6ta/f1EN38Yif1mmZHYg==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.62.0': + resolution: {integrity: sha512-yTB9TgfWj5wHe5QgktAgXTLLot1gvEjl1NiPPAUiCs4oPrIWFl5V4nC3GrkNdj9LaAU4s94nVrGbGOCqUpyWsg==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.62.0': + resolution: {integrity: sha512-5LOhoaesY3doG1c+ac/2JtgREpKoJr5bUHH8tKY0V8di7+uSV6BwLs2PlR0/yzefGOkR+wE7ZolZphHCsyG5Rw==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.62.0': + resolution: {integrity: sha512-yYkWHhmbhRTWTnWos5HC4GcPQfjlzzCNbM9e/+GXrLuaBXYA3qSDR9f0Vgufd5S8yX81U8jPKp7ZnAjZFMtRnw==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.62.0': + resolution: {integrity: sha512-SoTb6lPg25xZlA2ibwQ++ahCCnH+FP0qmEuafMJ4gznZKOlXioKEAeJLgCrqjM98ACziXM9V1amFjICVL4IFoA==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.62.0': + resolution: {integrity: sha512-5L+T1fMX4RIEBoZzT0+sQ0PhTS36NULFmMXtl1TZo44TMAROIMHbZufSOjVWt/Y622BtxgxtaNOokbTDvfsrZA==} + cpu: [x64] + os: [win32] + + '@tiptap/core@3.26.0': + resolution: {integrity: sha512-7jTed/RirIVsp+lLdLvGzGqF3EBGpnGHGYKOwz6t28V2BIJLAFdUhfEVdWie7xPxQNWK0TP+fPlsqZS0vxfHBg==} + peerDependencies: + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-blockquote@3.26.1': + resolution: {integrity: sha512-WaKjKmUaadgvZDDBk9JOn/oidlOFr6booqJIWHGL5S0aUUTKHS19oGfKQq/l9Z1y1niaRePk0Y4fy/jxCnfKPA==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-bold@3.26.1': + resolution: {integrity: sha512-VIlF2sAiV6K009pcIDotfY8mvsPaq90dxeG9Q0ZIqfMD958TUCqjHw4MGYZf0/FgP12xksBfmcR7W312xgUf9Q==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-bullet-list@3.26.1': + resolution: {integrity: sha512-JB6bEJJHxXNAXEXTIAN3/j70p1ARHdeMfhzshGZswWKUWtDibTCrspIp7p1VNeiuVtJ/HB6PpFkGi7yWtQ3RTg==} + peerDependencies: + '@tiptap/extension-list': 3.26.1 + + '@tiptap/extension-code-block@3.26.1': + resolution: {integrity: sha512-NY7SYqcrqDVYTSWyaNGdSfCims6pOHoRQ2Rh4DEFb/rb8gLVkqbLZhcHzQCVfinlPqgV3xWF6cYMORwmnlBkXQ==} + peerDependencies: + '@tiptap/core': 3.26.1 + '@tiptap/pm': 3.26.1 + + '@tiptap/extension-code@3.26.1': + resolution: {integrity: sha512-t9/VR5k3rGPyhcGau9YvVgaAQ+nP9R9WzS996bQQ7GIrMOTSXb0FWwoQFBiYl83V6VA16Tlj/oScC7SFlA8lvA==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-collaboration@3.26.0': + resolution: {integrity: sha512-zSNsjznGSpYC9CYg3acvLOt36ldjs4dA2qEsh7jaONqo6sKJo76UuZAN0N38V8qnH8WtAWes4uGmwWcWcRg90A==} + peerDependencies: + '@tiptap/core': 3.26.0 + '@tiptap/pm': 3.26.0 + '@tiptap/y-tiptap': ^3.0.4 + yjs: ^13 + + '@tiptap/extension-document@3.26.1': + resolution: {integrity: sha512-6W2vZjvi0Mv+4xEtwMDGhWwo7FotWR6eKfmntmduvehWevFpMxOKcTtyotjLigfZv738y50YWmvbaPuAPJG3BA==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-dropcursor@3.26.1': + resolution: {integrity: sha512-eVq3BvFIa3YD+pBIlj1i72vYEixlegGVKHnSYiVF2ovkQOSAH9sca7pkq6WgV1sMTCyWCU8e+WznTqtydvHUWA==} + peerDependencies: + '@tiptap/extensions': 3.26.1 + + '@tiptap/extension-gapcursor@3.26.1': + resolution: {integrity: sha512-BWW1yMQQA4TbEU0LLK+4cd9ebLTuZG5KjHwFMBRD/bGiRW9V1gTWFsCqThBbczcANoQiZK9pn5/4Ad/rGM3HUg==} + peerDependencies: + '@tiptap/extensions': 3.26.1 + + '@tiptap/extension-hard-break@3.26.1': + resolution: {integrity: sha512-gzNb1e/fK6HN+ko1axsrasjK7F1q0Bnm0G4ZY/0eq7pV7s1wZuwoCiGbvUx/9LCFKRV6+94FTqlb0A3NbYN36g==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-heading@3.26.1': + resolution: {integrity: sha512-eRlv9XxzUL8FobKAiF1WjP35CT2QpbcxxeyYFF7BmGEONvKI7r5g7JGwyGli4Cvclh70h8w6JuoXSmGUVEU65A==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-horizontal-rule@3.26.1': + resolution: {integrity: sha512-l9lPZYeSmY90y/2GkQcKaICFD5Atr8sx2SzJGkQzpNC9tRxZXyAHnfJE3OjBkspuGzjWIN0DimxBj4ibz58sKw==} + peerDependencies: + '@tiptap/core': 3.26.1 + '@tiptap/pm': 3.26.1 + + '@tiptap/extension-italic@3.26.1': + resolution: {integrity: sha512-cLKYvOLToWEkJkAPspgIZ/PYDzAxacLm1VWcAq1tO1QDQCDe2Kw+y/zsGlyYEq/aKsAgpp4JNopBwAXRXxt2/A==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-link@3.26.0': + resolution: {integrity: sha512-FA/d157aBxyvZFvsdc5eSu46tmHWXebAsqOQSvivOMyw+deBb00VlMsf+iD2J8+sekjbMYwx/hvbsu+xUoX43Q==} + peerDependencies: + '@tiptap/core': 3.26.0 + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-list-item@3.26.1': + resolution: {integrity: sha512-5gLXJUiP763NA6i4HgrtcwUDXPP8820hsaBQyF1Y1VsXNi02uW9FVLe3RZK8jF0NZUNh9CqD0gogYJCbKOUU8A==} + peerDependencies: + '@tiptap/extension-list': 3.26.1 + + '@tiptap/extension-list-keymap@3.26.1': + resolution: {integrity: sha512-EReSayePO6SIxtRbxx+7KfBQreWHvoZmMb3O/RemfT8W6J0hCG5N/Rh8Z12+YZOnCDRXJ4RzFpAikYka3E54jQ==} + peerDependencies: + '@tiptap/extension-list': 3.26.1 + + '@tiptap/extension-list@3.26.1': + resolution: {integrity: sha512-06nOjnyXpzMO8Ys5k3IbYsDsKib1mv2OtaxBYX1/1uvRyOKwUX5tqDLb/qigic0LIANNL73lkNC8Z8XPeG4Tkg==} + peerDependencies: + '@tiptap/core': 3.26.1 + '@tiptap/pm': 3.26.1 + + '@tiptap/extension-ordered-list@3.26.1': + resolution: {integrity: sha512-LeFPeFwb7ylkQVuuaHj+niu7WhWHpjDOi1GKZJE/ohOa2lgt7P221HMqhUzPiDlXOExN72oWTNmXUlT0ymCTkw==} + peerDependencies: + '@tiptap/extension-list': 3.26.1 + + '@tiptap/extension-paragraph@3.26.1': + resolution: {integrity: sha512-OkBeYUNM3eTzjm3z6IcC3NHryOX8g3eGNI86P/B+tFoFQSRuzLsKZU50ARCfIiLLg812NjcqujeJ1eX3BKDZrw==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-placeholder@3.26.0': + resolution: {integrity: sha512-q9RsGWmL0xEwrMK5Wx53eMdZlkA3J1cqloIc69rEugjOCjoExEkfF4e2nC9YK49qGxJZBKKksw1Ij7oCWEyu+g==} + peerDependencies: + '@tiptap/extensions': 3.26.0 + + '@tiptap/extension-strike@3.26.1': + resolution: {integrity: sha512-7hmQ2mBsA+75GRrJIKYxb+10H23mblEQSGGsv9Ptl7JLaGmj+8sv2HGQGSUT9QBiBVprxaYTqyWFXQC9akfLWg==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-table-cell@3.26.0': + resolution: {integrity: sha512-RhsCSJXgC7AxltrAZ7ePya+OG6H8fDEnQsr/jhWuucdnkH2jXPnYnXhzgOoJifyHwxRS+Sx0FRQWGHDA3peGMA==} + peerDependencies: + '@tiptap/extension-table': 3.26.0 + + '@tiptap/extension-table-header@3.26.0': + resolution: {integrity: sha512-kQx5RSjPygmhgNnkZtoD2j5AQ1Vj2Pzzif/sm8I75MlWNqp7yIWhCOcK7cwL6JQqf8GovzjAeMVY+5SDAOuVxw==} + peerDependencies: + '@tiptap/extension-table': 3.26.0 + + '@tiptap/extension-table-row@3.26.0': + resolution: {integrity: sha512-uBlCG1QIhgBwwXQROqolDlMwv9f2Wy3dH/2o5mlNwSQPI0B1+hdLV1eVep3MKRDweJqlP7kIhNNJxCUZQO+WYA==} + peerDependencies: + '@tiptap/extension-table': 3.26.0 + + '@tiptap/extension-table@3.26.0': + resolution: {integrity: sha512-pLL1+tKeUWSF/w4se84tjWUnuraKVELQtIHwi1XKoq6vkevotwwMb99xY6cJ752FaUFVDbViFe/JUYWBoU+bIw==} + peerDependencies: + '@tiptap/core': 3.26.0 + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-task-item@3.26.0': + resolution: {integrity: sha512-/S5+u/1hNd/fAkrsojqRV7D7hsL3uK9hY/icWGKYDlKN5uBsCehU8/a/YOR1xl3xCeLcLFs16nSlpgJF9UHP0A==} + peerDependencies: + '@tiptap/extension-list': 3.26.0 + + '@tiptap/extension-task-list@3.26.0': + resolution: {integrity: sha512-Zi94LADPSmYk0SGqLpR9zc9u/hyn0+EXY5IvYS/3q+p5usBXHG3noz/t6TbiIm5fkZZ+G0L15HsRR+YuoCbArw==} + peerDependencies: + '@tiptap/extension-list': 3.26.0 + + '@tiptap/extension-text@3.26.1': + resolution: {integrity: sha512-Gocui5WvcCCJJIX17gdOVCSdYi5H4fDwaR0qkMAUZPq5kJCdrfl+vNpt8BTt53Bk+/QumiUW21fhQ184w7RoeQ==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extension-underline@3.26.1': + resolution: {integrity: sha512-HUHtQ+DRWDM0opW7Nk3YQwrLzw876hMU7cr1X/ZTG+8Bp+AKHihlwU+bqrPgG5St0mqASyUEhHQ/vK5PlnUYOQ==} + peerDependencies: + '@tiptap/core': 3.26.1 + + '@tiptap/extensions@3.26.1': + resolution: {integrity: sha512-PmRaoe6bebTgz/ZQrjmzwZMST1d9js9ZTiKnUXeXl3Fm+V5U/c3TbbKDfqmL63qPQdjtShDMHi9tYuv+c77OFQ==} + peerDependencies: + '@tiptap/core': 3.26.1 + '@tiptap/pm': 3.26.1 + + '@tiptap/pm@3.26.0': + resolution: {integrity: sha512-q4RDeWwVrhOL0jJCGRgGxLSdjOYwzQ4h2InURZVhC66433ipcHd6f3bqSOhcXZ4r0sFmMNsuF7aZmUntjWLc7w==} + + '@tiptap/starter-kit@3.26.0': + resolution: {integrity: sha512-o34EtMfqtBaljdmeElZsRG/067oGx9Zcq+j2GWo71KlZe22ga/ALexeTf1c+ETsjCxSTKR6eyQ4RZvz/2JpYfg==} + + '@tiptap/y-tiptap@3.0.5': + resolution: {integrity: sha512-WoK5z3jMW+9nzumcWAxEDRCSC7yQmdq4NN0157MaxQBl9dGWwjxJx3+11mb+WAqR37oDeAMKMmSNy+/hm2XGlA==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + peerDependencies: + prosemirror-model: ^1.7.1 + prosemirror-state: ^1.2.3 + prosemirror-view: ^1.9.10 + y-protocols: ^1.0.1 + yjs: ^13.5.38 + + '@types/codemirror@5.60.8': + resolution: {integrity: sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/node@20.19.43': + resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==} + + '@types/tern@0.23.9': + resolution: {integrity: sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw==} + + '@types/turndown@5.0.6': + resolution: {integrity: sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg==} + + '@vitest/expect@2.1.9': + resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==} + + '@vitest/mocker@2.1.9': + resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@2.1.9': + resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==} + + '@vitest/runner@2.1.9': + resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==} + + '@vitest/snapshot@2.1.9': + resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==} + + '@vitest/spy@2.1.9': + resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==} + + '@vitest/utils@2.1.9': + resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + crelt@1.0.6: + resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.28.1: + resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.3.0: + resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + engines: {node: '>=12.0.0'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + isomorphic.js@0.2.5: + resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} + + lib0@0.2.117: + resolution: {integrity: sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==} + engines: {node: '>=16'} + hasBin: true + + linkifyjs@4.3.3: + resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + marked@18.0.5: + resolution: {integrity: sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==} + engines: {node: '>= 20'} + hasBin: true + + moment@2.29.4: + resolution: {integrity: sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.12: + resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obsidian@1.13.1: + resolution: {integrity: sha512-qtTEA2pmhJzhuhJqzbBFRYhpIOqvW+krDYjtFynv66KbxBbumHBlsJfWw3I4jtnK/6fZwbQhCrmmDdRwXmX56w==} + peerDependencies: + '@codemirror/state': 6.5.0 + '@codemirror/view': 6.38.6 + + orderedmap@2.1.1: + resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==} + + pathe@1.1.2: + resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + postcss@8.5.15: + resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} + engines: {node: ^10 || ^12 || >=14} + + prosemirror-changeset@2.4.1: + resolution: {integrity: sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==} + + prosemirror-commands@1.7.1: + resolution: {integrity: sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==} + + prosemirror-dropcursor@1.8.2: + resolution: {integrity: sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==} + + prosemirror-gapcursor@1.4.1: + resolution: {integrity: sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==} + + prosemirror-history@1.5.0: + resolution: {integrity: sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==} + + prosemirror-inputrules@1.5.1: + resolution: {integrity: sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==} + + prosemirror-keymap@1.2.3: + resolution: {integrity: sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==} + + prosemirror-model@1.25.8: + resolution: {integrity: sha512-BswA4BLSFEiORV6Vjj/yZBXDbos1zTEnhyeSSgT8psGFhstQS7UJ8/WOLiDos9Byaee27+tml0/DuMNxYR84zg==} + + prosemirror-schema-list@1.5.1: + resolution: {integrity: sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==} + + prosemirror-state@1.4.4: + resolution: {integrity: sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==} + + prosemirror-tables@1.8.5: + resolution: {integrity: sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==} + + prosemirror-transform@1.12.0: + resolution: {integrity: sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==} + + prosemirror-view@1.41.9: + resolution: {integrity: sha512-clTunTX+eaLbr87L1V1QPheRlEQJyTlL3gXe9x3jQIk3rL0RVWxviDGz8tFaydwIVm+hKhYCyr+R/zBtWr9s6A==} + + rollup@4.62.0: + resolution: {integrity: sha512-nc72Wgq62I7rtDV4izT5/aaS0zxy3kttkinf9586ApknY3jZO9NYsmtc24fUckA0X7Q2v+ML4a15pdUlV5V/jA==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + rope-sequence@1.3.4: + resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + style-mod@4.1.3: + resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@1.2.0: + resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==} + engines: {node: '>=14.0.0'} + + tinyspy@3.0.2: + resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==} + engines: {node: '>=14.0.0'} + + turndown-plugin-gfm@1.0.2: + resolution: {integrity: sha512-vwz9tfvF7XN/jE0dGoBei3FXWuvll78ohzCZQuOb+ZjWrs3a0XhQVomJEb2Qh4VHTPNRO4GPZh0V7VRbiWwkRg==} + + turndown@7.2.4: + resolution: {integrity: sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ==} + engines: {node: '>=18', npm: '>=9'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + vite-node@2.1.9: + resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + + vite@5.4.21: + resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vitest@2.1.9: + resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/node': ^18.0.0 || >=20.0.0 + '@vitest/browser': 2.1.9 + '@vitest/ui': 2.1.9 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + w3c-keyname@2.2.8: + resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + y-protocols@1.0.7: + resolution: {integrity: sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + peerDependencies: + yjs: ^13.0.0 + + y-websocket@3.0.0: + resolution: {integrity: sha512-mUHy7AzkOZ834T/7piqtlA8Yk6AchqKqcrCXjKW8J1w2lPtRDjz8W5/CvXz9higKAHgKRKqpI3T33YkRFLkPtg==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + peerDependencies: + yjs: ^13.5.6 + + yjs@13.6.31: + resolution: {integrity: sha512-Eq+5BRfbeGyqGVrTJL3bEcr8gKkxPuyuoHmAwpk52fDb8kOVMrfVSTRPd6yiGgX5Fskb96qCRjzjbRjrL4YEnw==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + +snapshots: + + '@codemirror/state@6.5.0': + dependencies: + '@marijn/find-cluster-break': 1.0.2 + + '@codemirror/view@6.38.6': + dependencies: + '@codemirror/state': 6.5.0 + crelt: 1.0.6 + style-mod: 4.1.3 + w3c-keyname: 2.2.8 + + '@esbuild/aix-ppc64@0.21.5': + optional: true + + '@esbuild/aix-ppc64@0.28.1': + optional: true + + '@esbuild/android-arm64@0.21.5': + optional: true + + '@esbuild/android-arm64@0.28.1': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-arm@0.28.1': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/android-x64@0.28.1': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.28.1': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.28.1': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.28.1': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.28.1': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.28.1': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-arm@0.28.1': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.28.1': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.28.1': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.28.1': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.28.1': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.28.1': + optional: true + + '@esbuild/linux-s390x@0.21.5': + optional: true + + '@esbuild/linux-s390x@0.28.1': + optional: true + + '@esbuild/linux-x64@0.21.5': + optional: true + + '@esbuild/linux-x64@0.28.1': + optional: true + + '@esbuild/netbsd-arm64@0.28.1': + optional: true + + '@esbuild/netbsd-x64@0.21.5': + optional: true + + '@esbuild/netbsd-x64@0.28.1': + optional: true + + '@esbuild/openbsd-arm64@0.28.1': + optional: true + + '@esbuild/openbsd-x64@0.21.5': + optional: true + + '@esbuild/openbsd-x64@0.28.1': + optional: true + + '@esbuild/openharmony-arm64@0.28.1': + optional: true + + '@esbuild/sunos-x64@0.21.5': + optional: true + + '@esbuild/sunos-x64@0.28.1': + optional: true + + '@esbuild/win32-arm64@0.21.5': + optional: true + + '@esbuild/win32-arm64@0.28.1': + optional: true + + '@esbuild/win32-ia32@0.21.5': + optional: true + + '@esbuild/win32-ia32@0.28.1': + optional: true + + '@esbuild/win32-x64@0.21.5': + optional: true + + '@esbuild/win32-x64@0.28.1': + optional: true + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@marijn/find-cluster-break@1.0.2': {} + + '@mixmark-io/domino@2.2.0': {} + + '@rollup/rollup-android-arm-eabi@4.62.0': + optional: true + + '@rollup/rollup-android-arm64@4.62.0': + optional: true + + '@rollup/rollup-darwin-arm64@4.62.0': + optional: true + + '@rollup/rollup-darwin-x64@4.62.0': + optional: true + + '@rollup/rollup-freebsd-arm64@4.62.0': + optional: true + + '@rollup/rollup-freebsd-x64@4.62.0': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.62.0': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.62.0': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.62.0': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.62.0': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.62.0': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.62.0': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.62.0': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.62.0': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.62.0': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.62.0': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.62.0': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.62.0': + optional: true + + '@rollup/rollup-linux-x64-musl@4.62.0': + optional: true + + '@rollup/rollup-openbsd-x64@4.62.0': + optional: true + + '@rollup/rollup-openharmony-arm64@4.62.0': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.62.0': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.62.0': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.62.0': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.62.0': + optional: true + + '@tiptap/core@3.26.0(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-blockquote@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-bold@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-bullet-list@3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-code-block@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-code@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-collaboration@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)(@tiptap/y-tiptap@3.0.5(prosemirror-model@1.25.8)(prosemirror-state@1.4.4)(prosemirror-view@1.41.9)(y-protocols@1.0.7(yjs@13.6.31))(yjs@13.6.31))(yjs@13.6.31)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + '@tiptap/y-tiptap': 3.0.5(prosemirror-model@1.25.8)(prosemirror-state@1.4.4)(prosemirror-view@1.41.9)(y-protocols@1.0.7(yjs@13.6.31))(yjs@13.6.31) + yjs: 13.6.31 + + '@tiptap/extension-document@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-dropcursor@3.26.1(@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extensions': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-gapcursor@3.26.1(@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extensions': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-hard-break@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-heading@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-horizontal-rule@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-italic@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-link@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + linkifyjs: 4.3.3 + + '@tiptap/extension-list-item@3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-list-keymap@3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-ordered-list@3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-paragraph@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-placeholder@3.26.0(@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extensions': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-strike@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-table-cell@3.26.0(@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-table': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-table-header@3.26.0(@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-table': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-table-row@3.26.0(@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-table': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-table@3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + + '@tiptap/extension-task-item@3.26.0(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-task-list@3.26.0(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + + '@tiptap/extension-text@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extension-underline@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + + '@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + + '@tiptap/pm@3.26.0': + dependencies: + prosemirror-changeset: 2.4.1 + prosemirror-commands: 1.7.1 + prosemirror-dropcursor: 1.8.2 + prosemirror-gapcursor: 1.4.1 + prosemirror-history: 1.5.0 + prosemirror-inputrules: 1.5.1 + prosemirror-keymap: 1.2.3 + prosemirror-model: 1.25.8 + prosemirror-schema-list: 1.5.1 + prosemirror-state: 1.4.4 + prosemirror-tables: 1.8.5 + prosemirror-transform: 1.12.0 + prosemirror-view: 1.41.9 + + '@tiptap/starter-kit@3.26.0': + dependencies: + '@tiptap/core': 3.26.0(@tiptap/pm@3.26.0) + '@tiptap/extension-blockquote': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-bold': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-bullet-list': 3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-code': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-code-block': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/extension-document': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-dropcursor': 3.26.1(@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-gapcursor': 3.26.1(@tiptap/extensions@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-hard-break': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-heading': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-horizontal-rule': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/extension-italic': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-link': 3.26.0(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/extension-list': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/extension-list-item': 3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-list-keymap': 3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-ordered-list': 3.26.1(@tiptap/extension-list@3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0)) + '@tiptap/extension-paragraph': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-strike': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-text': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extension-underline': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0)) + '@tiptap/extensions': 3.26.1(@tiptap/core@3.26.0(@tiptap/pm@3.26.0))(@tiptap/pm@3.26.0) + '@tiptap/pm': 3.26.0 + + '@tiptap/y-tiptap@3.0.5(prosemirror-model@1.25.8)(prosemirror-state@1.4.4)(prosemirror-view@1.41.9)(y-protocols@1.0.7(yjs@13.6.31))(yjs@13.6.31)': + dependencies: + lib0: 0.2.117 + prosemirror-model: 1.25.8 + prosemirror-state: 1.4.4 + prosemirror-view: 1.41.9 + y-protocols: 1.0.7(yjs@13.6.31) + yjs: 13.6.31 + + '@types/codemirror@5.60.8': + dependencies: + '@types/tern': 0.23.9 + + '@types/estree@1.0.9': {} + + '@types/node@20.19.43': + dependencies: + undici-types: 6.21.0 + + '@types/tern@0.23.9': + dependencies: + '@types/estree': 1.0.9 + + '@types/turndown@5.0.6': {} + + '@vitest/expect@2.1.9': + dependencies: + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + tinyrainbow: 1.2.0 + + '@vitest/mocker@2.1.9(vite@5.4.21(@types/node@20.19.43))': + dependencies: + '@vitest/spy': 2.1.9 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 5.4.21(@types/node@20.19.43) + + '@vitest/pretty-format@2.1.9': + dependencies: + tinyrainbow: 1.2.0 + + '@vitest/runner@2.1.9': + dependencies: + '@vitest/utils': 2.1.9 + pathe: 1.1.2 + + '@vitest/snapshot@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + magic-string: 0.30.21 + pathe: 1.1.2 + + '@vitest/spy@2.1.9': + dependencies: + tinyspy: 3.0.2 + + '@vitest/utils@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + loupe: 3.2.1 + tinyrainbow: 1.2.0 + + assertion-error@2.0.1: {} + + cac@6.7.14: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + check-error@2.1.3: {} + + crelt@1.0.6: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-eql@5.0.2: {} + + es-module-lexer@1.7.0: {} + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + esbuild@0.28.1: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.1 + '@esbuild/android-arm': 0.28.1 + '@esbuild/android-arm64': 0.28.1 + '@esbuild/android-x64': 0.28.1 + '@esbuild/darwin-arm64': 0.28.1 + '@esbuild/darwin-x64': 0.28.1 + '@esbuild/freebsd-arm64': 0.28.1 + '@esbuild/freebsd-x64': 0.28.1 + '@esbuild/linux-arm': 0.28.1 + '@esbuild/linux-arm64': 0.28.1 + '@esbuild/linux-ia32': 0.28.1 + '@esbuild/linux-loong64': 0.28.1 + '@esbuild/linux-mips64el': 0.28.1 + '@esbuild/linux-ppc64': 0.28.1 + '@esbuild/linux-riscv64': 0.28.1 + '@esbuild/linux-s390x': 0.28.1 + '@esbuild/linux-x64': 0.28.1 + '@esbuild/netbsd-arm64': 0.28.1 + '@esbuild/netbsd-x64': 0.28.1 + '@esbuild/openbsd-arm64': 0.28.1 + '@esbuild/openbsd-x64': 0.28.1 + '@esbuild/openharmony-arm64': 0.28.1 + '@esbuild/sunos-x64': 0.28.1 + '@esbuild/win32-arm64': 0.28.1 + '@esbuild/win32-ia32': 0.28.1 + '@esbuild/win32-x64': 0.28.1 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.3.0: {} + + fsevents@2.3.3: + optional: true + + isomorphic.js@0.2.5: {} + + lib0@0.2.117: + dependencies: + isomorphic.js: 0.2.5 + + linkifyjs@4.3.3: {} + + loupe@3.2.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + marked@18.0.5: {} + + moment@2.29.4: {} + + ms@2.1.3: {} + + nanoid@3.3.12: {} + + obsidian@1.13.1(@codemirror/state@6.5.0)(@codemirror/view@6.38.6): + dependencies: + '@codemirror/state': 6.5.0 + '@codemirror/view': 6.38.6 + '@types/codemirror': 5.60.8 + moment: 2.29.4 + + orderedmap@2.1.1: {} + + pathe@1.1.2: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + postcss@8.5.15: + dependencies: + nanoid: 3.3.12 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prosemirror-changeset@2.4.1: + dependencies: + prosemirror-transform: 1.12.0 + + prosemirror-commands@1.7.1: + dependencies: + prosemirror-model: 1.25.8 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + + prosemirror-dropcursor@1.8.2: + dependencies: + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + prosemirror-view: 1.41.9 + + prosemirror-gapcursor@1.4.1: + dependencies: + prosemirror-keymap: 1.2.3 + prosemirror-model: 1.25.8 + prosemirror-state: 1.4.4 + prosemirror-view: 1.41.9 + + prosemirror-history@1.5.0: + dependencies: + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + prosemirror-view: 1.41.9 + rope-sequence: 1.3.4 + + prosemirror-inputrules@1.5.1: + dependencies: + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + + prosemirror-keymap@1.2.3: + dependencies: + prosemirror-state: 1.4.4 + w3c-keyname: 2.2.8 + + prosemirror-model@1.25.8: + dependencies: + orderedmap: 2.1.1 + + prosemirror-schema-list@1.5.1: + dependencies: + prosemirror-model: 1.25.8 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + + prosemirror-state@1.4.4: + dependencies: + prosemirror-model: 1.25.8 + prosemirror-transform: 1.12.0 + prosemirror-view: 1.41.9 + + prosemirror-tables@1.8.5: + dependencies: + prosemirror-keymap: 1.2.3 + prosemirror-model: 1.25.8 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + prosemirror-view: 1.41.9 + + prosemirror-transform@1.12.0: + dependencies: + prosemirror-model: 1.25.8 + + prosemirror-view@1.41.9: + dependencies: + prosemirror-model: 1.25.8 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.0 + + rollup@4.62.0: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.62.0 + '@rollup/rollup-android-arm64': 4.62.0 + '@rollup/rollup-darwin-arm64': 4.62.0 + '@rollup/rollup-darwin-x64': 4.62.0 + '@rollup/rollup-freebsd-arm64': 4.62.0 + '@rollup/rollup-freebsd-x64': 4.62.0 + '@rollup/rollup-linux-arm-gnueabihf': 4.62.0 + '@rollup/rollup-linux-arm-musleabihf': 4.62.0 + '@rollup/rollup-linux-arm64-gnu': 4.62.0 + '@rollup/rollup-linux-arm64-musl': 4.62.0 + '@rollup/rollup-linux-loong64-gnu': 4.62.0 + '@rollup/rollup-linux-loong64-musl': 4.62.0 + '@rollup/rollup-linux-ppc64-gnu': 4.62.0 + '@rollup/rollup-linux-ppc64-musl': 4.62.0 + '@rollup/rollup-linux-riscv64-gnu': 4.62.0 + '@rollup/rollup-linux-riscv64-musl': 4.62.0 + '@rollup/rollup-linux-s390x-gnu': 4.62.0 + '@rollup/rollup-linux-x64-gnu': 4.62.0 + '@rollup/rollup-linux-x64-musl': 4.62.0 + '@rollup/rollup-openbsd-x64': 4.62.0 + '@rollup/rollup-openharmony-arm64': 4.62.0 + '@rollup/rollup-win32-arm64-msvc': 4.62.0 + '@rollup/rollup-win32-ia32-msvc': 4.62.0 + '@rollup/rollup-win32-x64-gnu': 4.62.0 + '@rollup/rollup-win32-x64-msvc': 4.62.0 + fsevents: 2.3.3 + + rope-sequence@1.3.4: {} + + siginfo@2.0.0: {} + + source-map-js@1.2.1: {} + + stackback@0.0.2: {} + + std-env@3.10.0: {} + + style-mod@4.1.3: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinypool@1.1.1: {} + + tinyrainbow@1.2.0: {} + + tinyspy@3.0.2: {} + + turndown-plugin-gfm@1.0.2: {} + + turndown@7.2.4: + dependencies: + '@mixmark-io/domino': 2.2.0 + + typescript@5.9.3: {} + + undici-types@6.21.0: {} + + vite-node@2.1.9(@types/node@20.19.43): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 1.1.2 + vite: 5.4.21(@types/node@20.19.43) + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vite@5.4.21(@types/node@20.19.43): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.15 + rollup: 4.62.0 + optionalDependencies: + '@types/node': 20.19.43 + fsevents: 2.3.3 + + vitest@2.1.9(@types/node@20.19.43): + dependencies: + '@vitest/expect': 2.1.9 + '@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@20.19.43)) + '@vitest/pretty-format': 2.1.9 + '@vitest/runner': 2.1.9 + '@vitest/snapshot': 2.1.9 + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.3.0 + magic-string: 0.30.21 + pathe: 1.1.2 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinypool: 1.1.1 + tinyrainbow: 1.2.0 + vite: 5.4.21(@types/node@20.19.43) + vite-node: 2.1.9(@types/node@20.19.43) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 20.19.43 + transitivePeerDependencies: + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + w3c-keyname@2.2.8: {} + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + y-protocols@1.0.7(yjs@13.6.31): + dependencies: + lib0: 0.2.117 + yjs: 13.6.31 + + y-websocket@3.0.0(yjs@13.6.31): + dependencies: + lib0: 0.2.117 + y-protocols: 1.0.7(yjs@13.6.31) + yjs: 13.6.31 + + yjs@13.6.31: + dependencies: + lib0: 0.2.117 diff --git a/src/api-client.test.ts b/src/api-client.test.ts new file mode 100644 index 0000000..9dc120e --- /dev/null +++ b/src/api-client.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from "vitest"; +import { PagedenApiClient, PagedenApiError, type RequestTransport } from "./api-client"; + +class FakeTransport implements RequestTransport { + calls: Array<{ url: string; method: string; headers?: Record; body?: string | ArrayBuffer }> = []; + + constructor(private readonly response: { status: number; text: string; arrayBuffer?: ArrayBuffer }) {} + + async request(options: { url: string; method: string; headers?: Record; body?: string | ArrayBuffer }) { + this.calls.push(options); + return this.response; + } +} + +describe("Pageden API client", () => { + it("sends bearer auth and trims duplicate server URL slashes", async () => { + const transport = new FakeTransport({ status: 200, text: JSON.stringify({ folders: [], documents: [] }) }); + const api = new PagedenApiClient("https://team.example.com///", "pm_live_test", transport); + await api.tree("ws 1"); + + expect(transport.calls[0]?.url).toBe("https://team.example.com/api/documents/tree?workspaceId=ws%201"); + expect(transport.calls[0]?.headers?.authorization).toBe("Bearer pm_live_test"); + }); + + it("surfaces conflict errors with currentVersion", async () => { + const transport = new FakeTransport({ + status: 409, + text: JSON.stringify({ error: "conflict", currentVersion: "rev2", message: "stale" }), + }); + const api = new PagedenApiClient("https://team.example.com", "pm_live_test", transport); + + await expect(api.push("doc1", { baseVersion: "rev1", checksum: "sha256:x", content: "x" })).rejects.toMatchObject({ + status: 409, + currentVersion: "rev2", + } satisfies Partial); + }); + + it("searches remote documents with bearer auth", async () => { + const transport = new FakeTransport({ status: 200, text: JSON.stringify({ results: [] }) }); + const api = new PagedenApiClient("https://team.example.com", "pm_live_test", transport); + await api.search("ws1", "runbook notes", 10); + + expect(transport.calls[0]?.url).toBe("https://team.example.com/api/search?workspaceId=ws1&q=runbook+notes&limit=10"); + expect(transport.calls[0]?.headers?.authorization).toBe("Bearer pm_live_test"); + }); + + it("creates folders and documents through the normal API", async () => { + const folderTransport = new FakeTransport({ status: 201, text: JSON.stringify({ id: "folder1", path: "imported" }) }); + const api = new PagedenApiClient("https://team.example.com", "pm_live_test", folderTransport); + await api.createFolder({ workspaceId: "ws1", parentFolderId: null, name: "Imported", slug: "imported" }); + + expect(folderTransport.calls[0]?.url).toBe("https://team.example.com/api/folders"); + expect(folderTransport.calls[0]?.headers?.authorization).toBe("Bearer pm_live_test"); + expect(JSON.parse(String(folderTransport.calls[0]?.body ?? "{}"))).toEqual({ + workspaceId: "ws1", + parentFolderId: null, + name: "Imported", + slug: "imported", + }); + + const documentTransport = new FakeTransport({ status: 201, text: JSON.stringify({ id: "doc1", version: "rev1", checksum: "sha256:x", path: "imported/note.md" }) }); + const docApi = new PagedenApiClient("https://team.example.com", "pm_live_test", documentTransport); + await docApi.createDocument({ workspaceId: "ws1", folderId: "folder1", title: "Note", slug: "note", content: "# Note\n" }); + + expect(documentTransport.calls[0]?.url).toBe("https://team.example.com/api/documents"); + expect(JSON.parse(String(documentTransport.calls[0]?.body ?? "{}"))).toEqual({ + workspaceId: "ws1", + folderId: "folder1", + title: "Note", + slug: "note", + content: "# Note\n", + }); + }); + + it("starts and polls device login without bearer auth", async () => { + const transport = new FakeTransport({ + status: 201, + text: JSON.stringify({ deviceCode: "dev", userCode: "ABCD-2345", verificationUri: "https://app/devices", expiresIn: 600, interval: 5 }), + }); + const api = new PagedenApiClient("https://team.example.com", "", transport); + await api.deviceStart(); + + expect(transport.calls[0]?.url).toBe("https://team.example.com/api/auth/device/start"); + expect(transport.calls[0]?.headers?.authorization).toBeUndefined(); + + const pollTransport = new FakeTransport({ status: 200, text: JSON.stringify({ status: "approved", token: "pm_live_new" }) }); + const pollApi = new PagedenApiClient("https://team.example.com", "", pollTransport); + await expect(pollApi.devicePoll("dev")).resolves.toEqual({ status: "approved", token: "pm_live_new" }); + expect(pollTransport.calls[0]?.url).toBe("https://team.example.com/api/auth/device/poll"); + expect(pollTransport.calls[0]?.headers?.authorization).toBeUndefined(); + expect(JSON.parse(String(pollTransport.calls[0]?.body ?? "{}"))).toEqual({ deviceCode: "dev" }); + }); + + it("uploads and downloads attachment bytes", async () => { + const body = new Uint8Array([1, 2, 3]).buffer; + const transport = new FakeTransport({ + status: 201, + text: JSON.stringify({ id: "att1", filename: "a b.png", contentType: "image/png", size: 3, sha256: "abc", createdAt: "now" }), + }); + const api = new PagedenApiClient("https://team.example.com", "pm_live_test", transport); + await api.uploadAttachment("doc1", "a b.png", body, "image/png"); + + expect(transport.calls[0]?.url).toBe("https://team.example.com/api/documents/doc1/attachments?filename=a%20b.png"); + expect(transport.calls[0]?.headers?.["content-type"]).toBe("image/png"); + expect(transport.calls[0]?.body).toBe(body); + + const downloadBody = new Uint8Array([9]).buffer; + const downloadTransport = new FakeTransport({ status: 200, text: "", arrayBuffer: downloadBody }); + const downloadApi = new PagedenApiClient("https://team.example.com", "pm_live_test", downloadTransport); + await expect(downloadApi.downloadAttachment("att1")).resolves.toBe(downloadBody); + }); +}); diff --git a/src/api-client.ts b/src/api-client.ts new file mode 100644 index 0000000..6676fb0 --- /dev/null +++ b/src/api-client.ts @@ -0,0 +1,170 @@ +import { requestUrl } from "obsidian"; +import type { + Attachment, + AttachmentListResponse, + CreateDocumentResponse, + CreateFolderResponse, + DevicePollResponse, + DeviceStartResponse, + MeResponse, + RemoteDocumentWithContent, + RemoteTree, + SearchResponse, + WriteResult, +} from "./types"; + +export class PagedenApiError extends Error { + constructor( + readonly status: number, + readonly body: unknown, + ) { + super(`Pageden API error ${status}`); + this.name = "PagedenApiError"; + } + + get code(): string | undefined { + if (this.body && typeof this.body === "object" && "error" in this.body) { + return String((this.body as { error: unknown }).error); + } + return undefined; + } + + get currentVersion(): string | null { + if (this.body && typeof this.body === "object" && "currentVersion" in this.body) { + const value = (this.body as { currentVersion: unknown }).currentVersion; + return typeof value === "string" ? value : null; + } + return null; + } +} + +export interface RequestTransport { + request(options: { + url: string; + method: string; + headers?: Record; + body?: string | ArrayBuffer; + }): Promise<{ status: number; text: string; arrayBuffer?: ArrayBuffer }>; +} + +export class ObsidianRequestTransport implements RequestTransport { + async request(options: { url: string; method: string; headers?: Record; body?: string | ArrayBuffer }) { + const response = await requestUrl(options); + return { status: response.status, text: response.text, arrayBuffer: response.arrayBuffer }; + } +} + +export class PagedenApiClient { + constructor( + private readonly serverUrl: string, + private readonly token: string, + private readonly transport: RequestTransport = new ObsidianRequestTransport(), + ) {} + + me(): Promise { + return this.request("GET", "/me"); + } + + async validate(): Promise { + await this.me(); + } + + tree(workspaceId: string): Promise { + return this.request("GET", `/documents/tree?workspaceId=${encodeURIComponent(workspaceId)}`); + } + + document(id: string): Promise { + return this.request("GET", `/documents/${encodeURIComponent(id)}`); + } + + createFolder(body: { workspaceId: string; parentFolderId: string | null; name: string; slug: string }): Promise { + return this.request("POST", "/folders", body); + } + + createDocument(body: { workspaceId: string; folderId: string; title: string; slug: string; content: string }): Promise { + return this.request("POST", "/documents", body); + } + + push(documentId: string, body: { baseVersion: string; checksum: string; content: string }): Promise { + return this.request("POST", `/documents/${encodeURIComponent(documentId)}/push`, body); + } + + search(workspaceId: string, q: string, limit = 20): Promise { + const params = new URLSearchParams({ workspaceId, q, limit: String(limit) }); + return this.request("GET", `/search?${params.toString()}`); + } + + deviceStart(): Promise { + return this.request("POST", "/auth/device/start", undefined, { auth: false }); + } + + devicePoll(deviceCode: string): Promise { + return this.request("POST", "/auth/device/poll", { deviceCode }, { auth: false }); + } + + attachments(documentId: string): Promise { + return this.request("GET", `/documents/${encodeURIComponent(documentId)}/attachments`); + } + + uploadAttachment(documentId: string, filename: string, data: ArrayBuffer, contentType = "application/octet-stream"): Promise { + return this.request("POST", `/documents/${encodeURIComponent(documentId)}/attachments?filename=${encodeURIComponent(filename)}`, data, { + contentType, + raw: true, + }); + } + + async downloadAttachment(attachmentId: string): Promise { + const response = await this.rawRequest("GET", `/attachments/${encodeURIComponent(attachmentId)}`); + if (response.arrayBuffer) return response.arrayBuffer; + return new TextEncoder().encode(response.text).buffer; + } + + async deleteAttachment(attachmentId: string): Promise { + await this.request("DELETE", `/attachments/${encodeURIComponent(attachmentId)}`); + } + + private async request( + method: string, + path: string, + body?: unknown, + options: { auth?: boolean; contentType?: string; raw?: boolean } = {}, + ): Promise { + const response = await this.rawRequest(method, path, body, options); + const json = safeJson(response.text); + if (response.status < 200 || response.status >= 300) { + throw new PagedenApiError(response.status, json); + } + return json as T; + } + + private async rawRequest( + method: string, + path: string, + body?: unknown, + options: { auth?: boolean; contentType?: string; raw?: boolean } = {}, + ): Promise<{ status: number; text: string; arrayBuffer?: ArrayBuffer }> { + const headers = { + ...(options.auth === false || !this.token ? {} : { authorization: `Bearer ${this.token}` }), + ...(body === undefined ? {} : { "content-type": options.contentType ?? "application/json" }), + }; + const response = await this.transport.request({ + method, + url: `${this.serverUrl.replace(/\/+$/, "")}/api${path}`, + headers, + body: body === undefined ? undefined : options.raw ? (body as ArrayBuffer) : JSON.stringify(body), + }); + if (response.status < 200 || response.status >= 300) { + throw new PagedenApiError(response.status, safeJson(response.text)); + } + return response; + } +} + +function safeJson(text: string): unknown { + if (!text) return null; + try { + return JSON.parse(text); + } catch { + return text; + } +} diff --git a/src/checksum.test.ts b/src/checksum.test.ts new file mode 100644 index 0000000..bb4d853 --- /dev/null +++ b/src/checksum.test.ts @@ -0,0 +1,15 @@ +import { createHash, webcrypto } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { canonicalize, checksum } from "./checksum"; + +Object.defineProperty(globalThis, "crypto", { value: webcrypto, configurable: true }); + +describe("plugin checksum", () => { + it("canonicalizes CRLF, bare CR, empty, and trailing-newline variants", async () => { + expect(canonicalize("a\r\nb\r")).toBe("a\nb\n"); + expect(canonicalize("")).toBe("\n"); + expect(canonicalize("a\n\n\n")).toBe("a\n"); + const expected = createHash("sha256").update("a\nb\n", "utf8").digest("hex"); + await expect(checksum("a\r\nb")).resolves.toBe(`sha256:${expected}`); + }); +}); diff --git a/src/checksum.ts b/src/checksum.ts new file mode 100644 index 0000000..4a0692c --- /dev/null +++ b/src/checksum.ts @@ -0,0 +1,13 @@ +export function canonicalize(content: string): string { + return content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n*$/, "") + "\n"; +} + +export async function checksum(content: string): Promise { + if (!globalThis.crypto?.subtle) { + throw new Error("Web Crypto is required to compute Pageden checksums."); + } + const bytes = new TextEncoder().encode(canonicalize(content)); + const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes); + const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `sha256:${hex}`; +} diff --git a/src/import-vault.test.ts b/src/import-vault.test.ts new file mode 100644 index 0000000..e5d8cf4 --- /dev/null +++ b/src/import-vault.test.ts @@ -0,0 +1,111 @@ +import { webcrypto } from "node:crypto"; +import { describe, expect, it, vi } from "vitest"; +import { buildVaultImportPreview, extractAttachmentRefs, importVaultToPageden, slugify, type VaultImportFile } from "./import-vault"; +import type { RemoteDocumentWithContent, RemoteTree, ServerMetaEntry } from "./types"; + +Object.defineProperty(globalThis, "crypto", { value: webcrypto, configurable: true }); + +const files: VaultImportFile[] = [ + { path: "Projects/Launch.md", name: "Launch.md", extension: "md" }, + { path: "Projects/assets/diagram.png", name: "diagram.png", extension: "png" }, + { path: ".obsidian/app.json", name: "app.json", extension: "json" }, + { path: "Scratch.conflict.md", name: "Scratch.conflict.md", extension: "md" }, +]; + +const emptyTree: RemoteTree = { folders: [], documents: [] }; + +describe("vault import", () => { + it("previews notes, attachments, skipped internal files, and remote path conflicts", () => { + const preview = buildVaultImportPreview(files, { + folders: [], + documents: [ + { + id: "doc-existing", + folderId: "folder-existing", + title: "Launch", + path: "imported-from-obsidian/projects/launch.md", + permission: "editor", + version: "rev1", + checksum: "sha256:x", + }, + ], + }); + + expect(preview).toMatchObject({ + targetRootSlug: "imported-from-obsidian", + notes: 1, + attachments: 1, + skipped: 2, + conflicts: ["imported-from-obsidian/projects/launch.md"], + }); + }); + + it("extracts Obsidian and Markdown attachment embeds", () => { + expect(extractAttachmentRefs("![[diagram.png|wide]]\n![chart](assets/chart%201.png)\n![remote](https://example.com/x.png)")).toEqual([ + "diagram.png", + "assets/chart 1.png", + ]); + }); + + it("slugifies names into stable URL-safe segments", () => { + expect(slugify("Finance Plan.md")).toBe("finance-plan"); + expect(slugify("你好")).toBe("untitled"); + }); + + it("creates folders and documents, links metadata, and uploads referenced attachments", async () => { + const read = vi.fn(async (path: string) => { + if (path === "Projects/Launch.md") return "# Launch\r\n\n![[diagram.png]]\n"; + throw new Error(`missing ${path}`); + }); + const readBinary = vi.fn(async (path: string) => { + if (path === "Projects/assets/diagram.png") return new Uint8Array([1, 2, 3]).buffer; + throw new Error(`missing binary ${path}`); + }); + const upsert = vi.fn(); + const remoteDoc: RemoteDocumentWithContent = { + id: "doc1", + workspaceId: "ws1", + folderId: "folder-projects", + title: "Launch", + path: "imported-from-obsidian/projects/launch.md", + permission: "editor", + version: "rev1", + checksum: "sha256:server", + content: "# Launch\n\n![[diagram.png]]\n", + updatedAt: "2026-06-10T00:00:00.000Z", + }; + const api = { + tree: vi.fn(async () => emptyTree), + createFolder: vi + .fn() + .mockResolvedValueOnce({ id: "folder-root", path: "imported-from-obsidian" }) + .mockResolvedValueOnce({ id: "folder-projects", path: "imported-from-obsidian/projects" }), + createDocument: vi.fn(async () => ({ id: "doc1", version: "rev1", checksum: "sha256:server", path: "imported-from-obsidian/projects/launch.md" })), + document: vi.fn(async () => remoteDoc), + uploadAttachment: vi.fn(async () => ({ id: "att1", filename: "diagram.png", contentType: "image/png", size: 3, sha256: "sha256:a", createdAt: "now" })), + }; + + const report = await importVaultToPageden({ + api, + vault: { read, readBinary }, + meta: { upsert }, + workspaceId: "ws1", + files, + targetRootName: "Imported from Obsidian", + remoteTree: emptyTree, + }); + + expect(report).toMatchObject({ foldersCreated: 2, documentsCreated: 1, documentsSkipped: 0, attachmentsUploaded: 1 }); + expect(api.createFolder).toHaveBeenNthCalledWith(1, expect.objectContaining({ parentFolderId: null, slug: "imported-from-obsidian" })); + expect(api.createFolder).toHaveBeenNthCalledWith(2, expect.objectContaining({ parentFolderId: "folder-root", slug: "projects" })); + expect(api.createDocument).toHaveBeenCalledWith(expect.objectContaining({ folderId: "folder-projects", title: "Launch", slug: "launch" })); + expect(api.uploadAttachment).toHaveBeenCalledWith("doc1", "diagram.png", expect.any(ArrayBuffer), "image/png"); + expect(upsert).toHaveBeenCalledWith( + expect.objectContaining({ + documentId: "doc1", + localPath: "Projects/Launch.md", + baseVersion: "rev1", + } satisfies Partial), + ); + }); +}); diff --git a/src/import-vault.ts b/src/import-vault.ts new file mode 100644 index 0000000..4d3c1f9 --- /dev/null +++ b/src/import-vault.ts @@ -0,0 +1,373 @@ +import { normalizePath } from "obsidian"; +import type { PagedenApiClient } from "./api-client"; +import { canonicalize } from "./checksum"; +import type { RemoteFolder, RemoteTree, ServerMetaEntry } from "./types"; +import type { MetaStoreLike, VaultLike } from "./sync"; + +export interface VaultImportFile { + path: string; + name: string; + extension: string; +} + +export interface VaultImportPreview { + targetRootName: string; + targetRootSlug: string; + notes: number; + attachments: number; + skipped: number; + conflicts: string[]; + warnings: string[]; +} + +export interface VaultImportReport extends VaultImportPreview { + foldersCreated: number; + documentsCreated: number; + documentsSkipped: number; + attachmentsUploaded: number; + attachmentWarnings: string[]; + rows: ImportReportRow[]; +} + +export type ImportReportRow = + | { path: string; status: "created"; message: string } + | { path: string; status: "skipped"; message: string } + | { path: string; status: "warning"; message: string }; + +interface ImportDeps { + api: Pick; + vault: Pick; + meta: Pick; + workspaceId: string; + files: VaultImportFile[]; + targetRootName: string; + remoteTree?: RemoteTree; + onProgress?: (current: number, total: number) => void; +} + +interface ImportableFiles { + notes: VaultImportFile[]; + attachments: VaultImportFile[]; + skipped: number; +} + +const DEFAULT_ROOT_NAME = "Imported from Obsidian"; + +export function buildVaultImportPreview(files: VaultImportFile[], remoteTree: RemoteTree, targetRootName = DEFAULT_ROOT_NAME): VaultImportPreview { + const importable = splitImportableFiles(files); + const targetRootSlug = slugify(targetRootName); + const remoteDocumentPaths = new Set(remoteTree.documents.map((doc) => trimSlashes(doc.path))); + const conflicts = importable.notes + .map((file) => remotePathForNote(file.path, targetRootSlug)) + .filter((path) => remoteDocumentPaths.has(path)) + .sort(); + + const warnings = conflicts.length + ? [`${conflicts.length} note${conflicts.length === 1 ? "" : "s"} already exist in Pageden and will be skipped.`] + : []; + + return { + targetRootName, + targetRootSlug, + notes: importable.notes.length, + attachments: importable.attachments.length, + skipped: importable.skipped, + conflicts, + warnings, + }; +} + +export async function importVaultToPageden(deps: ImportDeps): Promise { + const remoteTree = deps.remoteTree ?? (await deps.api.tree(deps.workspaceId)); + const preview = buildVaultImportPreview(deps.files, remoteTree, deps.targetRootName); + const importable = splitImportableFiles(deps.files); + const attachmentIndex = buildAttachmentIndex(importable.attachments); + const folderByPath = new Map(remoteTree.folders.map((folder) => [trimSlashes(folder.path), folder])); + const documentPaths = new Set(remoteTree.documents.map((doc) => trimSlashes(doc.path))); + const targetRootSlug = preview.targetRootSlug; + let foldersCreated = 0; + let documentsCreated = 0; + let documentsSkipped = 0; + let attachmentsUploaded = 0; + const attachmentWarnings: string[] = []; + const rows: ImportReportRow[] = []; + + async function ensureRemoteFolder(localDir: string): Promise { + const segments = localDir.split("/").filter(Boolean); + let parent: RemoteFolder | null = null; + let currentPath = ""; + + const rootPath = targetRootSlug; + parent = folderByPath.get(rootPath) ?? null; + if (!parent) { + const created = await deps.api.createFolder({ + workspaceId: deps.workspaceId, + parentFolderId: null, + name: deps.targetRootName, + slug: targetRootSlug, + }); + parent = folderFromCreate(created.id, null, deps.targetRootName, targetRootSlug, created.path); + folderByPath.set(rootPath, parent); + foldersCreated += 1; + } + currentPath = rootPath; + + for (const segment of segments) { + const slug = slugify(segment); + currentPath = `${currentPath}/${slug}`; + const existing = folderByPath.get(currentPath); + if (existing) { + parent = existing; + continue; + } + const created = await deps.api.createFolder({ + workspaceId: deps.workspaceId, + parentFolderId: parent.id, + name: segment, + slug, + }); + parent = folderFromCreate(created.id, parent.id, segment, slug, created.path); + folderByPath.set(currentPath, parent); + foldersCreated += 1; + } + + return parent; + } + + let noteIndex = 0; + for (const note of importable.notes) { + noteIndex++; + deps.onProgress?.(noteIndex, importable.notes.length); + const remotePath = remotePathForNote(note.path, targetRootSlug); + if (documentPaths.has(remotePath)) { + documentsSkipped += 1; + rows.push({ path: note.path, status: "skipped", message: "A document with this path already exists." }); + continue; + } + const localDir = dirname(note.path); + const folder = await ensureRemoteFolder(localDir); + const content = canonicalize(await deps.vault.read(note.path)); + const title = frontmatterTitle(content) ?? (basename(note.path).replace(/\.md$/i, "") || "Untitled"); + const created = await deps.api.createDocument({ + workspaceId: deps.workspaceId, + folderId: folder.id, + title, + slug: slugify(basename(note.path).replace(/\.md$/i, "")), + content, + }); + documentPaths.add(trimSlashes(created.path)); + const remote = await deps.api.document(created.id); + await deps.meta.upsert(metaFromImportedRemote(remote, note.path)); + documentsCreated += 1; + rows.push({ path: note.path, status: "created", message: `Created ${created.path}` }); + + const refs = extractAttachmentRefs(content); + const uploadedForDoc = new Set(); + for (const ref of refs) { + const attachment = resolveAttachmentRef(ref, note.path, attachmentIndex); + if (!attachment || uploadedForDoc.has(attachment.path)) continue; + uploadedForDoc.add(attachment.path); + if (!deps.vault.readBinary) { + const message = `Cannot upload ${attachment.path}: this vault adapter does not support binary reads.`; + attachmentWarnings.push(message); + rows.push({ path: attachment.path, status: "warning", message }); + continue; + } + try { + const bytes = await deps.vault.readBinary(attachment.path); + await uploadAttachmentWithRetry(deps.api, remote.id, basename(attachment.path), bytes, mimeTypeForPath(attachment.path)); + attachmentsUploaded += 1; + } catch (error) { + const message = `Could not upload ${attachment.path}: ${error instanceof Error ? error.message : "unknown error"}`; + attachmentWarnings.push(message); + rows.push({ path: attachment.path, status: "warning", message }); + } + } + } + + return { + ...preview, + foldersCreated, + documentsCreated, + documentsSkipped, + attachmentsUploaded, + attachmentWarnings, + rows, + }; +} + +export function extractAttachmentRefs(markdown: string): string[] { + const refs = new Set(); + const obsidianEmbed = /!\[\[([^\]#|]+)(?:[#|][^\]]*)?\]\]/g; + const markdownImage = /!\[[^\]]*]\((?![a-z][a-z0-9+.-]*:)([^)\s]+)(?:\s+"[^"]*")?\)/gi; + + for (const match of markdown.matchAll(obsidianEmbed)) { + if (match[1]) refs.add(match[1]); + } + for (const match of markdown.matchAll(markdownImage)) { + if (match[1]) refs.add(decodeURIComponent(match[1])); + } + return [...refs]; +} + +export function slugify(value: string): string { + const slug = value + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .replace(/\.md$/i, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return slug || "untitled"; +} + +function splitImportableFiles(files: VaultImportFile[]): ImportableFiles { + let skipped = 0; + const notes: VaultImportFile[] = []; + const attachments: VaultImportFile[] = []; + for (const file of files) { + const path = normalizePath(file.path); + if (isIgnoredPath(path)) { + skipped += 1; + continue; + } + if (file.extension.toLowerCase() === "md") { + if (path.endsWith(".conflict.md")) skipped += 1; + else notes.push({ ...file, path }); + } else { + attachments.push({ ...file, path }); + } + } + notes.sort((a, b) => a.path.localeCompare(b.path)); + attachments.sort((a, b) => a.path.localeCompare(b.path)); + return { notes, attachments, skipped }; +} + +function isIgnoredPath(path: string): boolean { + return path.startsWith(".obsidian/") || path.startsWith(".trash/") || path.startsWith(".git/"); +} + +function buildAttachmentIndex(files: VaultImportFile[]) { + const byPath = new Map(); + const byName = new Map(); + for (const file of files) { + byPath.set(file.path, file); + const list = byName.get(file.name) ?? []; + list.push(file); + byName.set(file.name, list); + } + return { byPath, byName }; +} + +function resolveAttachmentRef( + ref: string, + notePath: string, + index: ReturnType, +): VaultImportFile | null { + const cleanRef = normalizePath(ref.replace(/^<|>$/g, "")); + const noteDir = dirname(notePath); + const candidates = [ + normalizePath(`${noteDir}/${cleanRef}`), + cleanRef, + ]; + for (const candidate of candidates) { + const found = index.byPath.get(candidate); + if (found) return found; + } + const byName = index.byName.get(basename(cleanRef)); + if (byName?.length) return byName[0] ?? null; + return null; +} + +function remotePathForNote(path: string, targetRootSlug: string): string { + const localDir = dirname(path) + .split("/") + .filter(Boolean) + .map(slugify) + .join("/"); + const docSlug = slugify(basename(path)); + return [targetRootSlug, localDir, `${docSlug}.md`].filter(Boolean).join("/"); +} + +function frontmatterTitle(content: string): string | null { + if (!content.startsWith("---\n")) return null; + const end = content.indexOf("\n---", 4); + if (end === -1) return null; + const raw = content.slice(4, end); + for (const line of raw.split("\n")) { + const match = line.match(/^title:\s*(.+)$/i); + if (!match?.[1]) continue; + return match[1].trim().replace(/^['"]|['"]$/g, "") || null; + } + return null; +} + +async function uploadAttachmentWithRetry( + api: Pick, + documentId: string, + name: string, + bytes: ArrayBuffer, + mimeType: string, +): Promise { + try { + await api.uploadAttachment(documentId, name, bytes, mimeType); + } catch (firstError) { + try { + await api.uploadAttachment(documentId, name, bytes, mimeType); + } catch { + throw firstError; + } + } +} + +function folderFromCreate(id: string, parentFolderId: string | null, name: string, slug: string, path: string): RemoteFolder { + return { + id, + parentFolderId, + name, + slug, + path: trimSlashes(path), + permission: "manager", + }; +} + +function metaFromImportedRemote(remote: { id: string; path: string; title: string; version: string | null; checksum: string | null; permission: ServerMetaEntry["permission"]; updatedAt: string }, localPath: string): ServerMetaEntry { + if (!remote.version || !remote.checksum) throw new Error("Imported document is missing version metadata."); + return { + documentId: remote.id, + localPath, + remotePath: remote.path, + title: remote.title, + baseVersion: remote.version, + checksum: remote.checksum, + permission: remote.permission, + updatedAt: remote.updatedAt, + }; +} + +function mimeTypeForPath(path: string): string { + const ext = path.split(".").pop()?.toLowerCase(); + if (ext === "png") return "image/png"; + if (ext === "jpg" || ext === "jpeg") return "image/jpeg"; + if (ext === "gif") return "image/gif"; + if (ext === "webp") return "image/webp"; + if (ext === "mp4") return "video/mp4"; + if (ext === "webm") return "video/webm"; + if (ext === "mov") return "video/quicktime"; + if (ext === "pdf") return "application/pdf"; + return "application/octet-stream"; +} + +function dirname(path: string): string { + const normalized = normalizePath(path); + const index = normalized.lastIndexOf("/"); + return index === -1 ? "" : normalized.slice(0, index); +} + +function basename(path: string): string { + return normalizePath(path).split("/").filter(Boolean).pop() ?? ""; +} + +function trimSlashes(path: string): string { + return path.replace(/^\/+|\/+$/g, ""); +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..51fe467 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,1291 @@ +import { + App, + ItemView, + Modal, + Notice, + Plugin, + PluginSettingTab, + Setting, + TFile, + WorkspaceLeaf, + normalizePath, +} from "obsidian"; +import { Editor } from "@tiptap/core"; +import StarterKit from "@tiptap/starter-kit"; +import Collaboration from "@tiptap/extension-collaboration"; +import Link from "@tiptap/extension-link"; +import Placeholder from "@tiptap/extension-placeholder"; +import TaskList from "@tiptap/extension-task-list"; +import TaskItem from "@tiptap/extension-task-item"; +import { Table } from "@tiptap/extension-table"; +import TableRow from "@tiptap/extension-table-row"; +import TableHeader from "@tiptap/extension-table-header"; +import TableCell from "@tiptap/extension-table-cell"; +import { marked } from "marked"; +import TurndownService from "turndown"; +import { gfm } from "turndown-plugin-gfm"; +import * as Y from "yjs"; +import { WebsocketProvider } from "y-websocket"; +import { PagedenApiClient, PagedenApiError } from "./api-client"; +import { ServerMetaStore } from "./metadata"; +import { + conflictSiblingPath, + downloadDocument, + pushOrCreateLocalDocument, + runBackgroundSyncPass, + type SyncPassSummary, + type VaultLike, +} from "./sync"; +import { createDebouncer, createSyncRunner } from "./runner"; +import { canonicalize, checksum } from "./checksum"; +import { buildVaultImportPreview, importVaultToPageden, type VaultImportFile, type VaultImportReport } from "./import-vault"; +import type { DeviceStartResponse, MeResponse, PagedenSettings, RemoteDocument, RemoteTree, SearchResult } from "./types"; + +const PUSH_DEBOUNCE_MS = 2000; +const REMOTE_WRITE_GUARD_MS = 1500; +const LIVE_VIEW_TYPE = "pageden-live-document"; + +const turndown = new TurndownService({ + bulletListMarker: "-", + codeBlockStyle: "fenced", + headingStyle: "atx", +}); +turndown.use(gfm); + +const DEFAULT_SETTINGS: PagedenSettings = { + serverUrl: "https://go.pageden.app", + token: "", + workspaceId: "", + remoteDocsFolder: "Remote Docs", + autoSyncEnabled: false, + autoSyncIntervalMinutes: 5, + userName: "", + workspaceName: "", +}; + +export default class PagedenPlugin extends Plugin { + settings: PagedenSettings = DEFAULT_SETTINGS; + private metaStore!: ServerMetaStore; + private statusBarEl?: HTMLElement; + private syncRunner!: ReturnType; + private pushDebouncer!: ReturnType; + private readonly applyingRemoteWrites = new Set(); + private syncIntervalId?: number; + private lastSummary?: SyncPassSummary; + + async onload(): Promise { + await this.loadSettings(); + this.metaStore = new ServerMetaStore(this.app.vault.adapter, this.pluginDir()); + + this.addSettingTab(new PagedenSettingTab(this.app, this)); + this.registerView(LIVE_VIEW_TYPE, (leaf) => new LiveDocumentView(leaf, this)); + + this.addCommand({ + id: "validate-connection", + name: "Validate connection", + callback: () => void this.validateConnection(), + }); + + this.addCommand({ + id: "browse-remote-documents", + name: "Browse remote documents", + callback: () => void this.openRemoteBrowser(), + }); + + this.addCommand({ + id: "search-remote-documents", + name: "Search remote documents", + callback: () => void this.openRemoteSearch(), + }); + + this.addCommand({ + id: "import-vault", + name: "Import this vault to Pageden", + callback: () => void this.openVaultImport(), + }); + + this.addCommand({ + id: "open-live-document", + name: "Open live document", + callback: () => void this.openLiveDocumentPicker(), + }); + + this.addCommand({ + id: "device-code-login", + name: "Log in with device code", + callback: () => void this.startDeviceLogin(), + }); + + this.addCommand({ + id: "push-active-document", + name: "Push active document", + checkCallback: (checking) => { + const file = this.app.workspace.getActiveFile(); + const canPush = file instanceof TFile && file.extension === "md"; + if (checking) return canPush; + if (file) void this.pushFile(file); + return true; + }, + }); + + this.addCommand({ + id: "download-folder", + name: "Download a Pageden folder", + callback: () => void this.openFolderDownload(), + }); + + this.addCommand({ + id: "download-all-documents", + name: "Download all Pageden documents", + callback: () => void this.downloadAllDocuments(), + }); + + this.addCommand({ + id: "resolve-conflict", + name: "Resolve conflict for this note", + checkCallback: (checking) => { + const file = this.app.workspace.getActiveFile(); + const canResolve = file instanceof TFile && file.extension === "md" && !file.path.endsWith(".conflict.md"); + if (checking) return canResolve; + if (file) void this.resolveConflict(file); + return true; + }, + }); + + // Background sync wiring. + this.statusBarEl = this.addStatusBarItem(); + this.syncRunner = createSyncRunner(() => this.runSyncPass()); + this.pushDebouncer = createDebouncer(PUSH_DEBOUNCE_MS); + + this.addCommand({ + id: "sync-now", + name: "Sync now", + callback: () => void this.syncRunner.run(), + }); + + this.registerEvent(this.app.vault.on("modify", (file) => this.onVaultFileChanged(file))); + this.registerEvent(this.app.vault.on("create", (file) => this.onVaultFileChanged(file))); + this.app.workspace.onLayoutReady(() => this.startAutoSync()); + } + + onunload(): void { + this.stopAutoSync(); + } + + // Start (or restart) the auto-sync interval. Safe to call repeatedly — e.g. when settings change. + startAutoSync(): void { + this.stopAutoSync(); + if (!this.settings.autoSyncEnabled) { + this.setStatusIdle(); + return; + } + const minutes = Math.max(1, Math.floor(Number(this.settings.autoSyncIntervalMinutes)) || DEFAULT_SETTINGS.autoSyncIntervalMinutes); + this.syncIntervalId = window.setInterval(() => void this.syncRunner.run(), minutes * 60_000); + this.registerInterval(this.syncIntervalId); + if (this.isConfigured()) void this.syncRunner.run(); + else this.setStatus("Pageden: not connected"); + } + + private stopAutoSync(): void { + if (this.syncIntervalId !== undefined) { + window.clearInterval(this.syncIntervalId); + this.syncIntervalId = undefined; + } + this.pushDebouncer?.cancelAll(); + } + + isConfigured(): boolean { + return Boolean(this.settings.serverUrl.trim() && this.settings.token.trim() && this.settings.workspaceId.trim()); + } + + // One full pull/push reconciliation pass. Serialised by syncRunner; never throws into Obsidian. + private async runSyncPass(): Promise { + if (!this.settings.autoSyncEnabled || !this.isConfigured()) return; + this.setStatus("Pageden: syncing\u2026"); + try { + const summary = await runBackgroundSyncPass(this.backgroundSyncDeps()); + this.lastSummary = summary; + this.renderSummary(summary); + } catch { + // Network/top-level failure: pause quietly, retry next tick. No noisy popups. + this.setStatus("Pageden: offline"); + } + } + + private onVaultFileChanged(file: unknown): void { + if (!this.settings.autoSyncEnabled || !this.isConfigured()) return; + if (!(file instanceof TFile) || file.extension !== "md") return; + const path = file.path; + if (path.endsWith(".conflict.md")) return; + if (this.applyingRemoteWrites.has(path)) return; // our own pull write — don't echo it back + this.pushDebouncer.schedule(path, () => void this.debouncedPush(path)); + } + + private async debouncedPush(path: string): Promise { + // Don't push during a full pass; reschedule so the edit is not dropped. + if (this.syncRunner.isRunning()) { + this.pushDebouncer.schedule(path, () => void this.debouncedPush(path)); + return; + } + try { + const meta = await this.metaStore.getByLocalPath(path); + if (meta?.permission === "viewer") return; + if (!meta && !isUnderRemoteDocsFolder(this.settings.remoteDocsFolder, path)) return; + // Don't auto-push while an unresolved conflict copy exists — wait for the user to resolve it. + if (await this.app.vault.adapter.exists(conflictSiblingPath(path))) return; + const localCanonical = canonicalize(await this.app.vault.adapter.read(path)); + // Checksum gate: identical to the last-synced content means a remote write or a no-op save, + // not a real edit — skip to avoid pull/push ping-pong (covers delayed modify events too). + if (meta && (await checksum(localCanonical)) === meta.checksum) return; + const result = await pushOrCreateLocalDocument(this.createSyncDeps(), path); + if (result.status === "conflict") this.setStatus("Pageden: conflict"); + else if (result.status === "pushed" || result.status === "created") this.setStatusIdle(); + } catch { + this.setStatus("Pageden: error"); + } + } + + private backgroundSyncDeps() { + const base = this.syncDeps(); + return { + ...base, + vault: this.guardedVault(base.vault), + workspaceId: this.settings.workspaceId, + localMarkdownPaths: async () => + this.app.vault + .getFiles() + .filter((file) => file.extension === "md" && isUnderRemoteDocsFolder(this.settings.remoteDocsFolder, file.path)) + .map((file) => file.path), + }; + } + + // Wrap vault writes so a background pull marks the path as remote-applied; the modify handler + // skips it (belt to the checksum gate's suspenders). + private guardedVault(base: VaultLike): VaultLike { + return { + ...base, + write: async (path: string, content: string) => { + this.applyingRemoteWrites.add(path); + try { + await base.write(path, content); + } finally { + window.setTimeout(() => this.applyingRemoteWrites.delete(path), REMOTE_WRITE_GUARD_MS); + } + }, + writeBinary: base.writeBinary + ? async (path: string, content: ArrayBuffer) => { + this.applyingRemoteWrites.add(path); + try { + await base.writeBinary?.(path, content); + } finally { + window.setTimeout(() => this.applyingRemoteWrites.delete(path), REMOTE_WRITE_GUARD_MS); + } + } + : undefined, + }; + } + + private setStatus(text: string): void { + this.statusBarEl?.setText(text); + } + + private setStatusIdle(): void { + const s = this.lastSummary; + if (s && s.conflicts) { + this.setStatus(`Pageden: ${s.conflicts} conflict${s.conflicts === 1 ? "" : "s"} \u2014 run "Resolve conflict" to fix`); + } else if (s && (s.created || s.pulled || s.pushed)) { + this.setStatus(`Pageden: synced (${s.created} created, ${s.pushed} sent, ${s.pulled} received)`); + } else { + this.setStatus("Pageden: up to date"); + } + } + + private renderSummary(s: SyncPassSummary): void { + if (s.errors) this.setStatus("Pageden: sync error \u2014 will retry"); + else if (s.conflicts) this.setStatus(`Pageden: ${s.conflicts} conflict${s.conflicts === 1 ? "" : "s"} \u2014 run "Resolve conflict" to fix`); + else this.setStatus(`Pageden: synced (${s.created} created, ${s.pushed} sent, ${s.pulled} received)`); + } + + async loadSettings(): Promise { + this.settings = { ...DEFAULT_SETTINGS, ...((await this.loadData()) as Partial | null) }; + } + + async saveSettings(): Promise { + await this.saveData(this.settings); + } + + api(): PagedenApiClient { + return new PagedenApiClient(this.settings.serverUrl, this.settings.token); + } + + liveBaseUrl(): string { + return `${this.settings.serverUrl.replace(/\/+$/, "")}/api/live`; + } + + publicApi(): PagedenApiClient { + return new PagedenApiClient(this.settings.serverUrl, ""); + } + + async validateConnection(): Promise { + try { + this.requireConfigured(); + await this.api().validate(); + new Notice("Pageden connection is valid."); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async openRemoteBrowser(): Promise { + try { + this.requireConfigured(); + const tree = await this.api().tree(this.settings.workspaceId); + new RemoteDocumentModal(this.app, tree, (doc) => void this.download(doc)).open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async openRemoteSearch(): Promise { + try { + this.requireConfigured(); + new RemoteSearchModal(this.app, this).open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async openVaultImport(): Promise { + try { + this.requireConfigured(); + const files = this.vaultImportFiles(); + const tree = await this.api().tree(this.settings.workspaceId); + new VaultImportModal(this.app, this, files, tree).open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async openLiveDocumentPicker(): Promise { + try { + this.requireConfigured(); + const tree = await this.api().tree(this.settings.workspaceId); + new RemoteDocumentModal(this.app, tree, (doc) => void this.openLiveDocument(doc), "Open live").open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async searchRemote(query: string): Promise { + const response = await this.api().search(this.settings.workspaceId, query); + return response.results; + } + + async downloadSearchResult(result: SearchResult): Promise { + await this.download({ + id: result.id, + folderId: "", + title: result.title, + path: result.path, + permission: result.permission, + version: null, + checksum: null, + }); + } + + async startDeviceLogin(): Promise { + try { + if (!this.settings.serverUrl.trim()) throw new Error("Set a Pageden server URL first."); + const request = await this.publicApi().deviceStart(); + new DeviceLoginModal(this.app, this, request).open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async pollDeviceLogin(deviceCode: string): Promise<"pending" | "done"> { + const result = await this.publicApi().devicePoll(deviceCode); + if (result.status === "pending") return "pending"; + if (result.status === "approved") { + this.settings.token = result.token; + try { + const me = await new PagedenApiClient(this.settings.serverUrl, result.token).me(); + this.settings.userName = me.user.name; + if (me.workspaces.length === 1) { + const ws = me.workspaces[0]!; + this.settings.workspaceId = ws.id; + this.settings.workspaceName = ws.name; + await this.saveSettings(); + this.startAutoSync(); + new Notice(`Connected! Signed in as ${me.user.name}, workspace "${ws.name}".`); + } else if (me.workspaces.length > 1) { + await this.saveSettings(); + new WorkspacePickerModal(this.app, this, me.workspaces).open(); + } else { + await this.saveSettings(); + this.startAutoSync(); + new Notice(`Connected as ${me.user.name}. No workspaces found — create one in Pageden first.`); + } + } catch { + await this.saveSettings(); + this.startAutoSync(); + new Notice("Login approved. Open Settings → Pageden to select a workspace."); + } + return "done"; + } + if (result.status === "denied") new Notice("Login was cancelled."); + else if (result.status === "expired") new Notice("Login code expired. Please try again."); + else new Notice(`Login ${result.status}.`); + return "done"; + } + + async download(doc: RemoteDocument): Promise { + try { + const result = await downloadDocument(this.syncDeps(), doc); + new Notice(`Downloaded ${result.localPath}`); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async openLiveDocument(doc: Pick): Promise { + try { + this.requireConfigured(); + if (doc.permission === "viewer") { + new Notice("Live editing requires editor or manager permission."); + return; + } + const leaf = this.app.workspace.getLeaf("tab"); + await leaf.setViewState({ type: LIVE_VIEW_TYPE, active: true }); + if (leaf.view instanceof LiveDocumentView) await leaf.view.openDocument(doc.id); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async pushFile(file: TFile): Promise { + try { + this.requireConfigured(); + const result = await pushOrCreateLocalDocument(this.createSyncDeps(), file.path); + if (result.status === "blocked_viewer") { + new Notice("This remote document is viewer-only, so it cannot be pushed."); + } else if (result.status === "conflict") { + new Notice( + `Your changes conflict with a newer server version.\nThe server version was saved as "${result.conflictPath}".\nUse the "Resolve conflict for this note" command to dismiss it.`, + 8000, + ); + } else { + new Notice(result.status === "created" ? "Created in Pageden." : "Pushed to Pageden."); + } + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async importVault(files: VaultImportFile[], targetRootName: string, onProgress?: (current: number, total: number) => void): Promise { + this.requireConfigured(); + return importVaultToPageden({ + api: this.api(), + vault: this.vaultAdapter(), + meta: this.metaStore, + workspaceId: this.settings.workspaceId, + files, + targetRootName, + onProgress, + }); + } + + async openFolderDownload(): Promise { + try { + this.requireConfigured(); + const tree = await this.api().tree(this.settings.workspaceId); + new FolderDownloadModal(this.app, this, tree).open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async downloadFolderDocuments(folderId: string, folderName: string, tree: RemoteTree): Promise { + try { + const docs = tree.documents.filter((d) => d.folderId === folderId); + if (docs.length === 0) { + new Notice(`No documents found in "${folderName}".`); + return; + } + new Notice(`Downloading ${docs.length} note${docs.length === 1 ? "" : "s"} from "${folderName}"…`, 3000); + let downloaded = 0; + let failed = 0; + for (const doc of docs) { + try { + await downloadDocument(this.syncDeps(), doc); + downloaded++; + } catch { + failed++; + } + } + new Notice( + failed > 0 + ? `Downloaded ${downloaded} of ${docs.length} notes from "${folderName}". ${failed} failed.` + : `Downloaded ${downloaded} note${downloaded === 1 ? "" : "s"} from "${folderName}".`, + ); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async downloadAllDocuments(): Promise { + try { + this.requireConfigured(); + const tree = await this.api().tree(this.settings.workspaceId); + if (tree.documents.length === 0) { + new Notice("No documents found in your Pageden workspace."); + return; + } + new Notice(`Downloading ${tree.documents.length} note${tree.documents.length === 1 ? "" : "s"}…`, 3000); + let downloaded = 0; + let failed = 0; + for (const doc of tree.documents) { + try { + await downloadDocument(this.syncDeps(), doc); + downloaded++; + } catch { + failed++; + } + } + new Notice( + failed > 0 + ? `Downloaded ${downloaded} of ${tree.documents.length} notes. ${failed} failed.` + : `Downloaded all ${downloaded} note${downloaded === 1 ? "" : "s"}.`, + ); + } catch (error) { + new Notice(errorMessage(error)); + } + } + + async resolveConflict(file: TFile): Promise { + const conflictPath = conflictSiblingPath(file.path); + if (!(await this.app.vault.adapter.exists(conflictPath))) { + new Notice("No conflict file found for this note."); + return; + } + await this.app.vault.adapter.remove(conflictPath); + new Notice("Conflict resolved — the server copy has been removed."); + } + + private syncDeps() { + return { + api: this.api(), + vault: this.vaultAdapter(), + meta: this.metaStore, + remoteDocsFolder: this.settings.remoteDocsFolder, + }; + } + + private createSyncDeps() { + return { + ...this.syncDeps(), + workspaceId: this.settings.workspaceId, + }; + } + + private vaultAdapter(): VaultLike { + const adapter = this.app.vault.adapter; + return { + read: (path) => adapter.read(path), + write: (path, content) => adapter.write(path, content), + readBinary: (path) => adapter.readBinary(path), + writeBinary: (path, content) => adapter.writeBinary(path, content), + exists: (path) => adapter.exists(path), + mkdir: (path) => adapter.mkdir(path), + }; + } + + private vaultImportFiles(): VaultImportFile[] { + return this.app.vault.getFiles().map((file) => ({ + path: file.path, + name: file.name, + extension: file.extension, + })); + } + + private pluginDir(): string { + return this.manifest.dir ?? `.obsidian/plugins/${this.manifest.id}`; + } + + private requireConfigured(): void { + if (!this.settings.serverUrl.trim()) throw new Error("Please set your Pageden server URL in settings."); + if (!this.settings.token.trim()) throw new Error("Please connect to Pageden first. Open Settings → Pageden and click \"Connect to Pageden\"."); + if (!this.settings.workspaceId.trim()) throw new Error("Please select a workspace. Open Settings → Pageden and click \"Connect to Pageden\"."); + } +} + +class LiveDocumentView extends ItemView { + private editor?: Editor; + private provider?: WebsocketProvider; + private ydoc?: Y.Doc; + private documentId?: string; + private baseVersion = ""; + private lastSavedMarkdown = ""; + private statusEl?: HTMLElement; + private titleEl?: HTMLElement; + private pathEl?: HTMLElement; + private saveTimer?: number; + private saving = false; + private saveAgain = false; + + constructor( + leaf: WorkspaceLeaf, + private readonly plugin: PagedenPlugin, + ) { + super(leaf); + } + + getViewType(): string { + return LIVE_VIEW_TYPE; + } + + getDisplayText(): string { + return this.titleEl?.getText() || "Pageden live document"; + } + + async openDocument(documentId: string): Promise { + this.destroyLiveSession(); + this.documentId = documentId; + this.contentEl.empty(); + this.contentEl.addClass("pageden-live-view"); + + const header = this.contentEl.createDiv({ cls: "pageden-live-header" }); + const titleWrap = header.createDiv(); + this.titleEl = titleWrap.createEl("h2", { text: "Loading..." }); + this.pathEl = titleWrap.createEl("p", { text: "Connecting to Pageden" }); + this.statusEl = header.createEl("span", { text: "Connecting", cls: "pageden-live-status" }); + + const toolbar = this.contentEl.createDiv({ cls: "pageden-live-toolbar" }); + const editorEl = this.contentEl.createDiv({ cls: "pageden-live-editor" }); + + const remote = await this.plugin.api().document(documentId); + if (remote.permission === "viewer") throw new Error("Live editing requires editor or manager permission."); + this.baseVersion = remote.version ?? ""; + this.lastSavedMarkdown = remote.content; + this.titleEl.setText(remote.title); + this.pathEl.setText(remote.path); + + this.ydoc = new Y.Doc(); + this.provider = new WebsocketProvider(this.plugin.liveBaseUrl(), documentId, this.ydoc, { + params: { token: this.plugin.settings.token }, + connect: true, + disableBc: true, + }); + + this.editor = new Editor({ + element: editorEl, + extensions: [ + StarterKit.configure({ link: false, undoRedo: false }), + Collaboration.configure({ document: this.ydoc }), + Link.configure({ autolink: true, openOnClick: false, protocols: ["http", "https", "mailto"] }), + Placeholder.configure({ placeholder: "Start writing..." }), + TaskList, + TaskItem.configure({ nested: true }), + Table.configure({ resizable: true }), + TableRow, + TableHeader, + TableCell, + ], + editorProps: { + attributes: { class: "pageden-live-prosemirror" }, + }, + onUpdate: ({ editor }) => { + const markdown = htmlToMarkdown(editor.getHTML()); + if (markdown !== this.lastSavedMarkdown) this.scheduleSave(); + }, + }); + + this.renderToolbar(toolbar); + this.provider.on("status", (event: { status: string }) => this.setStatus(event.status === "connected" ? "Live" : "Reconnecting")); + this.provider.on("sync", (synced: boolean) => { + if (synced) this.seedInitialContent(remote.content); + }); + if (this.provider.synced) this.seedInitialContent(remote.content); + } + + async onClose(): Promise { + this.destroyLiveSession(); + } + + private renderToolbar(toolbar: HTMLElement): void { + const buttons: Array<[string, () => void]> = [ + ["B", () => this.editor?.chain().focus().toggleBold().run()], + ["I", () => this.editor?.chain().focus().toggleItalic().run()], + ["H1", () => this.editor?.chain().focus().toggleHeading({ level: 1 }).run()], + ["H2", () => this.editor?.chain().focus().toggleHeading({ level: 2 }).run()], + ["List", () => this.editor?.chain().focus().toggleBulletList().run()], + ["Task", () => this.editor?.chain().focus().toggleTaskList().run()], + ["Save", () => void this.persist()], + ]; + for (const [label, action] of buttons) { + const button = toolbar.createEl("button", { text: label, cls: "pageden-live-button" }); + button.addEventListener("click", action); + } + } + + private seedInitialContent(markdown: string): void { + if (!this.editor || this.editor.getText().trim()) return; + this.editor.commands.setContent(markdownToHtml(markdown), { emitUpdate: true }); + } + + private scheduleSave(): void { + if (this.saving) { + this.saveAgain = true; + return; + } + if (this.saveTimer !== undefined) window.clearTimeout(this.saveTimer); + this.saveTimer = window.setTimeout(() => void this.persist(), 1500); + } + + private async persist(): Promise { + if (!this.editor || !this.documentId) return; + if (this.saving) { + this.saveAgain = true; + return; + } + if (this.saveTimer !== undefined) { + window.clearTimeout(this.saveTimer); + this.saveTimer = undefined; + } + const content = htmlToMarkdown(this.editor.getHTML()); + if (content === this.lastSavedMarkdown) return; + this.saving = true; + this.setStatus("Saving"); + try { + const result = await this.plugin.api().push(this.documentId, { + baseVersion: this.baseVersion, + checksum: await checksum(content), + content, + }); + this.baseVersion = result.version; + this.lastSavedMarkdown = content; + this.setStatus("Saved"); + } catch (error) { + if (error instanceof PagedenApiError && error.status === 409 && error.currentVersion) { + this.baseVersion = error.currentVersion; + this.saving = false; + await this.persist(); + return; + } + this.setStatus("Save failed"); + throw error; + } finally { + this.saving = false; + if (this.saveAgain) { + this.saveAgain = false; + this.scheduleSave(); + } + } + } + + private setStatus(status: string): void { + this.statusEl?.setText(status); + } + + private destroyLiveSession(): void { + if (this.saveTimer !== undefined) { + window.clearTimeout(this.saveTimer); + this.saveTimer = undefined; + } + this.editor?.destroy(); + this.provider?.destroy(); + this.ydoc?.destroy(); + this.editor = undefined; + this.provider = undefined; + this.ydoc = undefined; + this.saveAgain = false; + } +} + +class PagedenSettingTab extends PluginSettingTab { + constructor(app: App, private readonly plugin: PagedenPlugin) { + super(app, plugin); + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl("h2", { text: "Pageden" }); + + const isConnected = this.plugin.isConfigured(); + + if (!isConnected) { + containerEl.createEl("p", { + text: "Connect your Obsidian vault to Pageden to sync notes and collaborate with your team.", + cls: "setting-item-description", + }); + + new Setting(containerEl) + .setName("Connect your vault") + .setDesc("Click the button below. A login page will open in your browser — approve it there and you're done.") + .addButton((btn) => + btn + .setButtonText("Connect to Pageden") + .setCta() + .onClick(() => void this.plugin.startDeviceLogin()), + ); + + containerEl.createEl("h3", { text: "Server" }); + + new Setting(containerEl) + .setName("Server URL") + .setDesc("The address of your Pageden server.") + .addText((text) => + text + .setPlaceholder("https://app.example.com") + .setValue(this.plugin.settings.serverUrl) + .onChange(async (value) => { + this.plugin.settings.serverUrl = value.trim(); + await this.plugin.saveSettings(); + }), + ); + } else { + const displayName = this.plugin.settings.userName || "your account"; + const displayWs = this.plugin.settings.workspaceName || this.plugin.settings.workspaceId; + + new Setting(containerEl) + .setName(`Signed in as ${displayName}`) + .setDesc(`Workspace: ${displayWs}`) + .addButton((btn) => + btn.setButtonText("Change workspace").onClick(() => void this.changeWorkspace()), + ) + .addButton((btn) => + btn.setButtonText("Disconnect").onClick(async () => { + this.plugin.settings.token = ""; + this.plugin.settings.workspaceId = ""; + this.plugin.settings.userName = ""; + this.plugin.settings.workspaceName = ""; + await this.plugin.saveSettings(); + this.plugin.startAutoSync(); + this.display(); + }), + ); + + containerEl.createEl("h3", { text: "Sync" }); + + new Setting(containerEl) + .setName("Background sync") + .setDesc("Automatically pull remote updates and push local edits.") + .addToggle((toggle) => + toggle.setValue(this.plugin.settings.autoSyncEnabled).onChange(async (value) => { + this.plugin.settings.autoSyncEnabled = value; + await this.plugin.saveSettings(); + this.plugin.startAutoSync(); + }), + ); + + new Setting(containerEl) + .setName("Sync interval (minutes)") + .setDesc("How often background sync runs. Minimum 1 minute.") + .addText((text) => + text + .setPlaceholder("5") + .setValue(String(this.plugin.settings.autoSyncIntervalMinutes)) + .onChange(async (value) => { + const minutes = Math.max(1, Math.floor(Number(value)) || DEFAULT_SETTINGS.autoSyncIntervalMinutes); + this.plugin.settings.autoSyncIntervalMinutes = minutes; + await this.plugin.saveSettings(); + this.plugin.startAutoSync(); + }), + ); + + new Setting(containerEl) + .setName("Local folder") + .setDesc("Folder in your vault where downloaded documents are stored.") + .addText((text) => + text + .setPlaceholder("Remote Docs") + .setValue(this.plugin.settings.remoteDocsFolder) + .onChange(async (value) => { + this.plugin.settings.remoteDocsFolder = normalizePath(value.trim() || DEFAULT_SETTINGS.remoteDocsFolder); + await this.plugin.saveSettings(); + }), + ); + + const details = containerEl.createEl("details"); + details.createEl("summary", { text: "Advanced" }); + const adv = details.createDiv(); + + new Setting(adv) + .setName("Server URL") + .addText((text) => + text + .setPlaceholder("https://app.example.com") + .setValue(this.plugin.settings.serverUrl) + .onChange(async (value) => { + this.plugin.settings.serverUrl = value.trim(); + await this.plugin.saveSettings(); + this.plugin.startAutoSync(); + }), + ); + + new Setting(adv) + .setName("Connection") + .addButton((btn) => + btn.setButtonText("Test connection").onClick(() => void this.plugin.validateConnection()), + ) + .addButton((btn) => + btn.setButtonText("Sign in again").onClick(() => void this.plugin.startDeviceLogin()), + ); + } + } + + private async changeWorkspace(): Promise { + try { + const me = await this.plugin.api().me(); + if (me.workspaces.length === 0) { + new Notice("No workspaces found on this account."); + return; + } + new WorkspacePickerModal(this.app, this.plugin, me.workspaces, () => this.display()).open(); + } catch (error) { + new Notice(errorMessage(error)); + } + } +} + +class RemoteDocumentModal extends Modal { + constructor( + app: App, + private readonly tree: RemoteTree, + private readonly onPick: (doc: RemoteDocument) => void, + private readonly buttonText = "Download", + ) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "Pageden documents" }); + const visibleDocs = this.tree.documents.filter((doc) => doc.permission !== "viewer" || doc.version); + if (visibleDocs.length === 0) { + contentEl.createEl("p", { text: "No remote documents are available." }); + return; + } + for (const doc of visibleDocs) { + new Setting(contentEl) + .setName(doc.title) + .setDesc(doc.permission === "viewer" ? `${doc.path} · read only` : doc.path) + .addButton((button) => + button.setButtonText(this.buttonText).onClick(() => { + this.close(); + this.onPick(doc); + }), + ); + } + } +} + +class RemoteSearchModal extends Modal { + private query = ""; + private resultsEl?: HTMLElement; + + constructor(app: App, private readonly plugin: PagedenPlugin) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "Search Pageden" }); + new Setting(contentEl) + .setName("Query") + .addText((text) => + text + .setPlaceholder("Search remote documents") + .onChange((value) => { + this.query = value; + }), + ) + .addButton((button) => + button.setButtonText("Search").onClick(() => void this.runSearch()), + ); + this.resultsEl = contentEl.createDiv(); + } + + private async runSearch(): Promise { + if (!this.resultsEl) return; + this.resultsEl.empty(); + const q = this.query.trim(); + if (!q) { + this.resultsEl.createEl("p", { text: "Enter a search query." }); + return; + } + try { + const results = await this.plugin.searchRemote(q); + if (results.length === 0) { + this.resultsEl.createEl("p", { text: "No results." }); + return; + } + for (const result of results) { + new Setting(this.resultsEl) + .setName(result.title) + .setDesc(result.permission === "viewer" ? `${result.path} · read only` : result.path) + .addButton((button) => + button.setButtonText("Download").onClick(() => { + this.close(); + void this.plugin.downloadSearchResult(result); + }), + ); + } + } catch (error) { + this.resultsEl.createEl("p", { text: errorMessage(error) }); + } + } +} + +class VaultImportModal extends Modal { + private targetRootName = "Imported from Obsidian"; + private previewEl?: HTMLElement; + private statusEl?: HTMLElement; + + constructor( + app: App, + private readonly plugin: PagedenPlugin, + private readonly files: VaultImportFile[], + private readonly remoteTree: RemoteTree, + ) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "Import Obsidian vault" }); + contentEl.createEl("p", { + text: "Upload this vault's notes into Pageden. Existing remote documents are skipped, never overwritten.", + }); + + new Setting(contentEl) + .setName("Pageden folder") + .setDesc("Imported folders and notes will be created under this top-level folder.") + .addText((text) => + text + .setPlaceholder("Imported from Obsidian") + .setValue(this.targetRootName) + .onChange((value) => { + this.targetRootName = value.trim() || "Imported from Obsidian"; + this.renderPreview(); + }), + ); + + this.previewEl = contentEl.createDiv(); + this.statusEl = contentEl.createEl("p"); + this.renderPreview(); + + new Setting(contentEl) + .addButton((button) => + button + .setButtonText("Import vault") + .setCta() + .onClick(async () => { + button.setDisabled(true).setButtonText("Importing..."); + await this.runImport(); + button.setDisabled(false).setButtonText("Import vault"); + }), + ) + .addButton((button) => button.setButtonText("Cancel").onClick(() => this.close())); + } + + private renderPreview(): void { + if (!this.previewEl) return; + this.previewEl.empty(); + const preview = buildVaultImportPreview(this.files, this.remoteTree, this.targetRootName); + this.previewEl.createEl("h3", { text: "Preview" }); + const list = this.previewEl.createEl("ul"); + list.createEl("li", { text: `${preview.notes} Markdown note${preview.notes === 1 ? "" : "s"} ready to import.` }); + list.createEl("li", { text: `${preview.attachments} attachment${preview.attachments === 1 ? "" : "s"} detected.` }); + list.createEl("li", { text: `${preview.skipped} internal or unsupported file${preview.skipped === 1 ? "" : "s"} skipped.` }); + if (preview.conflicts.length) { + list.createEl("li", { text: `${preview.conflicts.length} remote document${preview.conflicts.length === 1 ? "" : "s"} already exist and will be skipped.` }); + } + this.statusEl?.setText(""); + } + + private async runImport(): Promise { + try { + this.statusEl?.setText("Starting import…"); + const report = await this.plugin.importVault(this.files, this.targetRootName, (current, total) => { + this.statusEl?.setText(`Importing note ${current} of ${total}…`); + }); + const warnings = report.attachmentWarnings.length ? ` ${report.attachmentWarnings.length} attachment warning${report.attachmentWarnings.length === 1 ? "" : "s"}.` : ""; + this.statusEl?.setText( + `Done! Created ${report.foldersCreated} folder${report.foldersCreated === 1 ? "" : "s"}, imported ${report.documentsCreated} note${report.documentsCreated === 1 ? "" : "s"}, uploaded ${report.attachmentsUploaded} attachment${report.attachmentsUploaded === 1 ? "" : "s"}.${warnings}`, + ); + new Notice("Vault import complete."); + } catch (error) { + const message = errorMessage(error); + this.statusEl?.setText(message); + new Notice(message); + } + } +} + +class DeviceLoginModal extends Modal { + private intervalId?: number; + private statusEl?: HTMLElement; + + constructor( + app: App, + private readonly plugin: PagedenPlugin, + private readonly request: DeviceStartResponse, + ) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "Connect to Pageden" }); + contentEl.createEl("p", { + text: "A login page should have opened in your browser. Enter this code there to approve the connection:", + }); + contentEl.createEl("h3", { text: this.request.userCode, cls: "pageden-device-code" }); + contentEl.createEl("p", { + text: "If the browser did not open automatically, use the button below.", + cls: "setting-item-description", + }); + new Setting(contentEl) + .addButton((button) => + button.setButtonText("Open browser").onClick(() => window.open(this.request.verificationUri)), + ) + .addButton((button) => + button.setButtonText("Copy code").onClick(() => void navigator.clipboard?.writeText(this.request.userCode)), + ) + .addButton((button) => + button.setButtonText("Check now").onClick(() => void this.poll()), + ); + this.statusEl = contentEl.createEl("p", { text: "Waiting for you to approve in the browser…" }); + const intervalMs = Math.max(1, this.request.interval) * 1000; + this.intervalId = window.setInterval(() => void this.poll(), intervalMs); + window.open(this.request.verificationUri); + } + + onClose(): void { + if (this.intervalId !== undefined) { + window.clearInterval(this.intervalId); + this.intervalId = undefined; + } + } + + private async poll(): Promise { + try { + const status = await this.plugin.pollDeviceLogin(this.request.deviceCode); + if (status === "pending") { + this.statusEl?.setText("Waiting for approval..."); + } else { + this.close(); + } + } catch (error) { + this.statusEl?.setText(errorMessage(error)); + } + } +} + +class WorkspacePickerModal extends Modal { + constructor( + app: App, + private readonly plugin: PagedenPlugin, + private readonly workspaces: MeResponse["workspaces"], + private readonly onSelect?: () => void, + ) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "Choose a workspace" }); + contentEl.createEl("p", { + text: "Select which Pageden workspace to sync with this vault.", + cls: "setting-item-description", + }); + for (const ws of this.workspaces) { + new Setting(contentEl) + .setName(ws.name) + .setDesc(ws.role === "admin" ? "You are an admin" : "Member") + .addButton((btn) => + btn + .setButtonText("Select") + .setCta() + .onClick(async () => { + this.plugin.settings.workspaceId = ws.id; + this.plugin.settings.workspaceName = ws.name; + await this.plugin.saveSettings(); + this.plugin.startAutoSync(); + this.close(); + new Notice(`Workspace set to "${ws.name}".`); + this.onSelect?.(); + }), + ); + } + } +} + +class FolderDownloadModal extends Modal { + constructor( + app: App, + private readonly plugin: PagedenPlugin, + private readonly tree: RemoteTree, + ) { + super(app); + } + + onOpen(): void { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: "Download a folder" }); + contentEl.createEl("p", { + text: "Choose a folder to download all its notes to your vault.", + cls: "setting-item-description", + }); + + const foldersWithDocs = this.tree.folders + .map((folder) => ({ folder, count: this.tree.documents.filter((d) => d.folderId === folder.id).length })) + .filter(({ count }) => count > 0) + .sort((a, b) => a.folder.path.localeCompare(b.folder.path)); + + if (foldersWithDocs.length === 0) { + contentEl.createEl("p", { text: "No folders with documents found in your workspace." }); + return; + } + + for (const { folder, count } of foldersWithDocs) { + new Setting(contentEl) + .setName(folder.name) + .setDesc(`${folder.path} · ${count} note${count === 1 ? "" : "s"}`) + .addButton((btn) => + btn.setButtonText("Download all").onClick(() => { + this.close(); + void this.plugin.downloadFolderDocuments(folder.id, folder.name, this.tree); + }), + ); + } + } +} + +function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message; + return "Pageden request failed."; +} + +function isUnderRemoteDocsFolder(remoteDocsFolder: string, path: string): boolean { + const root = normalizePath(remoteDocsFolder).replace(/\/+$/, ""); + const localPath = normalizePath(path); + return localPath === root || localPath.startsWith(`${root}/`); +} + +function markdownToHtml(markdown: string): string { + return marked.parse(markdown, { async: false }) as string; +} + +function htmlToMarkdown(html: string): string { + const markdown = turndown.turndown(html).trimEnd(); + return markdown ? `${markdown}\n` : ""; +} diff --git a/src/metadata.test.ts b/src/metadata.test.ts new file mode 100644 index 0000000..7d80930 --- /dev/null +++ b/src/metadata.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ServerMetaStore } from "./metadata"; + +class MemoryAdapter { + files = new Map(); + + async exists(path: string): Promise { + return this.files.has(path); + } + + async read(path: string): Promise { + const value = this.files.get(path); + if (value === undefined) throw new Error("missing"); + return value; + } + + async write(path: string, content: string): Promise { + this.files.set(path, content); + } +} + +describe("server metadata store", () => { + it("stores .server-meta.json keyed by documentId in the plugin dir", async () => { + const adapter = new MemoryAdapter(); + const store = new ServerMetaStore(adapter, ".obsidian/plugins/pageden"); + + await store.upsert({ + documentId: "doc1", + localPath: "Remote Docs/runbook.md", + remotePath: "/engineering/runbook", + title: "Runbook", + baseVersion: "rev1", + checksum: "sha256:one", + permission: "editor", + updatedAt: "2026-06-04T00:00:00.000Z", + }); + + expect(store.filePath).toBe(".obsidian/plugins/pageden/.server-meta.json"); + expect(await store.getByLocalPath("Remote Docs/runbook.md")).toMatchObject({ documentId: "doc1" }); + expect(JSON.parse(adapter.files.get(store.filePath) ?? "{}").documents.doc1.baseVersion).toBe("rev1"); + }); +}); + +describe("Obsidian community metadata", () => { + it("keeps the root manifest in sync with the plugin manifest", () => { + const root = resolve(fileURLToPath(new URL("../", import.meta.url))); + const pluginManifest = JSON.parse(readFileSync(resolve(root, "manifest.json"), "utf8")); + const rootManifest = JSON.parse(readFileSync(resolve(root, "manifest.json"), "utf8")); + const pluginVersions = JSON.parse(readFileSync(resolve(root, "versions.json"), "utf8")); + const rootVersions = JSON.parse(readFileSync(resolve(root, "versions.json"), "utf8")); + + expect(rootManifest).toEqual(pluginManifest); + expect(rootVersions).toEqual(pluginVersions); + expect(rootVersions[rootManifest.version]).toBe(rootManifest.minAppVersion); + }); +}); diff --git a/src/metadata.ts b/src/metadata.ts new file mode 100644 index 0000000..d2276bc --- /dev/null +++ b/src/metadata.ts @@ -0,0 +1,68 @@ +import type { DataAdapter } from "obsidian"; +import type { ServerMetaAttachmentEntry, ServerMetaEntry, ServerMetaFile } from "./types"; + +export class ServerMetaStore { + private readonly path: string; + + constructor( + private readonly adapter: Pick, + pluginDir: string, + ) { + this.path = `${pluginDir.replace(/\/+$/, "")}/.server-meta.json`; + } + + get filePath(): string { + return this.path; + } + + async read(): Promise { + if (!(await this.adapter.exists(this.path))) return { documents: {}, attachments: {} }; + const raw = await this.adapter.read(this.path); + const parsed = JSON.parse(raw) as Partial; + return { documents: parsed.documents ?? {}, attachments: parsed.attachments ?? {} }; + } + + async write(meta: ServerMetaFile): Promise { + await this.adapter.write(this.path, JSON.stringify(meta, null, 2)); + } + + async list(): Promise { + const meta = await this.read(); + return Object.values(meta.documents); + } + + async getByLocalPath(localPath: string): Promise { + const meta = await this.read(); + return Object.values(meta.documents).find((entry) => entry.localPath === localPath) ?? null; + } + + async upsert(entry: ServerMetaEntry): Promise { + const meta = await this.read(); + meta.documents[entry.documentId] = entry; + await this.write(meta); + } + + async listAttachments(): Promise { + const meta = await this.read(); + return Object.values(meta.attachments ?? {}); + } + + async listAttachmentsForDocument(documentId: string): Promise { + const meta = await this.read(); + return Object.values(meta.attachments ?? {}).filter((entry) => entry.documentId === documentId); + } + + async upsertAttachment(entry: ServerMetaAttachmentEntry): Promise { + const meta = await this.read(); + meta.attachments ??= {}; + meta.attachments[entry.attachmentId] = entry; + await this.write(meta); + } + + async removeAttachment(attachmentId: string): Promise { + const meta = await this.read(); + if (!meta.attachments) return; + delete meta.attachments[attachmentId]; + await this.write(meta); + } +} diff --git a/src/runner.test.ts b/src/runner.test.ts new file mode 100644 index 0000000..6070205 --- /dev/null +++ b/src/runner.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it, vi } from "vitest"; +import { createDebouncer, createSyncRunner } from "./runner"; + +describe("createSyncRunner", () => { + it("runs one pass at a time and coalesces overlapping triggers into a single follow-up", async () => { + let active = 0; + let maxActive = 0; + let calls = 0; + let release!: () => void; + const gate = new Promise((r) => (release = r)); + + const runner = createSyncRunner(async () => { + calls += 1; + active += 1; + maxActive = Math.max(maxActive, active); + if (calls === 1) await gate; // hold the first pass open while we trigger more + active -= 1; + }); + + const first = runner.run(); // starts, blocks on gate + void runner.run(); // in-flight → pending + void runner.run(); // in-flight → still just one pending + expect(runner.isRunning()).toBe(true); + + release(); + await first; + // wait microtasks for the coalesced follow-up pass to complete + await new Promise((r) => setTimeout(r, 0)); + + expect(maxActive).toBe(1); // never two passes at once + expect(calls).toBe(2); // first + exactly one coalesced follow-up + expect(runner.isRunning()).toBe(false); + }); +}); + +describe("createDebouncer", () => { + it("collapses repeated schedules for a key into one trailing call", () => { + vi.useFakeTimers(); + try { + const d = createDebouncer(2000); + const fn = vi.fn(); + d.schedule("a", fn); + d.schedule("a", fn); + d.schedule("a", fn); + vi.advanceTimersByTime(1999); + expect(fn).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(fn).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it("debounces independently per key and cancelAll stops pending timers", () => { + vi.useFakeTimers(); + try { + const d = createDebouncer(1000); + const a = vi.fn(); + const b = vi.fn(); + d.schedule("a", a); + d.schedule("b", b); + d.cancelAll(); + vi.advanceTimersByTime(2000); + expect(a).not.toHaveBeenCalled(); + expect(b).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/src/runner.ts b/src/runner.ts new file mode 100644 index 0000000..09ba775 --- /dev/null +++ b/src/runner.ts @@ -0,0 +1,65 @@ +// Small, framework-free concurrency helpers used by the background-sync engine. Kept pure so +// the loop-safety and debounce behaviour can be unit-tested without an Obsidian runtime. + +/** + * Serialises async passes so only one runs at a time. If `run()` is called while a pass is in + * flight, exactly one follow-up pass is queued (further calls collapse into that single pending + * run) — so overlapping triggers (startup + interval + a modify event) never race the API. + */ +export function createSyncRunner(pass: () => Promise): { run: () => Promise; isRunning: () => boolean } { + let inFlight = false; + let pending = false; + async function run(): Promise { + if (inFlight) { + pending = true; // collapse all overlapping triggers into a single follow-up + return; + } + inFlight = true; + try { + // Loop (not recursion) so sustained triggers can't build an unbounded promise chain. + do { + pending = false; + await pass(); + } while (pending); + } finally { + inFlight = false; + } + } + return { run, isRunning: () => inFlight }; +} + +/** + * Per-key debouncer: repeated `schedule(key, fn)` calls within `ms` collapse into a single + * trailing invocation of the most recent `fn` for that key. + */ +export function createDebouncer(ms: number): { + schedule: (key: string, fn: () => void) => void; + cancel: (key: string) => void; + cancelAll: () => void; +} { + const timers = new Map>(); + function cancel(key: string): void { + const existing = timers.get(key); + if (existing !== undefined) { + clearTimeout(existing); + timers.delete(key); + } + } + return { + schedule(key: string, fn: () => void): void { + cancel(key); + timers.set( + key, + setTimeout(() => { + timers.delete(key); + fn(); + }, ms), + ); + }, + cancel, + cancelAll(): void { + for (const timer of timers.values()) clearTimeout(timer); + timers.clear(); + }, + }; +} diff --git a/src/sync.test.ts b/src/sync.test.ts new file mode 100644 index 0000000..dfb559c --- /dev/null +++ b/src/sync.test.ts @@ -0,0 +1,503 @@ +import { webcrypto } from "node:crypto"; +import { describe, expect, it, vi } from "vitest"; +import { PagedenApiError } from "./api-client"; +import { + createRemoteDocumentFromLocal, + downloadDocument, + extractAttachmentPaths, + localPathForRemote, + pushLocalDocument, + pushOrCreateLocalDocument, + runBackgroundSyncPass, + syncDocumentAttachments, + syncLinkedDocument, + type VaultLike, +} from "./sync"; +import { checksum } from "./checksum"; +import type { Attachment, RemoteDocumentWithContent, ServerMetaAttachmentEntry, ServerMetaEntry } from "./types"; + +Object.defineProperty(globalThis, "crypto", { value: webcrypto, configurable: true }); + +class MemoryVault implements VaultLike { + files = new Map(); + binaryFiles = new Map(); + folders = new Set(); + + async read(path: string): Promise { + const value = this.files.get(path); + if (value === undefined) throw new Error("missing"); + return value; + } + + async write(path: string, content: string): Promise { + this.files.set(path, content); + } + + async readBinary(path: string): Promise { + const value = this.binaryFiles.get(path); + if (value === undefined) throw new Error("missing binary"); + return value; + } + + async writeBinary(path: string, content: ArrayBuffer): Promise { + this.binaryFiles.set(path, content); + } + + async exists(path: string): Promise { + return this.files.has(path) || this.binaryFiles.has(path) || this.folders.has(path); + } + + async mkdir(path: string): Promise { + this.folders.add(path); + } +} + +class MemoryMeta { + entries = new Map(); + attachments = new Map(); + + async list(): Promise { + return [...this.entries.values()]; + } + + async getByLocalPath(path: string): Promise { + return [...this.entries.values()].find((entry) => entry.localPath === path) ?? null; + } + + async upsert(entry: ServerMetaEntry): Promise { + this.entries.set(entry.documentId, entry); + } + + async listAttachmentsForDocument(documentId: string): Promise { + return [...this.attachments.values()].filter((entry) => entry.documentId === documentId); + } + + async upsertAttachment(entry: ServerMetaAttachmentEntry): Promise { + this.attachments.set(entry.attachmentId, entry); + } + + async removeAttachment(attachmentId: string): Promise { + this.attachments.delete(attachmentId); + } +} + +const remote: RemoteDocumentWithContent = { + id: "doc1", + workspaceId: "ws1", + folderId: "folder1", + title: "Runbook", + path: "/engineering/runbook", + permission: "editor", + version: "rev1", + checksum: "sha256:old", + content: "# Runbook\r\n", + updatedAt: "2026-06-04T00:00:00.000Z", +}; + +describe("plugin sync", () => { + it("maps remote paths into the configured local folder", () => { + expect(localPathForRemote("Remote Docs", "/engineering/runbook")).toBe("Remote Docs/engineering/runbook.md"); + expect(localPathForRemote("Remote Docs", "root.md")).toBe("Remote Docs/root.md"); + }); + + it("extracts markdown and Obsidian image attachment references", () => { + expect( + [...extractAttachmentPaths("![one](img/a.png)\n[download](files/report.pdf)\n![[b.jpg|thumb]]\n[doc](other.md)\n![remote](https://x.test/a.png)", "Remote Docs/e2e/doc.md")], + ).toEqual(["Remote Docs/e2e/img/a.png", "Remote Docs/e2e/files/report.pdf", "Remote Docs/e2e/b.jpg"]); + }); + + it("syncs attachments by downloading remote files, uploading changed local references, and deleting missing tracked files", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + const entry: ServerMetaEntry = { documentId: "doc1", localPath: "Remote Docs/e2e/doc.md", remotePath: "/e2e/doc", title: "Doc", baseVersion: "rev1", checksum: "sha256:doc", permission: "editor", updatedAt: "old" }; + await meta.upsert(entry); + await meta.upsertAttachment({ attachmentId: "old", documentId: "doc1", localPath: "Remote Docs/e2e/old.png", filename: "old.png", sha256: "oldsha", size: 1, contentType: "image/png", createdAt: "old" }); + const oldAttachment: Attachment = { id: "old", filename: "old.png", contentType: "image/png", size: 1, sha256: "oldsha", createdAt: "old" }; + const remoteAttachment: Attachment = { id: "remote", filename: "server.png", contentType: "image/png", size: 4, sha256: "remotesha", createdAt: "new" }; + const uploaded: Attachment = { id: "uploaded", filename: "local.png", contentType: "image/png", size: 5, sha256: "uploadsha", createdAt: "later" }; + await vault.write("Remote Docs/e2e/doc.md", "![local](local.png)\n"); + await vault.writeBinary("Remote Docs/e2e/local.png", new Uint8Array([1, 2, 3, 4, 5]).buffer); + const api = { + document: vi.fn(), + push: vi.fn(), + attachments: vi.fn().mockResolvedValue({ attachments: [oldAttachment, remoteAttachment] }), + downloadAttachment: vi.fn().mockResolvedValue(new Uint8Array([9, 9, 9, 9]).buffer), + uploadAttachment: vi.fn().mockResolvedValue(uploaded), + deleteAttachment: vi.fn().mockResolvedValue(undefined), + }; + + const result = await syncDocumentAttachments({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, entry, "![local](local.png)\n"); + + expect(result).toMatchObject({ downloaded: 1, uploaded: 1, deleted: 1 }); + expect(vault.binaryFiles.has("Remote Docs/e2e/server.png")).toBe(true); + expect(api.uploadAttachment).toHaveBeenCalledWith("doc1", "local.png", expect.any(ArrayBuffer), "image/png"); + expect(api.deleteAttachment).toHaveBeenCalledWith("old"); + expect(await meta.listAttachmentsForDocument("doc1")).toEqual( + expect.arrayContaining([ + expect.objectContaining({ attachmentId: "remote", localPath: "Remote Docs/e2e/server.png" }), + expect.objectContaining({ attachmentId: "uploaded", localPath: "Remote Docs/e2e/local.png" }), + ]), + ); + }); + + it("downloads a document, creates folders, canonicalizes content, and updates metadata", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + const api = { document: vi.fn().mockResolvedValue(remote), push: vi.fn() }; + + const result = await downloadDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, remote); + + expect(result.localPath).toBe("Remote Docs/engineering/runbook.md"); + expect(vault.folders.has("Remote Docs")).toBe(true); + expect(vault.folders.has("Remote Docs/engineering")).toBe(true); + expect(vault.files.get(result.localPath)).toBe("# Runbook\n"); + expect(await meta.getByLocalPath(result.localPath)).toMatchObject({ documentId: "doc1", baseVersion: "rev1" }); + }); + + it("pushes an editor document with baseVersion and advances metadata", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await meta.upsert({ documentId: "doc1", localPath: "Remote Docs/runbook.md", remotePath: "/runbook", title: "Runbook", baseVersion: "rev1", checksum: "sha256:old", permission: "editor", updatedAt: "old" }); + await vault.write("Remote Docs/runbook.md", "# Local\r\n"); + const api = { + document: vi.fn(), + push: vi.fn().mockResolvedValue({ id: "doc1", version: "rev2", checksum: "sha256:new", updatedAt: "new" }), + }; + + const result = await pushLocalDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, "Remote Docs/runbook.md"); + + expect(result.status).toBe("pushed"); + expect(api.push).toHaveBeenCalledWith("doc1", expect.objectContaining({ baseVersion: "rev1", content: "# Local\n" })); + expect(await meta.getByLocalPath("Remote Docs/runbook.md")).toMatchObject({ baseVersion: "rev2", checksum: "sha256:new" }); + }); + + it("creates a remote document for an unlinked local note and stores sync metadata", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/imported-from-web/hermes-deployment/ooo.md", "---\ntitle: OOO\n---\n\nTest\r\n"); + const createdRemote: RemoteDocumentWithContent = { + id: "doc-new", + workspaceId: "ws1", + folderId: "folder-hermes", + title: "OOO", + path: "imported-from-web/hermes-deployment/ooo.md", + permission: "editor", + version: "rev-new", + checksum: "sha256:new", + content: "---\ntitle: OOO\n---\n\nTest\n", + updatedAt: "2026-06-14T00:00:00.000Z", + }; + const api = { + tree: vi.fn().mockResolvedValue({ folders: [], documents: [] }), + createFolder: vi + .fn() + .mockResolvedValueOnce({ id: "folder-imported", path: "imported-from-web" }) + .mockResolvedValueOnce({ id: "folder-hermes", path: "imported-from-web/hermes-deployment" }), + createDocument: vi.fn().mockResolvedValue({ id: "doc-new", version: "rev-new", checksum: "sha256:new", path: "imported-from-web/hermes-deployment/ooo.md" }), + document: vi.fn().mockResolvedValue(createdRemote), + push: vi.fn(), + }; + + const result = await pushOrCreateLocalDocument( + { api, vault, meta, remoteDocsFolder: "Remote Docs", workspaceId: "ws1" }, + "Remote Docs/imported-from-web/hermes-deployment/ooo.md", + ); + + expect(result.status).toBe("created"); + expect(api.createFolder).toHaveBeenNthCalledWith(1, expect.objectContaining({ parentFolderId: null, slug: "imported-from-web" })); + expect(api.createFolder).toHaveBeenNthCalledWith(2, expect.objectContaining({ parentFolderId: "folder-imported", slug: "hermes-deployment" })); + expect(api.createDocument).toHaveBeenCalledWith( + expect.objectContaining({ + folderId: "folder-hermes", + title: "OOO", + slug: "ooo", + content: "---\ntitle: OOO\n---\n\nTest\n", + }), + ); + expect(await meta.getByLocalPath("Remote Docs/imported-from-web/hermes-deployment/ooo.md")).toMatchObject({ + documentId: "doc-new", + remotePath: "imported-from-web/hermes-deployment/ooo.md", + baseVersion: "rev-new", + }); + }); + + it("does not create over an existing remote path for an unlinked local note", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/team/plan.md", "# Local\n"); + const api = { + tree: vi.fn().mockResolvedValue({ + folders: [{ id: "folder-team", parentFolderId: null, name: "Team", slug: "team", path: "team", permission: "manager" }], + documents: [{ id: "doc-existing", folderId: "folder-team", title: "Plan", path: "team/plan.md", permission: "editor", version: "rev1", checksum: "sha256:x" }], + }), + createFolder: vi.fn(), + createDocument: vi.fn(), + document: vi.fn(), + push: vi.fn(), + }; + + await expect( + createRemoteDocumentFromLocal({ api, vault, meta, remoteDocsFolder: "Remote Docs", workspaceId: "ws1" }, "Remote Docs/team/plan.md"), + ).rejects.toThrow(/already exists/); + expect(api.createDocument).not.toHaveBeenCalled(); + }); + + it("blocks viewer-only pushes before calling the API", async () => { + const meta = new MemoryMeta(); + await meta.upsert({ documentId: "doc1", localPath: "Remote Docs/runbook.md", remotePath: "/runbook", title: "Runbook", baseVersion: "rev1", checksum: "sha256:old", permission: "viewer", updatedAt: "old" }); + const api = { document: vi.fn(), push: vi.fn() }; + + const result = await pushLocalDocument({ api, vault: new MemoryVault(), meta, remoteDocsFolder: "Remote Docs" }, "Remote Docs/runbook.md"); + + expect(result.status).toBe("blocked_viewer"); + expect(api.push).not.toHaveBeenCalled(); + }); + + it("keeps local edits and writes a conflict copy of the server version on 409", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await meta.upsert({ documentId: "doc1", localPath: "Remote Docs/runbook.md", remotePath: "/runbook", title: "Runbook", baseVersion: "rev1", checksum: "sha256:old", permission: "editor", updatedAt: "old" }); + await vault.write("Remote Docs/runbook.md", "# Local\n"); + const api = { + push: vi.fn().mockRejectedValue(new PagedenApiError(409, { error: "conflict", currentVersion: "rev2" })), + document: vi.fn().mockResolvedValue({ ...remote, content: "# Server\n", version: "rev2", checksum: "sha256:server" }), + }; + + const result = await pushLocalDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, "Remote Docs/runbook.md"); + + expect(result.status).toBe("conflict"); + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Local\n"); + expect(vault.files.get("Remote Docs/runbook.conflict.md")).toBe("# Server\n"); + expect(await meta.getByLocalPath("Remote Docs/runbook.md")).toMatchObject({ baseVersion: "rev2", checksum: "sha256:server" }); + }); +}); + +describe("background sync", () => { + const entry = (over: Partial = {}): ServerMetaEntry => ({ + documentId: "doc1", + localPath: "Remote Docs/runbook.md", + remotePath: "/runbook", + title: "Runbook", + baseVersion: "rev1", + checksum: "sha256:tracked", + permission: "editor", + updatedAt: "old", + ...over, + }); + + it("is a no-op when the server version matches and local has not diverged", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Same\n"); + const e = entry({ checksum: await checksum("# Same\n") }); + await meta.upsert(e); + const api = { document: vi.fn().mockResolvedValue({ ...remote, version: "rev1", content: "# Same\n" }), push: vi.fn() }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("unchanged"); + expect(api.push).not.toHaveBeenCalled(); + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Same\n"); + }); + + it("pulls server content (canonicalizing CRLF) and advances meta when the server moved", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Same\n"); + const e = entry({ checksum: await checksum("# Same\n") }); + await meta.upsert(e); + const api = { + document: vi.fn().mockResolvedValue({ ...remote, version: "rev2", checksum: "sha256:server2", content: "# Server v2\r\n" }), + push: vi.fn(), + }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("pulled"); + expect(api.push).not.toHaveBeenCalled(); + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Server v2\n"); // CRLF canonicalized + expect(await meta.getByLocalPath("Remote Docs/runbook.md")).toMatchObject({ baseVersion: "rev2", checksum: "sha256:server2" }); + }); + + it("pushes local edits when local diverged and the server has not moved", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Local edit\n"); + const e = entry({ checksum: "sha256:tracked" }); // tracked != checksum of local → diverged + await meta.upsert(e); + const api = { + document: vi.fn().mockResolvedValue({ ...remote, version: "rev1" }), // server unchanged + push: vi.fn().mockResolvedValue({ id: "doc1", version: "rev2", checksum: "sha256:new", updatedAt: "new" }), + }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("pushed"); + expect(api.push).toHaveBeenCalledWith("doc1", expect.objectContaining({ baseVersion: "rev1", content: "# Local edit\n" })); + }); + + it("writes a conflict copy and preserves local when the server moved AND local diverged", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Local edit\n"); + const e = entry({ checksum: "sha256:tracked" }); + await meta.upsert(e); + const api = { + document: vi.fn().mockResolvedValue({ ...remote, version: "rev2", checksum: "sha256:server", content: "# Server\n" }), + push: vi.fn().mockRejectedValue(new PagedenApiError(409, { error: "conflict", currentVersion: "rev2" })), + }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("conflict"); + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Local edit\n"); // never clobbered + expect(vault.files.get("Remote Docs/runbook.conflict.md")).toBe("# Server\n"); + }); + + it("reports a 404 document as gone and leaves the local file untouched", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Same\n"); + const e = entry({ checksum: await checksum("# Same\n") }); + await meta.upsert(e); + const api = { document: vi.fn().mockRejectedValue(new PagedenApiError(404, { error: "not_found" })), push: vi.fn() }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("gone"); + expect(api.push).not.toHaveBeenCalled(); + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Same\n"); + }); + + it("does NOT auto-push while an unresolved conflict copy exists (sticky conflict)", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Local edit\n"); + await vault.write("Remote Docs/runbook.conflict.md", "# Server side\n"); // unresolved conflict + const e = entry({ checksum: "sha256:tracked" }); // local diverged + await meta.upsert(e); + const api = { document: vi.fn().mockResolvedValue({ ...remote, version: "rev2" }), push: vi.fn() }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("conflict_pending"); + expect(api.push).not.toHaveBeenCalled(); + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Local edit\n"); + }); + + it("does not clobber a local edit that lands between the divergence check and the write (TOCTOU)", async () => { + class RaceVault extends MemoryVault { + reads = 0; + async read(path: string): Promise { + this.reads += 1; + // 1st read (divergence check): matches tracked. 2nd read (pre-write guard): user just edited. + return this.reads === 1 ? "# Same\n" : "# Edited mid-flight\n"; + } + } + const vault = new RaceVault(); + await vault.write("Remote Docs/runbook.md", "# Same\n"); + const meta = new MemoryMeta(); + const e = entry({ checksum: await checksum("# Same\n") }); + await meta.upsert(e); + const api = { document: vi.fn().mockResolvedValue({ ...remote, version: "rev2", checksum: "sha256:server2", content: "# Server v2\n" }), push: vi.fn() }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("conflict"); + expect(api.push).not.toHaveBeenCalled(); + expect(vault.files.get("Remote Docs/runbook.conflict.md")).toBe("# Server v2\n"); + // original local file was not overwritten by the pull + expect(vault.files.get("Remote Docs/runbook.md")).toBe("# Same\n"); + }); + + it("does not push when the server has downgraded the document to viewer", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/runbook.md", "# Local edit\n"); + const e = entry({ checksum: "sha256:tracked", permission: "editor" }); // diverged, meta says editor + await meta.upsert(e); + const api = { document: vi.fn().mockResolvedValue({ ...remote, version: "rev1", permission: "viewer" }), push: vi.fn() }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("blocked_viewer"); + expect(api.push).not.toHaveBeenCalled(); + expect(await meta.getByLocalPath("Remote Docs/runbook.md")).toMatchObject({ permission: "viewer" }); + }); + + it("does not resurrect a tracked file the user deleted locally", async () => { + const vault = new MemoryVault(); // file absent + const meta = new MemoryMeta(); + const e = entry({ checksum: "sha256:tracked" }); + await meta.upsert(e); + const api = { document: vi.fn().mockResolvedValue({ ...remote, version: "rev2", content: "# Server\n" }), push: vi.fn() }; + + const result = await syncLinkedDocument({ api, vault, meta, remoteDocsFolder: "Remote Docs" }, e); + + expect(result.status).toBe("missing_local"); + expect(vault.files.has("Remote Docs/runbook.md")).toBe(false); + expect(api.push).not.toHaveBeenCalled(); + }); + + it("runBackgroundSyncPass tallies results and isolates per-document errors", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/a.md", "# A\n"); + await meta.upsert(entry({ documentId: "docA", localPath: "Remote Docs/a.md", checksum: await checksum("# A\n") })); + await meta.upsert(entry({ documentId: "docB", localPath: "Remote Docs/b.md", checksum: await checksum("# B\n") })); + const api = { + document: vi.fn().mockImplementation((id: string) => { + if (id === "docA") return Promise.resolve({ ...remote, id: "docA", version: "rev1", content: "# A\n" }); + return Promise.reject(new PagedenApiError(500, { error: "server_error" })); + }), + push: vi.fn(), + }; + + const summary = await runBackgroundSyncPass({ api, vault, meta, remoteDocsFolder: "Remote Docs" }); + + expect(summary.unchanged).toBe(1); + expect(summary.errors).toBe(1); + }); + + it("runBackgroundSyncPass creates unlinked local notes under the remote docs folder", async () => { + const vault = new MemoryVault(); + const meta = new MemoryMeta(); + await vault.write("Remote Docs/team/new-plan.md", "# New plan\n"); + const createdRemote: RemoteDocumentWithContent = { + id: "doc-new", + workspaceId: "ws1", + folderId: "folder-team", + title: "New Plan", + path: "team/new-plan.md", + permission: "editor", + version: "rev-new", + checksum: "sha256:new", + content: "# New plan\n", + updatedAt: "2026-06-14T00:00:00.000Z", + }; + const api = { + document: vi.fn().mockResolvedValue(createdRemote), + push: vi.fn(), + tree: vi.fn().mockResolvedValue({ + folders: [{ id: "folder-team", parentFolderId: null, name: "Team", slug: "team", path: "team", permission: "manager" }], + documents: [], + }), + createFolder: vi.fn(), + createDocument: vi.fn().mockResolvedValue({ id: "doc-new", version: "rev-new", checksum: "sha256:new", path: "team/new-plan.md" }), + }; + + const summary = await runBackgroundSyncPass({ + api, + vault, + meta, + remoteDocsFolder: "Remote Docs", + workspaceId: "ws1", + localMarkdownPaths: async () => ["Remote Docs/team/new-plan.md"], + }); + + expect(summary.created).toBe(1); + expect(summary.errors).toBe(0); + expect(api.createDocument).toHaveBeenCalledWith(expect.objectContaining({ folderId: "folder-team", slug: "new-plan" })); + expect(await meta.getByLocalPath("Remote Docs/team/new-plan.md")).toMatchObject({ documentId: "doc-new", baseVersion: "rev-new" }); + }); +}); diff --git a/src/sync.ts b/src/sync.ts new file mode 100644 index 0000000..9f660c6 --- /dev/null +++ b/src/sync.ts @@ -0,0 +1,628 @@ +import { normalizePath } from "obsidian"; +import type { PagedenApiClient } from "./api-client"; +import { PagedenApiError } from "./api-client"; +import { canonicalize, checksum } from "./checksum"; +import type { Attachment, RemoteDocument, RemoteDocumentWithContent, RemoteFolder, RemoteTree, ServerMetaAttachmentEntry, ServerMetaEntry, WriteResult } from "./types"; + +export interface VaultLike { + read(path: string): Promise; + write(path: string, content: string): Promise; + readBinary?(path: string): Promise; + writeBinary?(path: string, content: ArrayBuffer): Promise; + exists(path: string): Promise; + mkdir(path: string): Promise; +} + +export interface MetaStoreLike { + list(): Promise; + getByLocalPath(path: string): Promise; + upsert(entry: ServerMetaEntry): Promise; + listAttachmentsForDocument?(documentId: string): Promise; + upsertAttachment?(entry: ServerMetaAttachmentEntry): Promise; + removeAttachment?(attachmentId: string): Promise; +} + +export interface SyncDeps { + api: Pick & + Partial>; + vault: VaultLike; + meta: MetaStoreLike; + remoteDocsFolder: string; +} + +export interface CreateRemoteDeps extends SyncDeps { + api: SyncDeps["api"] & Pick; + workspaceId: string; +} + +export interface BackgroundSyncDeps extends SyncDeps { + api: SyncDeps["api"] & Partial>; + workspaceId?: string; + localMarkdownPaths?: () => Promise; +} + +export interface DownloadResult { + localPath: string; + meta: ServerMetaEntry; + attachments: AttachmentSyncSummary; +} + +export interface PushResult { + status: "pushed" | "created" | "blocked_viewer" | "conflict"; + result?: WriteResult; + conflictPath?: string; + serverPath?: string; + meta?: ServerMetaEntry; +} + +export function localPathForRemote(remoteDocsFolder: string, remotePath: string): string { + const withoutLeadingSlash = remotePath.replace(/^\/+/, ""); + const withExtension = withoutLeadingSlash.endsWith(".md") ? withoutLeadingSlash : `${withoutLeadingSlash}.md`; + return normalizePath(`${remoteDocsFolder}/${withExtension}`); +} + +export async function ensureFolder(vault: VaultLike, folderPath: string): Promise { + const parts = normalizePath(folderPath).split("/").filter(Boolean); + let current = ""; + for (const part of parts) { + current = current ? `${current}/${part}` : part; + if (!(await vault.exists(current))) await vault.mkdir(current); + } +} + +export async function downloadDocument(deps: SyncDeps, doc: Pick): Promise { + const remote = await deps.api.document(doc.id); + const localPath = localPathForRemote(deps.remoteDocsFolder, remote.path); + const parent = localPath.split("/").slice(0, -1).join("/"); + if (parent) await ensureFolder(deps.vault, parent); + const content = canonicalize(remote.content); + await deps.vault.write(localPath, content); + const meta = metaFromRemote(remote, localPath); + await deps.meta.upsert(meta); + const attachments = hasAttachmentSupport(deps) ? await syncDocumentAttachments(deps, meta, content) : emptyAttachmentSummary(); + return { localPath, meta, attachments }; +} + +export async function pushLocalDocument(deps: SyncDeps, localPath: string): Promise { + const meta = await deps.meta.getByLocalPath(localPath); + if (!meta) throw new Error("This file is not linked to a Pageden document."); + if (meta.permission === "viewer") return { status: "blocked_viewer" }; + + const content = canonicalize(await deps.vault.read(localPath)); + try { + const result = await deps.api.push(meta.documentId, { + baseVersion: meta.baseVersion, + checksum: await checksum(content), + content, + }); + const nextMeta = { ...meta, baseVersion: result.version, checksum: result.checksum, updatedAt: result.updatedAt }; + await deps.meta.upsert(nextMeta); + if (hasAttachmentSupport(deps)) await syncDocumentAttachments(deps, nextMeta, content); + return { status: "pushed", result }; + } catch (error) { + if (error instanceof PagedenApiError && error.status === 409) { + const server = await deps.api.document(meta.documentId); + const conflictPath = await writeConflictFile(deps.vault, localPath, server); + await deps.meta.upsert({ ...meta, baseVersion: server.version ?? meta.baseVersion, checksum: server.checksum ?? meta.checksum, permission: server.permission, updatedAt: server.updatedAt }); + return { status: "conflict", conflictPath, serverPath: server.path }; + } + throw error; + } +} + +export async function pushOrCreateLocalDocument(deps: CreateRemoteDeps, localPath: string): Promise { + const meta = await deps.meta.getByLocalPath(localPath); + if (meta) return pushLocalDocument(deps, localPath); + return createRemoteDocumentFromLocal(deps, localPath); +} + +export async function createRemoteDocumentFromLocal(deps: CreateRemoteDeps, localPath: string): Promise { + const content = canonicalize(await deps.vault.read(localPath)); + const tree = await deps.api.tree(deps.workspaceId); + const target = targetPathForLocal(deps.remoteDocsFolder, localPath); + const existingPath = target.documentPath; + if (tree.documents.some((doc) => trimSlashes(doc.path) === existingPath)) { + throw new Error(`A Pageden document already exists at "${existingPath}". Download it first to link this local note safely.`); + } + + const folder = await ensureRemoteFolderPath(deps.api, deps.workspaceId, tree, target.folderSegments); + const created = await deps.api.createDocument({ + workspaceId: deps.workspaceId, + folderId: folder.id, + title: frontmatterTitle(content) ?? target.title, + slug: target.documentSlug, + content, + }); + const remote = await deps.api.document(created.id); + const meta = metaFromRemote(remote, localPath); + await deps.meta.upsert(meta); + if (hasAttachmentSupport(deps)) await syncDocumentAttachments(deps, meta, content); + return { + status: "created", + result: { id: remote.id, version: meta.baseVersion, checksum: meta.checksum, updatedAt: meta.updatedAt }, + meta, + }; +} + +async function writeConflictFile(vault: VaultLike, localPath: string, server: RemoteDocumentWithContent): Promise { + const stem = localPath.replace(/\.md$/i, ""); + const conflictPath = normalizePath(`${stem}.conflict.md`); + await vault.write(conflictPath, canonicalize(server.content)); + return conflictPath; +} + +function metaFromRemote(remote: RemoteDocumentWithContent, localPath: string): ServerMetaEntry { + if (!remote.version || !remote.checksum) { + throw new Error("Remote document is missing version metadata."); + } + return { + documentId: remote.id, + localPath, + remotePath: remote.path, + title: remote.title, + baseVersion: remote.version, + checksum: remote.checksum, + permission: remote.permission, + updatedAt: remote.updatedAt, + }; +} + +async function ensureRemoteFolderPath( + api: Pick, + workspaceId: string, + tree: RemoteTree, + folderSegments: string[], +): Promise { + const folderByPath = new Map(tree.folders.map((folder) => [trimSlashes(folder.path), folder])); + let parent: RemoteFolder | null = null; + let currentPath = ""; + + for (const segment of folderSegments) { + const slug = slugify(segment); + currentPath = currentPath ? `${currentPath}/${slug}` : slug; + const existing = folderByPath.get(currentPath); + if (existing) { + parent = existing; + continue; + } + const created = await api.createFolder({ + workspaceId, + parentFolderId: parent?.id ?? null, + name: segment, + slug, + }); + parent = { + id: created.id, + parentFolderId: parent?.id ?? null, + name: segment, + slug, + path: trimSlashes(created.path), + permission: "manager", + }; + folderByPath.set(currentPath, parent); + } + + if (!parent) { + throw new Error("Create the note inside a folder so Pageden knows where to place it."); + } + return parent; +} + +function targetPathForLocal(remoteDocsFolder: string, localPath: string) { + const normalizedLocal = normalizePath(localPath); + const normalizedRoot = normalizePath(remoteDocsFolder).replace(/\/+$/, ""); + const relativePath = normalizedLocal === normalizedRoot + ? "" + : normalizedLocal.startsWith(`${normalizedRoot}/`) + ? normalizedLocal.slice(normalizedRoot.length + 1) + : normalizedLocal; + const parts = relativePath.split("/").filter(Boolean); + const filename = parts.pop() ?? "untitled.md"; + const folderSegments = parts.map((part) => part.replace(/\.md$/i, "")); + const title = filename.replace(/\.md$/i, "") || "Untitled"; + const documentSlug = slugify(filename); + const documentPath = [...folderSegments.map(slugify), `${documentSlug}.md`].filter(Boolean).join("/"); + return { folderSegments, title, documentSlug, documentPath }; +} + +function frontmatterTitle(content: string): string | null { + if (!content.startsWith("---\n")) return null; + const end = content.indexOf("\n---", 4); + if (end === -1) return null; + const raw = content.slice(4, end); + for (const line of raw.split("\n")) { + const match = line.match(/^title:\s*(.+)$/i); + if (!match?.[1]) continue; + return match[1].trim().replace(/^['"]|['"]$/g, "") || null; + } + return null; +} + +function slugify(value: string): string { + const slug = value + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .replace(/\.md$/i, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return slug || "untitled"; +} + +function trimSlashes(path: string): string { + return path.replace(/^\/+|\/+$/g, ""); +} + + +// --------------------------------------------------------------------------- +// Background sync (Milestone 6). Pure orchestration over the same primitives the manual +// commands use, so behaviour (canonicalization, opaque version, 409 → *.conflict.md, never +// overwrite local) stays identical. The Obsidian-facing engine in main.ts only wires lifecycle, +// events, debounce, status, and the applyingRemoteWrite guard around these. +// --------------------------------------------------------------------------- + +export type DocSyncStatus = + | "unchanged" + | "created" + | "pulled" + | "pushed" + | "conflict" + | "conflict_pending" + | "blocked_viewer" + | "missing_local" + | "gone"; + +// The server copy of an unresolved conflict is written beside the local file as `.conflict.md`. +export function conflictSiblingPath(localPath: string): string { + return `${localPath.replace(/\.md$/i, "")}.conflict.md`; +} + +export interface DocSyncResult { + documentId: string; + localPath: string; + status: DocSyncStatus; + conflictPath?: string; +} + +export interface SyncPassSummary { + unchanged: number; + created: number; + pulled: number; + pushed: number; + conflicts: number; + conflictsPending: number; + blockedViewer: number; + missingLocal: number; + gone: number; + attachmentsDownloaded: number; + attachmentsUploaded: number; + attachmentsDeleted: number; + errors: number; +} + +export interface AttachmentSyncSummary { + downloaded: number; + uploaded: number; + deleted: number; + skipped: number; +} + +// Reconcile one linked document. Decision table: +// local diverged (checksum != tracked) -> push (a stale base yields a clean 409 -> conflict) +// server moved & local unchanged -> pull (write server content, advance meta) +// server moved & local missing -> pull (re-materialize the file) +// otherwise -> unchanged +export async function syncLinkedDocument(deps: SyncDeps, entry: ServerMetaEntry): Promise { + const base = { documentId: entry.documentId, localPath: entry.localPath }; + + let remote: RemoteDocumentWithContent; + try { + remote = await deps.api.document(entry.documentId); + } catch (error) { + // Existence-hiding: a deleted document or a revoked grant returns 404. Report it as gone and + // leave the local file untouched (the user keeps their copy); don't retry-loop. + if (error instanceof PagedenApiError && error.status === 404) return { ...base, status: "gone" }; + throw error; + } + + const serverMoved = (remote.version ?? "") !== entry.baseVersion; + const localExists = await deps.vault.exists(entry.localPath); + + // A previously-recorded conflict freezes the document until the user resolves it (deletes the + // *.conflict.md sibling). Without this, background auto-push would silently push the local side + // on the next pass and discard the server changes the user never reconciled. + if (await deps.vault.exists(conflictSiblingPath(entry.localPath))) { + return { ...base, status: "conflict_pending", conflictPath: conflictSiblingPath(entry.localPath) }; + } + + let localCanonical = ""; + if (localExists) { + localCanonical = canonicalize(await deps.vault.read(entry.localPath)); + const localDiverged = (await checksum(localCanonical)) !== entry.checksum; + if (localDiverged) { + // Reconcile permission from the live fetch: a downgrade to viewer means we must NOT push, + // even if the stored meta still says editor. + if (remote.permission === "viewer") { + if (serverMoved) { + const conflictPath = await writeConflictFile(deps.vault, entry.localPath, remote); + await deps.meta.upsert(metaFromRemote(remote, entry.localPath)); + return { ...base, status: "conflict", conflictPath }; + } + await deps.meta.upsert({ ...entry, permission: "viewer" }); + return { ...base, status: "blocked_viewer" }; + } + const pushed = await pushLocalDocument(deps, entry.localPath); + if (pushed.status === "pushed") return { ...base, status: "pushed" }; + if (pushed.status === "conflict") return { ...base, status: "conflict", conflictPath: pushed.conflictPath }; + return { ...base, status: "blocked_viewer" }; + } + } + + if (!localExists) { + // The user deleted a tracked file locally; don't resurrect it. Leave meta so a manual + // re-download can re-link it. + return { ...base, status: "missing_local" }; + } + + if (serverMoved) { + // Re-read immediately before writing to close the TOCTOU window between the divergence check + // above and the write: if the file changed in between, treat it as a conflict, never clobber. + const fresh = canonicalize(await deps.vault.read(entry.localPath)); + if ((await checksum(fresh)) !== entry.checksum) { + const conflictPath = await writeConflictFile(deps.vault, entry.localPath, remote); + await deps.meta.upsert(metaFromRemote(remote, entry.localPath)); + return { ...base, status: "conflict", conflictPath }; + } + await applyRemotePull(deps, entry.localPath, remote); + return { ...base, status: "pulled" }; + } + + // Unchanged content; still reconcile a permission change so the UI/gating stays accurate. + if (remote.permission !== entry.permission) { + await deps.meta.upsert({ ...entry, permission: remote.permission }); + } + if (hasAttachmentSupport(deps)) { + await syncDocumentAttachments(deps, { ...entry, permission: remote.permission }, localCanonical); + } + return { ...base, status: "unchanged" }; +} + +async function applyRemotePull(deps: SyncDeps, localPath: string, remote: RemoteDocumentWithContent): Promise { + const parent = localPath.split("/").slice(0, -1).join("/"); + if (parent) await ensureFolder(deps.vault, parent); + const content = canonicalize(remote.content); + await deps.vault.write(localPath, content); + const meta = metaFromRemote(remote, localPath); + await deps.meta.upsert(meta); + if (hasAttachmentSupport(deps)) await syncDocumentAttachments(deps, meta, content); +} + +// Run one pass over every linked document. Per-document errors are isolated so one failure +// (or one offline document) does not abort the rest of the pass. +export async function runBackgroundSyncPass( + deps: BackgroundSyncDeps, + onResult?: (result: DocSyncResult) => void, +): Promise { + const summary: SyncPassSummary = { + unchanged: 0, + created: 0, + pulled: 0, + pushed: 0, + conflicts: 0, + conflictsPending: 0, + blockedViewer: 0, + missingLocal: 0, + gone: 0, + attachmentsDownloaded: 0, + attachmentsUploaded: 0, + attachmentsDeleted: 0, + errors: 0, + }; + const entries = await deps.meta.list(); + const linkedLocalPaths = new Set(entries.map((entry) => normalizePath(entry.localPath))); + for (const entry of entries) { + try { + const result = await syncLinkedDocument(deps, entry); + onResult?.(result); + switch (result.status) { + case "unchanged": summary.unchanged += 1; break; + case "created": summary.created += 1; break; + case "pulled": summary.pulled += 1; break; + case "pushed": summary.pushed += 1; break; + case "conflict": summary.conflicts += 1; break; + case "conflict_pending": summary.conflictsPending += 1; break; + case "blocked_viewer": summary.blockedViewer += 1; break; + case "missing_local": summary.missingLocal += 1; break; + case "gone": summary.gone += 1; break; + } + } catch { + summary.errors += 1; + } + } + + if (canCreateUnlinkedLocalDocuments(deps)) { + for (const localPath of await deps.localMarkdownPaths()) { + const normalizedPath = normalizePath(localPath); + if (linkedLocalPaths.has(normalizedPath) || normalizedPath.endsWith(".conflict.md")) continue; + try { + const result = await createRemoteDocumentFromLocal(deps, normalizedPath); + if (result.meta) linkedLocalPaths.add(normalizePath(result.meta.localPath)); + summary.created += 1; + onResult?.({ documentId: result.meta?.documentId ?? "", localPath: normalizedPath, status: "created" }); + } catch { + summary.errors += 1; + } + } + } + return summary; +} + +function canCreateUnlinkedLocalDocuments(deps: BackgroundSyncDeps): deps is CreateRemoteDeps & { localMarkdownPaths: () => Promise } { + return Boolean(deps.workspaceId && deps.localMarkdownPaths && deps.api.tree && deps.api.createFolder && deps.api.createDocument); +} + +export async function syncDocumentAttachments( + deps: SyncDeps, + entry: ServerMetaEntry, + markdown?: string, +): Promise { + const api = requireAttachmentApi(deps); + const meta = requireAttachmentMeta(deps); + const vault = requireBinaryVault(deps); + const summary = emptyAttachmentSummary(); + const remote = await api.attachments(entry.documentId); + const tracked = await meta.listAttachmentsForDocument(entry.documentId); + const trackedById = new Map(tracked.map((item) => [item.attachmentId, item])); + const remoteById = new Map(remote.attachments.map((item) => [item.id, item])); + const content = markdown ?? (await deps.vault.exists(entry.localPath) ? await deps.vault.read(entry.localPath) : ""); + const referenced = entry.permission === "viewer" ? new Set() : extractAttachmentPaths(content, entry.localPath); + + for (const old of tracked) { + if (!remoteById.has(old.attachmentId)) await meta.removeAttachment(old.attachmentId); + } + + if (entry.permission !== "viewer") { + for (const old of tracked) { + if (!remoteById.has(old.attachmentId) || referenced.has(old.localPath) || (await deps.vault.exists(old.localPath))) continue; + await api.deleteAttachment(old.attachmentId); + await meta.removeAttachment(old.attachmentId); + remoteById.delete(old.attachmentId); + summary.deleted += 1; + } + } + + for (const attachment of remote.attachments) { + if (!remoteById.has(attachment.id)) continue; + const localPath = trackedById.get(attachment.id)?.localPath ?? attachmentLocalPath(entry.localPath, attachment.filename); + if (!(await deps.vault.exists(localPath)) || trackedById.get(attachment.id)?.sha256 !== attachment.sha256) { + await ensureParent(deps.vault, localPath); + await vault.writeBinary(localPath, await api.downloadAttachment(attachment.id)); + summary.downloaded += 1; + } + await meta.upsertAttachment(metaFromAttachment(entry.documentId, localPath, attachment)); + } + + if (entry.permission === "viewer") return summary; + const trackedByPath = new Map((await meta.listAttachmentsForDocument(entry.documentId)).map((item) => [item.localPath, item])); + + for (const localPath of referenced) { + if (!(await deps.vault.exists(localPath))) { + summary.skipped += 1; + continue; + } + const bytes = await vault.readBinary(localPath); + const sha256 = await sha256Hex(bytes); + const existing = trackedByPath.get(localPath); + if (existing?.sha256 === sha256) { + summary.skipped += 1; + continue; + } + const uploaded = await api.uploadAttachment(entry.documentId, localPath.split("/").pop() ?? "attachment", bytes, contentTypeForPath(localPath)); + if (existing) { + await api.deleteAttachment(existing.attachmentId); + await meta.removeAttachment(existing.attachmentId); + summary.deleted += 1; + } + await meta.upsertAttachment(metaFromAttachment(entry.documentId, localPath, uploaded)); + summary.uploaded += 1; + } + + return summary; +} + +function emptyAttachmentSummary(): AttachmentSyncSummary { + return { downloaded: 0, uploaded: 0, deleted: 0, skipped: 0 }; +} + +function hasAttachmentSupport(deps: SyncDeps): boolean { + return Boolean( + deps.api.attachments && + deps.api.uploadAttachment && + deps.api.downloadAttachment && + deps.api.deleteAttachment && + deps.vault.readBinary && + deps.vault.writeBinary && + deps.meta.listAttachmentsForDocument && + deps.meta.upsertAttachment && + deps.meta.removeAttachment, + ); +} + +function requireAttachmentApi(deps: SyncDeps): Required> { + if (!deps.api.attachments || !deps.api.uploadAttachment || !deps.api.downloadAttachment || !deps.api.deleteAttachment) { + throw new Error("Attachment sync requires attachment API methods."); + } + return deps.api as Required>; +} + +function requireAttachmentMeta(deps: SyncDeps): Required> { + if (!deps.meta.listAttachmentsForDocument || !deps.meta.upsertAttachment || !deps.meta.removeAttachment) { + throw new Error("Attachment sync requires attachment metadata methods."); + } + return deps.meta as Required>; +} + +function requireBinaryVault(deps: SyncDeps): Required> { + if (!deps.vault.readBinary || !deps.vault.writeBinary) { + throw new Error("Attachment sync requires binary vault methods."); + } + return deps.vault as Required>; +} + +function metaFromAttachment(documentId: string, localPath: string, attachment: Attachment): ServerMetaAttachmentEntry { + return { + attachmentId: attachment.id, + documentId, + localPath, + filename: attachment.filename, + sha256: attachment.sha256, + size: attachment.size, + contentType: attachment.contentType, + createdAt: attachment.createdAt, + }; +} + +function attachmentLocalPath(documentPath: string, filename: string): string { + const parent = documentPath.split("/").slice(0, -1).join("/"); + return normalizePath(`${parent}/${filename}`); +} + +async function ensureParent(vault: VaultLike, path: string): Promise { + const parent = path.split("/").slice(0, -1).join("/"); + if (parent) await ensureFolder(vault, parent); +} + +export function extractAttachmentPaths(markdown: string, documentPath: string): Set { + const parent = documentPath.split("/").slice(0, -1).join("/"); + const out = new Set(); + const push = (raw: string) => { + const target = raw.trim(); + if (!target || target.startsWith("#") || /^[a-z][a-z0-9+.-]*:/i.test(target) || target.endsWith(".md")) return; + const clean = target.split(/[?#]/)[0] ?? ""; + if (!clean) return; + out.add(normalizePath(clean.startsWith("/") ? clean.slice(1) : `${parent}/${clean}`)); + }; + for (const match of markdown.matchAll(/!\[[^\]]*]\(([^)]+)\)|\[[^\]]+]\(([^)]+)\)/g)) { + push(match[1] ?? match[2] ?? ""); + } + for (const match of markdown.matchAll(/!\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?]]/g)) { + push(match[1] ?? ""); + } + return out; +} + +async function sha256Hex(bytes: ArrayBuffer): Promise { + const hash = await crypto.subtle.digest("SHA-256", bytes); + return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +function contentTypeForPath(path: string): string { + const ext = path.split(".").pop()?.toLowerCase(); + if (ext === "png") return "image/png"; + if (ext === "jpg" || ext === "jpeg") return "image/jpeg"; + if (ext === "gif") return "image/gif"; + if (ext === "webp") return "image/webp"; + if (ext === "svg") return "image/svg+xml"; + if (ext === "pdf") return "application/pdf"; + return "application/octet-stream"; +} diff --git a/src/turndown-plugin-gfm.d.ts b/src/turndown-plugin-gfm.d.ts new file mode 100644 index 0000000..5b121d9 --- /dev/null +++ b/src/turndown-plugin-gfm.d.ts @@ -0,0 +1,5 @@ +declare module "turndown-plugin-gfm" { + import type TurndownService from "turndown"; + + export function gfm(service: TurndownService): void; +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..4f28bb2 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,132 @@ +export type Role = "owner" | "manager" | "editor" | "viewer"; + +export interface PagedenSettings { + serverUrl: string; + token: string; + workspaceId: string; + remoteDocsFolder: string; + autoSyncEnabled: boolean; + autoSyncIntervalMinutes: number; + userName?: string; + workspaceName?: string; +} + +export interface MeResponse { + user: { id: string; email: string; name: string }; + workspaces: { id: string; name: string; role: string }[]; +} + +export interface RemoteFolder { + id: string; + parentFolderId: string | null; + name: string; + slug: string; + path: string; + permission: Role | null; +} + +export interface RemoteDocument { + id: string; + folderId: string; + title: string; + path: string; + permission: Role; + version: string | null; + checksum: string | null; +} + +export interface RemoteTree { + folders: RemoteFolder[]; + documents: RemoteDocument[]; +} + +export interface SearchResult { + id: string; + title: string; + path: string; + permission: Role; +} + +export interface SearchResponse { + results: SearchResult[]; +} + +export interface RemoteDocumentWithContent extends RemoteDocument { + workspaceId: string; + content: string; + updatedAt: string; +} + +export interface CreateFolderResponse { + id: string; + path: string; +} + +export interface CreateDocumentResponse { + id: string; + version: string; + checksum: string; + path: string; +} + +export interface ServerMetaEntry { + documentId: string; + localPath: string; + remotePath: string; + title: string; + baseVersion: string; + checksum: string; + permission: Role; + updatedAt: string; +} + +export interface Attachment { + id: string; + filename: string; + contentType: string; + size: number; + sha256: string; + createdAt: string; +} + +export interface AttachmentListResponse { + attachments: Attachment[]; +} + +export interface ServerMetaAttachmentEntry { + attachmentId: string; + documentId: string; + localPath: string; + filename: string; + sha256: string; + size: number; + contentType: string; + createdAt: string; +} + +export interface ServerMetaFile { + documents: Record; + attachments?: Record; +} + +export interface WriteResult { + id: string; + version: string; + checksum: string; + updatedAt: string; +} + +export interface DeviceStartResponse { + deviceCode: string; + userCode: string; + verificationUri: string; + expiresIn: number; + interval: number; +} + +export type DevicePollResponse = + | { status: "pending" } + | { status: "denied" } + | { status: "expired" } + | { status: "consumed" } + | { status: "approved"; token: string }; diff --git a/test/obsidian-stub.ts b/test/obsidian-stub.ts new file mode 100644 index 0000000..cf86521 --- /dev/null +++ b/test/obsidian-stub.ts @@ -0,0 +1,14 @@ +export function normalizePath(path: string): string { + return path.replace(/\\/g, "/").replace(/\/+/g, "/").replace(/\/$/, ""); +} + +export async function requestUrl(): Promise { + throw new Error("requestUrl is not available in unit tests; inject a RequestTransport."); +} + +export class Plugin {} +export class PluginSettingTab {} +export class Setting {} +export class Modal {} +export class Notice {} +export class TFile {} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..c910611 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM"], + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true, + "esModuleInterop": true, + "noEmit": true, + "declaration": false, + "types": ["node"] + }, + "include": ["src", "esbuild.config.mjs", "vitest.config.ts"] +} diff --git a/versions.json b/versions.json index a499de0..ddf461d 100644 --- a/versions.json +++ b/versions.json @@ -3,5 +3,6 @@ "0.1.1": "1.5.0", "0.1.2": "1.5.0", "0.1.3": "1.5.0", - "0.1.4": "1.5.0" + "0.1.4": "1.5.0", + "0.1.5": "1.5.0" } diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..9bf4739 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from "vitest/config"; +import { fileURLToPath } from "node:url"; + +export default defineConfig({ + resolve: { + alias: { + obsidian: fileURLToPath(new URL("./test/obsidian-stub.ts", import.meta.url)), + }, + }, + test: { + include: ["src/**/*.test.ts"], + environment: "node", + }, +});