@ones-editor/editor 0.0.3-beta.113 → 0.0.3-beta.114

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ Available method signatures are:
21
21
  `).map((r,i)=>{const l=i===0&&(e==null?void 0:e.firstLineAsTitle)?{heading:1}:void 0;return Zn(r,l)})},meta:{},comments:{}}}function pd(n){const e=n.blocks.root;if(e.length!==1)return!1;const t=e[0];return!(!t.text||at(t.text))}function Bp(n,e){const t=N();return n.localInsertChildContainer(t,e),t}function Qn(n,e){return Bp(n,[Jl(e)])}function Ep(n){return typeof n.offset=="number"}function Kl(n){return Ep(n.anchor)}function nv(n){return Kl(n)&&n.anchor.offset===n.focus.offset&&n.anchor.blockId===n.focus.blockId}function Ip(n,e){return{blockId:n,offset:e}}function Xl(n,e){const t=Ip(n,e);return{anchor:t,focus:t}}function xp(n,e){return{blockId:n,childContainerId:e}}function ov(n,e){const t=xp(n,e);return{anchor:t,focus:t}}const rv=w("block-to-text");function iv(n,e,t){let o="";return e.forEach(r=>{if(d(rv,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,t,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}const sv=w("block-to-text");function lv(n,e,t){let o="";return e.forEach(r=>{if(d(sv,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const s=r.attributes,l=n.editorBoxes.getBoxClass(s.type);if(l!=null&&l.convertTo){o+=l.convertTo(n,s,t,"markdown");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${s.type}]`}const i=r.attributes;if(i){let s=r.insert;i.link&&(s=`[${s}](${i.link})`);const l=[];i["style-code"]?l.push("`"):(i["style-bold"]&&l.push("**"),i["style-italic"]&&l.push("*"),i["style-underline"]&&l.push("__"),i["style-strikethrough"]&&l.push("~~"));const c=l.join("");o.endsWith(c.substring(0,1))&&(o+=" ");const a=l.reverse().join("");o+=c+s+a;return}o+=r.insert}),o}function cv(n,e,t){const o=e.text||[];let i=lv(n,o,t);if(e.heading){const s=e.heading;i=`${"#".repeat(s)} ${i}`}return e.quoted&&(i=`> ${i}`),e.type==="text"&&(i=`${i}
22
22
  `),i}const av=w("block-to-text");function uv(n,e,t){let o="";return e.forEach(r=>{if(d(av,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const s=r.attributes,l=n.editorBoxes.getBoxClass(s.type);if(l!=null&&l.convertTo){o+=l.convertTo(n,s,t,"html");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${s.type}]`}const i=r.attributes;if(i){let s=r.insert;i.link&&(s=`<a href="${i.link}">${s}</a>`);const l=[];i.bold&&l.push("strong"),i.italic&&l.push("em"),i.underline&&l.push("u"),i.strike&&l.push("s"),i.code&&l.push("code");const c=l.map(u=>`<${u}>`).join(""),a=l.reverse().map(u=>`</${u}>`).join("");o+=c+s+a;return}o+=r.insert}),o||(o="<br>"),`<p>${o}</p>`}const os=w("text-block");function dv(n,e,t,o,r){const{text:i}=r;d(os,i,"no text for text block");const s=nr(o,"div");return Vl(n,e,r.id,s,i),s}function hv(n,e,t){d(os,t,"no text to update");const o=nr(null,"div");Vl(n,mo(e),z(e),o,t);const r=le(e);Wi(r,o)}function fv(n,e,t){return xb(n,e,t)}function Tp(n,e){let t="";return e.forEach(o=>{if(!!o.insert){if(o.attributes&&o.attributes.box===!0&&o.attributes.type==="math"){t+=`[${I.t("mathjax.abstract")}] `;return}t+=o.insert}}),t}function mv(n,e){d(os,$(n,e),"block in not textBlock");const t=n.selection.range;let o="";if(t.isCollapsed()){const r=n.getBlockText(e);o=Tp(n,r)}else{const r=z(e),i=tn(n,{simpleBlockOnly:!0}).find(s=>z(s.block)===r);if(i&&!Ie(n,i.block)){d(os,i.block===e,"block not match");const s=n.getBlockText(e),{start:l,end:c}=i,a=l.offset,u=c.offset-a;if(u>0){const{middle:f}=Ge(s,a,u);o=Tp(n,f)}}}return{abstract:o.trim()}}function gv(n,e,t,o){return d(os,e.text,"no text for text block"),o==="text"?iv(n,e.text,t):o==="markdown"?cv(n,e,t):uv(n,e.text,t)}const wt={blockType:"text",blockKind:"text",createBlockContent:dv,getBlockTextLength:Ki,getRangeFromPoint:Vb,moveCaret:jb,updateSelection:Tb,clearSelection:Db,getCaretRect:Dt,getClientRects:fv,setBlockText:hv,getBlockProperties:mv,convertTo:gv},pv=Vl,ec=w("action-helper");function yo(n,e){const t=_(e),o=q(t),r=K(e);return n.doc.getBlockData(o,r)}function pt(n,e){d(ec,$(n,e),"not a text kind block");const o=yo(n,e).text;return d(ec,o,"no text in block"),o}function tc(n,e,t){return kt(pt(n,e),t).left}function Dp(n,e){const t=j(e);d(ec,t,"no parent block");const o=pt(n,t),r=ug(e),i=o.find(s=>{const l=s.attributes;return l?l.box&&l.id===r:!1});return d(ec,i,"failed to find box"),i.attributes}const Te=w("block-text");function Cv(n,e,t){d(Te,$(n,e),"not a text kind block"),d(Te,ut(e,t),"not a valid offset"),d(Te,t>=0&&t<G(n,e),`invalid offset: ${t}`);const r=cr(e,t)-t;r===0&&d(Te,!1,`no text after offset: ${t}`);const i=pt(n,e),{middle:s}=Ge(i,t,r);d(Te,s.length===1,"failed to split text to 3 parts");const l=s[0];return Xi(l)?" ":(d(Te,l.insert.length===1||l.insert.length===2,"invalid op"),l.insert)}function Av(n,e,t){d(Te,$(n,e),"not a text kind block"),d(Te,ut(e,t),"not a valid offset"),d(Te,t>0&&t<=G(n,e),`invalid offset: ${t}`);const o=Ao(e,t),r=t-o;r===0&&d(Te,!1,`no text before offset: ${t}`);const i=pt(n,e),{middle:s}=Ge(i,o,r);d(Te,s.length===1,"failed to split text to 3 parts");const l=s[0];return Xi(l)?" ":(d(Te,l.insert.length===1||l.insert.length===2,"invalid op"),l.insert)}function nc(n,e,t){d(Te,$(n,e),"not a text kind block"),d(Te,ut(e,t),"not a valid offset"),d(Te,t>0&&t<=G(n,e),`invalid offset: ${t}`);const o=Ao(e,t),r=t-o;r===0&&d(Te,!1,`no text before offset: ${t}`);const i=pt(n,e),{middle:s}=Ge(i,o,r);d(Te,s.length===1,"failed to split text to 3 parts");const l=s[0];return Xi(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:Sl(l.insert)?"space":"text",offset:o,length:l.insert.length}}function rs(n,e,t){d(Te,$(n,e),"not a text kind block"),d(Te,ut(e,t),"not a valid offset"),d(Te,t>=0&&t<G(n,e),`invalid offset: ${t}`);const r=cr(e,t)-t;r===0&&d(Te,!1,`no text after offset: ${t}`);const i=pt(n,e),{middle:s}=Ge(i,t,r);d(Te,s.length===1,"failed to split text to 3 parts");const l=s[0];return Xi(l)?{op:l,charType:"box",offset:t,length:1}:{op:l,charType:Sl(l.insert)?"space":"text",offset:t,length:l.insert.length}}function bv(n,e,t,o){let r=t;for(;r>0;){const i=nc(n,e,r);if(i.charType===o)return i;r-=i.length}return null}function vv(n,e,t,o){const r=G(n,e);let i=t;for(;i<r;){const s=rs(n,e,i);if(s.charType===o)return s;i+=s.length}return null}function Cd(n,e,t,o){let r=t;for(;r>0;){const i=nc(n,e,r);if(i.charType!==o)return i;r-=i.length}return null}function Ad(n,e,t,o){const r=G(n,e);let i=t;for(;i<r;){const s=rs(n,e,i);if(s.charType!==o)return s;i+=s.length}return null}function bd(n,e,t){if(d(Te,$(n,e),"invalid blok type"),Ie(n,e))return 0;const o=nc(n,e,t);if(o.charType==="box")return t-1;let r=t;if(o.charType==="space"){const s=Cd(n,e,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=Cd(n,e,r,"text");return i?i.offset+i.length:0}function vd(n,e,t){if(d(Te,$(n,e),"invalid blok type"),Ie(n,e))return 0;const o=rs(n,e,t);if(o.charType==="box")return t+1;let r=t;if(o.charType==="space"){const s=Ad(n,e,r,"space");if(!s||s.offset===0)return G(n,e);if(s.charType==="box")return s.offset;r=s.offset}const i=Ad(n,e,r,"text");return i?i.offset:G(n,e)}const Sp=w("text-box");function yv(n,e,t,o){d(Sp,o.text,`no text for text box data: ${JSON.stringify(o)}`),d(Sp,typeof o.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`),A("span",[],t,o.text)}function kv(n,e,t,o){var r;return(r=e.text)!=null?r:""}const Lp={boxType:"text",updateBoxContent:yv,convertTo:kv},wv="data:image/svg+xml;base64,Cjxzdmcgdmlld0JveD0iMCAwIDI0IDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMTguMjQ0NSA2QzE3LjgyNzQgNiAxNy41MzYzIDYuMjkxMTcgMTcuNTM2MyA2LjcwODI2QzE3LjUzNjMgNi45ODM3IDE3LjU1OTkgNy4yMzU1MyAxNy41NTk5IDcuNjEzMjdDMTcuNTU5OSAxMC4yODExIDE2LjYyMzQgMTEuMzc0OSAxMy45NzkyIDExLjM3NDlIOC45NDI2Nkw3LjEyNDc5IDExLjQ4NTFMOS41NDA3NSA5LjI4MTYyTDExLjE5MzQgNy41OTc1M0MxMS4zMjcxIDcuNDcxNjEgMTEuMzk4IDcuMjgyNzQgMTEuMzk4IDcuMDkzODdDMTEuMzk4IDYuNjkyNTIgMTEuMDk4OSA2LjQwMTM1IDEwLjY5NzYgNi40MDEzNUMxMC41MDg3IDYuNDAxMzUgMTAuMzM1NiA2LjQ3MjE4IDEwLjE3ODIgNi42MjE3TDUuMjQzOTYgMTEuNTQ4MUM1LjA4NjU3IDExLjcwNTUgNSAxMS44OTQzIDUgMTIuMDkxMUM1IDEyLjI4NzggNS4wODY1NyAxMi40NzY3IDUuMjQzOTYgMTIuNjI2MkwxMC4xNjI1IDE3LjUzNjhDMTAuMzM1NiAxNy43MDk5IDEwLjUwODcgMTcuNzgwOCAxMC42OTc2IDE3Ljc4MDhDMTEuMDk4OSAxNy43ODA4IDExLjM5OCAxNy40ODk2IDExLjM5OCAxNy4wODgzQzExLjM5OCAxNi44OTE1IDExLjMyNzEgMTYuNzEwNSAxMS4xOTM0IDE2LjU4NDZMOS41NDA3NSAxNC45MDA1TDcuMTMyNjYgMTIuNjk3TDguOTQyNjYgMTIuODA3MkgxNC4wNTc5QzE3LjU1OTkgMTIuODA3MiAxOSAxMS4yNDExIDE5IDcuNjc2MjJDMTkgNy4yMzU1MyAxOC45OTIxIDYuODY1NjUgMTguOTM3IDYuNjEzODNDMTguODc0MSA2LjI5OTA0IDE4LjY3NzMgNiAxOC4yNDQ1IDZaIiBmaWxsPSIjQjJCQ0NEIi8+Cjwvc3ZnPgo=";function Bv(n,e,t,o){ym(wv,[],t),A("br",[],t)}function Ev(n,e,t,o){return o==="text"?`
23
23
  `:o==="html"?"<br>":o==="markdown"?`
24
- `:""}const Mp={boxType:"br",updateBoxContent:Bv,convertTo:Ev},Rp=w("editor-boxes");class Op{constructor(e){h(this,"boxes",new Map);this.editor=e}registerBoxClass(e){const t=e.boxType,o=this.boxes.get(t);d(Rp,!o,`duplicated box type: ${t}`),this.boxes.set(t,e)}getBoxClass(e){const t=this.boxes.get(e);return d(Rp,t,`unknown box type: ${e}`),t}createBox(e,t){const o=ag(t),r=dg(o);return this.getBoxClass(t.type).updateBoxContent(this.editor,o,r,t),o}}function Iv(n,e,t,o){const r=o,{width:i,height:s,src:l}=r,c=["editor-box-image"];r.link&&c.push("editor-box-image-link");const a=A("img",c,t);i&&(a.style.width=`${i}px`),s&&(a.style.height=`${s}px`),a.src=l}const Fp={boxType:"image",updateBoxContent:Iv};function xv(n,e,t,o){A("span",[],t,o.text)}const Pp={insertionType:"inputting",updateInsertionContent:xv},Np=w("editor-insertion");class $p{constructor(e){h(this,"insertions",new Map);this.editor=e}registerInsertionClass(e){const t=e.insertionType,o=this.insertions.get(t);d(Np,!o,`duplicated insertion type: ${t}`),this.insertions.set(t,e)}getInsertionClass(e){const t=this.insertions.get(e);return d(Np,t,`unknown insertion type: ${e}`),t}createInsertion(e,t){const o=hg(t.type,t.id),r=mg(o);return this.getInsertionClass(t.type).updateInsertionContent(this.editor,o,r,t),o}}class Tv{constructor(e){h(this,"cursors",new Map);h(this,"timer");this.editor=e,this.timer=this.startTimer()}add(e,t){this.cursors.set(e,t)}startTimer(){return setInterval(()=>{const e=Date.now();Array.from(this.cursors).forEach(([t,o])=>{if(e-o>3e3){const r=fg(this.editor,t);r&&H(r,"active"),this.cursors.delete(t)}})},1e3)}destroy(){clearInterval(this.timer)}}function Dv(n,e,t,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",a=>new Tv(a)).add(r.id,r.time),M(e,"active")),A("span",[],t,"|").setAttribute("data-cursor-name",r.name),e.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const yd={insertionType:"remote-cursor",updateInsertionContent:Dv};class _p{constructor(e){h(this,"decorators",[]);this.editor=e}registerDecorator(e){this.decorators.push(e)}decorateBlock(e,t){let o=t;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,e,t);i&&(o=Q.default(i))}}),o}decorateText(e,t){let o=t;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,e,t);if(s){const{insertions:l,text:c}=s;l&&Array.from(l.entries()).forEach(([a,u])=>{const f=r.get(a);f?f.push(...u):r.set(a,u)}),c&&(o=Q.default(c))}}}),{insertions:r,text:o}}}const kd=w("editor-input");class Sv{constructor(e,t){h(this,"editor");h(this,"composing",!1);h(this,"callbacks");h(this,"inputElement");h(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var t;const e=(t=document.getSelection())==null?void 0:t.focusNode;e&&this.editor.contains(e)&&!Nr(e)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});h(this,"handleEditorSelectionChanged",()=>{const t=!this.editor.isWritable();this.inputElement.readOnly=t});h(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});h(this,"handleCompositionstart",e=>{this.composing=!0,this.callbacks.onCompositionStart(e)});h(this,"handleCompositionend",e=>{this.composing=!1,this.callbacks.onUpdateCompositionText(e,this.inputElement.value,!0),this.inputElement.value=""});h(this,"handleInput",e=>{if(e instanceof InputEvent&&!!e.data){if(this.editor.readonly){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(e,e.data,!1):(this.callbacks.onInsertText(e,e.data),this.inputElement.value="")}});h(this,"handleKeyDown",e=>{if(!this.composing){if(this.callbacks.onKeyDown(e)){e.preventDefault(),e.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});h(this,"handleCopy",e=>{this.callbacks.onCopy(e)});h(this,"handleCut",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onCut(e),kd.debug("on cut")});h(this,"handlePaste",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onPaste(e)});h(this,"handlePasteText",e=>{this.callbacks.onPasteText(e)});this.editor=e,this.callbacks=t;const o=A("input",["editor-input"],e.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const e=this.inputElement;e.removeEventListener("compositionstart",this.handleCompositionstart),e.removeEventListener("compositionend",this.handleCompositionend),e.onkeydown=null,e.oninput=null,e.oncopy=null,e.onpaste=null,e.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),ot.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(e){this.callbacks.onChanged(e)}handleRemoteChanged(e){this.callbacks.onRemoteChanged(e)}addHandler(e){this.callbacks.addHandler(e)}removeHandler(e){this.callbacks.removeHandler(e)}defaultInsertText(e,t,o,r,i){d(kd,e===this.editor,"invalid editor"),this.callbacks.defaultInsertText(e,t,o,r,i)}defaultHandleKeydown(e,t){return d(kd,e===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(e,t)}}function Hp(n){const e=n.rootElement,t=e.getBoundingClientRect(),o=Qo(e),r=window.innerWidth,i=window.innerHeight,s=t.left<0?0:t.left,l=t.top<0?0:t.top,c=t.right>r?r:t.right,a=t.bottom>i?i:t.bottom,u=(s+c)/2,f=(l+a)/2,m=0-t.left+u,p=0-t.top+f,b=n.input.inputElement;b.style.left=`${m/o}px`,b.style.top=`${p/o}px`}const wd=w("editor-caret");class Lv{constructor(e){h(this,"editor");h(this,"caretElem");h(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=e,this.caretElem=A("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const e=window.getComputedStyle(this.caretElem);return e.display!=="none"&&e.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const e=this.editor.selection.range.start;if(!(e instanceof qe))return!1;const t=this.editor.getBlockById(e.blockId);return!!$(this.editor,t)}update(){if(Bm(this.editor.rootElement))return;const e=this.caretElem;if(this.hasCaret())e.style.display="";else{e.style.display="none",Hp(this.editor);return}const{range:t}=this.editor.selection;d(wd,t.isCollapsed,"range is not collapsed");const o=t.start;d(wd,o instanceof qe,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(wd,$(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Go(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Dt(r,o);const l=this.editor.contentElement.getBoundingClientRect(),c=i.left-l.left,a=i.top-l.top;e.style.left=`${c}px`,e.style.top=`${a}px`,e.style.height=`${i.height}px`;const u=this.editor.input.inputElement;u.style.left=`${c}px`,u.style.top=`${a+i.height-24}px`,ot.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`);const m=vn(r,{horizontal:!0}).getBoundingClientRect(),p=m.left-l.left,b=p+m.width;c<p||c>b?(Hp(this.editor),e.style.display="none"):e.style.display=""}}function Mv(n){bg(n),n.selection.range.getSelectedBlocks().forEach(e=>vg(n,e.block,e.start,e.end))}const Rv=w("editor-dom");function jp(n){return vn(n.rootContainer).clientHeight}function Ov(n){return n.getFirstBlock().getBoundingClientRect().top}function Fv(n){return n.getLastBlock().getBoundingClientRect().bottom}function Bd(n){const t=vn(n.rootContainer).getBoundingClientRect(),o=t.x<0?0:t.x,r=t.y<0?0:t.y,i=t.right>window.innerWidth?window.innerWidth:t.right,s=t.bottom>window.innerHeight?window.innerHeight:t.bottom;return new DOMRect(o,r,i-o,s-r)}function Pv(n,e){const t=Bd(n),o=n.getBlockById(e.blockId),i=Kt(n,o,e);return Yo(t,i.x,i.y)&&Yo(t,i.right,i.bottom)}function zp(n,e){const t=Bd(n),o=e.getBoundingClientRect();return o.top>=t.top&&o.top<=t.bottom||o.bottom<=t.bottom&&o.bottom>=t.top}function Nv(n,e){const t=Bd(n),o=e.getBoundingClientRect();return Yo(t,o.x,o.y)||Yo(t,o.right,o.bottom)}function $v(n){if(!Au(n.rootContainer)){Rv.warn("editorScrollIntoView: editor is not visible");return}const e=n.rootContainer.getBoundingClientRect();if(e.height<1&&e.width<1)return;const t=n.selection,o=t.range.focus;if(!o.isSimple()){const u=o,f=n.getContainerById(u.childContainerId);Nv(n,f)||f.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const u=n.getBlockById(t.range.start.blockId);if(Ke(u)&&zp(n,u)||ce(n,u)&&zp(n,u))return}const r=o,i=n.getBlockById(r.blockId);if(Pv(n,r))return;const s=Kt(n,i,r),l=i.getBoundingClientRect(),c=Fe(i),a=A("div",["editor-block-anchor"],c);a.style.top=`${s.top-l.top}px`,bu(a,{elementToScroll:vn(n.rootContainer)}),setTimeout(()=>{a.remove()},200)}function _v(n,e){if(e.isCollapsed())return!1;const t=$e(n.rootContainer),o=Je(n.rootContainer),{start:r,end:i}=e;return r.blockId===z(t)&&r.offset===0&&i.blockId===z(o)&&i.offset===G(n,o)}const Up=w("range-in-block");function Vp(n,e){const t=e.getEditor(),o=t.getBlockById(e.start.blockId),r=t.getBlockById(e.end.blockId),i=o===n||Ce(n,o),s=r===n||Ce(n,r);return!!(i||s)}function qp(n,e){const t=n.doc.toJSON(),o=new Set(Object.values(t.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=ye(e);if(i){for(;i&&!o.has(z(i));)i=ye(i);d(Up,i,"no prev block while deleting a block"),r=Pe(n,i,G(n,i))}else{const s=fe(e);d(Up,s,"no prev and next block while deleting a block"),r=Pe(n,s,0)}return r}const Hv=w("block-to-html");function Ed(n,e,t,o){const r=$r(n,e.type);if(r.convertTo)return r.convertTo(n,e,t,"html",o);if(r.blockKind!=="text")return`[${e.type}]`;d(Hv,e.text,"no text");const i=ve(e.text);return`<div>${Tm(i)}</div>`}const Wp=w("block-to-text");function jv(n,e,t){let o="";return e.forEach(r=>{if(d(Wp,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,t,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function oc(n,e,t,o){const r=$r(n,e.type);return r.convertTo?r.convertTo(n,e,t,"text",o):r.blockKind!=="text"?`[${e.type}]`:(d(Wp,e.text,"no text"),jv(n,e.text,t))}function Id(n,e,t,o){const r=$r(n,e.type);return r.convertTo?r.convertTo(n,e,t,"markdown",o):oc(n,e,t,o)}function rc(n,e){return e.blocks.root.map((r,i)=>Ed(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
24
+ `:""}const Mp={boxType:"br",updateBoxContent:Bv,convertTo:Ev},Rp=w("editor-boxes");class Op{constructor(e){h(this,"boxes",new Map);this.editor=e}registerBoxClass(e){const t=e.boxType,o=this.boxes.get(t);d(Rp,!o,`duplicated box type: ${t}`),this.boxes.set(t,e)}getBoxClass(e){const t=this.boxes.get(e);return d(Rp,t,`unknown box type: ${e}`),t}createBox(e,t){const o=ag(t),r=dg(o);return this.getBoxClass(t.type).updateBoxContent(this.editor,o,r,t),o}}function Iv(n,e,t,o){const r=o,{width:i,height:s,src:l}=r,c=["editor-box-image"];r.link&&c.push("editor-box-image-link");const a=A("img",c,t);i&&(a.style.width=`${i}px`),s&&(a.style.height=`${s}px`),a.src=n.doc.buildResourceUrl(l)}const Fp={boxType:"image",updateBoxContent:Iv};function xv(n,e,t,o){A("span",[],t,o.text)}const Pp={insertionType:"inputting",updateInsertionContent:xv},Np=w("editor-insertion");class $p{constructor(e){h(this,"insertions",new Map);this.editor=e}registerInsertionClass(e){const t=e.insertionType,o=this.insertions.get(t);d(Np,!o,`duplicated insertion type: ${t}`),this.insertions.set(t,e)}getInsertionClass(e){const t=this.insertions.get(e);return d(Np,t,`unknown insertion type: ${e}`),t}createInsertion(e,t){const o=hg(t.type,t.id),r=mg(o);return this.getInsertionClass(t.type).updateInsertionContent(this.editor,o,r,t),o}}class Tv{constructor(e){h(this,"cursors",new Map);h(this,"timer");this.editor=e,this.timer=this.startTimer()}add(e,t){this.cursors.set(e,t)}startTimer(){return setInterval(()=>{const e=Date.now();Array.from(this.cursors).forEach(([t,o])=>{if(e-o>3e3){const r=fg(this.editor,t);r&&H(r,"active"),this.cursors.delete(t)}})},1e3)}destroy(){clearInterval(this.timer)}}function Dv(n,e,t,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",a=>new Tv(a)).add(r.id,r.time),M(e,"active")),A("span",[],t,"|").setAttribute("data-cursor-name",r.name),e.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const yd={insertionType:"remote-cursor",updateInsertionContent:Dv};class _p{constructor(e){h(this,"decorators",[]);this.editor=e}registerDecorator(e){this.decorators.push(e)}decorateBlock(e,t){let o=t;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,e,t);i&&(o=Q.default(i))}}),o}decorateText(e,t){let o=t;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,e,t);if(s){const{insertions:l,text:c}=s;l&&Array.from(l.entries()).forEach(([a,u])=>{const f=r.get(a);f?f.push(...u):r.set(a,u)}),c&&(o=Q.default(c))}}}),{insertions:r,text:o}}}const kd=w("editor-input");class Sv{constructor(e,t){h(this,"editor");h(this,"composing",!1);h(this,"callbacks");h(this,"inputElement");h(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var t;const e=(t=document.getSelection())==null?void 0:t.focusNode;e&&this.editor.contains(e)&&!Nr(e)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});h(this,"handleEditorSelectionChanged",()=>{const t=!this.editor.isWritable();this.inputElement.readOnly=t});h(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});h(this,"handleCompositionstart",e=>{this.composing=!0,this.callbacks.onCompositionStart(e)});h(this,"handleCompositionend",e=>{this.composing=!1,this.callbacks.onUpdateCompositionText(e,this.inputElement.value,!0),this.inputElement.value=""});h(this,"handleInput",e=>{if(e instanceof InputEvent&&!!e.data){if(this.editor.readonly){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(e,e.data,!1):(this.callbacks.onInsertText(e,e.data),this.inputElement.value="")}});h(this,"handleKeyDown",e=>{if(!this.composing){if(this.callbacks.onKeyDown(e)){e.preventDefault(),e.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});h(this,"handleCopy",e=>{this.callbacks.onCopy(e)});h(this,"handleCut",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onCut(e),kd.debug("on cut")});h(this,"handlePaste",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onPaste(e)});h(this,"handlePasteText",e=>{this.callbacks.onPasteText(e)});this.editor=e,this.callbacks=t;const o=A("input",["editor-input"],e.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const e=this.inputElement;e.removeEventListener("compositionstart",this.handleCompositionstart),e.removeEventListener("compositionend",this.handleCompositionend),e.onkeydown=null,e.oninput=null,e.oncopy=null,e.onpaste=null,e.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),ot.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(e){this.callbacks.onChanged(e)}handleRemoteChanged(e){this.callbacks.onRemoteChanged(e)}addHandler(e){this.callbacks.addHandler(e)}removeHandler(e){this.callbacks.removeHandler(e)}defaultInsertText(e,t,o,r,i){d(kd,e===this.editor,"invalid editor"),this.callbacks.defaultInsertText(e,t,o,r,i)}defaultHandleKeydown(e,t){return d(kd,e===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(e,t)}}function Hp(n){const e=n.rootElement,t=e.getBoundingClientRect(),o=Qo(e),r=window.innerWidth,i=window.innerHeight,s=t.left<0?0:t.left,l=t.top<0?0:t.top,c=t.right>r?r:t.right,a=t.bottom>i?i:t.bottom,u=(s+c)/2,f=(l+a)/2,m=0-t.left+u,p=0-t.top+f,b=n.input.inputElement;b.style.left=`${m/o}px`,b.style.top=`${p/o}px`}const wd=w("editor-caret");class Lv{constructor(e){h(this,"editor");h(this,"caretElem");h(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=e,this.caretElem=A("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const e=window.getComputedStyle(this.caretElem);return e.display!=="none"&&e.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const e=this.editor.selection.range.start;if(!(e instanceof qe))return!1;const t=this.editor.getBlockById(e.blockId);return!!$(this.editor,t)}update(){if(Bm(this.editor.rootElement))return;const e=this.caretElem;if(this.hasCaret())e.style.display="";else{e.style.display="none",Hp(this.editor);return}const{range:t}=this.editor.selection;d(wd,t.isCollapsed,"range is not collapsed");const o=t.start;d(wd,o instanceof qe,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(wd,$(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Go(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Dt(r,o);const l=this.editor.contentElement.getBoundingClientRect(),c=i.left-l.left,a=i.top-l.top;e.style.left=`${c}px`,e.style.top=`${a}px`,e.style.height=`${i.height}px`;const u=this.editor.input.inputElement;u.style.left=`${c}px`,u.style.top=`${a+i.height-24}px`,ot.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`);const m=vn(r,{horizontal:!0}).getBoundingClientRect(),p=m.left-l.left,b=p+m.width;c<p||c>b?(Hp(this.editor),e.style.display="none"):e.style.display=""}}function Mv(n){bg(n),n.selection.range.getSelectedBlocks().forEach(e=>vg(n,e.block,e.start,e.end))}const Rv=w("editor-dom");function jp(n){return vn(n.rootContainer).clientHeight}function Ov(n){return n.getFirstBlock().getBoundingClientRect().top}function Fv(n){return n.getLastBlock().getBoundingClientRect().bottom}function Bd(n){const t=vn(n.rootContainer).getBoundingClientRect(),o=t.x<0?0:t.x,r=t.y<0?0:t.y,i=t.right>window.innerWidth?window.innerWidth:t.right,s=t.bottom>window.innerHeight?window.innerHeight:t.bottom;return new DOMRect(o,r,i-o,s-r)}function Pv(n,e){const t=Bd(n),o=n.getBlockById(e.blockId),i=Kt(n,o,e);return Yo(t,i.x,i.y)&&Yo(t,i.right,i.bottom)}function zp(n,e){const t=Bd(n),o=e.getBoundingClientRect();return o.top>=t.top&&o.top<=t.bottom||o.bottom<=t.bottom&&o.bottom>=t.top}function Nv(n,e){const t=Bd(n),o=e.getBoundingClientRect();return Yo(t,o.x,o.y)||Yo(t,o.right,o.bottom)}function $v(n){if(!Au(n.rootContainer)){Rv.warn("editorScrollIntoView: editor is not visible");return}const e=n.rootContainer.getBoundingClientRect();if(e.height<1&&e.width<1)return;const t=n.selection,o=t.range.focus;if(!o.isSimple()){const u=o,f=n.getContainerById(u.childContainerId);Nv(n,f)||f.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const u=n.getBlockById(t.range.start.blockId);if(Ke(u)&&zp(n,u)||ce(n,u)&&zp(n,u))return}const r=o,i=n.getBlockById(r.blockId);if(Pv(n,r))return;const s=Kt(n,i,r),l=i.getBoundingClientRect(),c=Fe(i),a=A("div",["editor-block-anchor"],c);a.style.top=`${s.top-l.top}px`,bu(a,{elementToScroll:vn(n.rootContainer)}),setTimeout(()=>{a.remove()},200)}function _v(n,e){if(e.isCollapsed())return!1;const t=$e(n.rootContainer),o=Je(n.rootContainer),{start:r,end:i}=e;return r.blockId===z(t)&&r.offset===0&&i.blockId===z(o)&&i.offset===G(n,o)}const Up=w("range-in-block");function Vp(n,e){const t=e.getEditor(),o=t.getBlockById(e.start.blockId),r=t.getBlockById(e.end.blockId),i=o===n||Ce(n,o),s=r===n||Ce(n,r);return!!(i||s)}function qp(n,e){const t=n.doc.toJSON(),o=new Set(Object.values(t.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=ye(e);if(i){for(;i&&!o.has(z(i));)i=ye(i);d(Up,i,"no prev block while deleting a block"),r=Pe(n,i,G(n,i))}else{const s=fe(e);d(Up,s,"no prev and next block while deleting a block"),r=Pe(n,s,0)}return r}const Hv=w("block-to-html");function Ed(n,e,t,o){const r=$r(n,e.type);if(r.convertTo)return r.convertTo(n,e,t,"html",o);if(r.blockKind!=="text")return`[${e.type}]`;d(Hv,e.text,"no text");const i=ve(e.text);return`<div>${Tm(i)}</div>`}const Wp=w("block-to-text");function jv(n,e,t){let o="";return e.forEach(r=>{if(d(Wp,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,t,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function oc(n,e,t,o){const r=$r(n,e.type);return r.convertTo?r.convertTo(n,e,t,"text",o):r.blockKind!=="text"?`[${e.type}]`:(d(Wp,e.text,"no text"),jv(n,e.text,t))}function Id(n,e,t,o){const r=$r(n,e.type);return r.convertTo?r.convertTo(n,e,t,"markdown",o):oc(n,e,t,o)}function rc(n,e){return e.blocks.root.map((r,i)=>Ed(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
25
25
  `)}function Gp(n,e){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${rc(n,e)}</body></html>`}function is(n,e){return e.blocks.root.map((r,i)=>oc(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
26
26
  `)}function ss(n,e){return e.blocks.root.map((r,i)=>Id(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
27
27
  `)}const zv=w("get-text-position");function Ur(n,e){const t=e!=null?e:n.selection.range.start;t instanceof qe||d(zv,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=K(r),s=_(r),l=q(s),{offset:c}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const ls=w("insert-text");function Zp(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(d(ls,r,"no block data"),d(ls,r.text,"no block text"),at(r.text)===0)return d(ls,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Ge(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function Uv(n,e,t){const o=_(e),r=q(o),i=K(e);return Zp(n,r,i,t)}function Qp(n,e,t,o,r){const i=_(e),s=q(i),l=K(e),c=Uv(n,e,t),a=Zl(t,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),pt(n,e)}function Yp(n,e,t,o){const r=_(e),i=q(r),s=K(e),l=Zl(t," ",o);return n.doc.localUpdateBlockText(i,s,l),pt(n,e)}function xd(n,e,t,o,r){const i=n.doc.getBlockData(t,o);d(ls,i,"no block data"),d(ls,i.text,"no block text");const s=Zp(n,t,o,r),l=Zl(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),pt(n,n.getBlockById(i.id))}function Td(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=Ur(n);xd(n,e,t,o,r)}const ic=w("update-composition-text");function Jp(n){const e=n.selection.range.start;e instanceof qe||d(ic,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);d(ic,$(n,o),"not a text kind block");const r=_(o),i=q(r),s=K(o),l=n.doc.getBlockData(i,s);d(ic,l,"no block data in doc"),d(ic,l.text,"no text data in text block");const c=le(o);Vl(n,mo(o),t,c,l.text)}function Kp(n){wb(n)}function Vr(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const cs=w("delete-block-text");function Dd(n,e,t,o,r){if(!n.isBlockWritable(e))return cs.error("block is not writable"),0;d(cs,$(n,e),"block is not a text kind block");const i=_(e),s=q(i),l=K(e),c=n.doc.getBlockData(s,l);d(cs,c,"no block data in doc"),d(cs,c.text,"no text data in text block");let a=t;ut(e,t)||(a=Ao(e,a));let u=t+o;d(cs,u<=G(n,e),`invalid offset and count: ${t}, ${o}`),ut(e,u)||(u=cr(e,u));const f=u-a,m=cp(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const Sd=w("break-text-block");function Xp(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function qr(n,e,t,o){d(Sd,$(n,e),`block is not a text kind block: ${ie(e)}`),d(Sd,t>=0&&t<=G(n,e),`invalid offset: ${t}`);const r=_(e),i=q(r),s=K(e),l=o!=null&&o.copyBlockAttributes?Xp(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===G(n,e))){const p=t===0?s:s+1,b={...Zn(""),...l,...o==null?void 0:o.newBlockData},k=Pe(n,e.id,0),v=Vr(n,i,p,b,k);return{block:e,newBlock:v}}d(Sd,ut(e,t),"not a valid offset");const c=pt(n,e),{right:a}=kt(c,t),u=at(a);u>0&&Dd(n,e,t,u);const f={...Zn(a),...l,...o==null?void 0:o.newBlockData},m=Vr(n,i,s+1,f,Pe(n,f.id,0));return{block:e,newBlock:m}}const Vv=w("prepare-insert-new-block");function qv(n,e,t){if(e&&t!==void 0&&t!==null){const a=n.getContainerById(e),u=Me(a);return d(Vv,t>=0&&t<=u.length,`invalid blockIndex: ${t}`),{containerId:e,blockIndex:t}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(e=q(_(r)),t=K(r),!$(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===G(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const c=qr(n,r,s).newBlock;return{containerId:e,blockIndex:K(c)}}const Wv=w("auto-insert-block");function e0(n,e,t,o,r,i){const s=qv(n,t,o);d(Wv,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},c={anchor:l,focus:l};return Vr(n,s.containerId,s.blockIndex,e,r!=null?r:c,i)}const Gv=w("delete-block");function sc(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{sc(n,i,t)})}))}function Ld(n,e,t){const o=_(e),r=q(o),i=K(e),s=n.doc.getBlockData(r,i);return d(Gv,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,We(n,{anchor:t.start,focus:t.end})),s}function Md(n,e,t){return n.undoManager.runInGroup(()=>{const o=_(e);Qt(o)===1&&n.insertTextBlock("",q(o),0);let r=t?go(n,t):null;if(!r){const l=n.selection.range;Vp(e,l)?r=qp(n,e):r=l}const i=Ld(n,e,r),s=[];return sc(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function Zv(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{sc(n,r,t)}),n.doc.localDeleteChildContainers(t)}function t0(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{sc(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Rd=w("merge-text-block");function n0(n,e,t){d(Rd,$(n,e),"only text block can be merged"),d(Rd,$(n,t),"only text block can be merged");const o=yo(n,e),r=yo(n,t),i=o.text,s=r.text;d(Rd,i&&s,"block data has no text");const l=_(e),c=q(l),a=K(e),u=G(n,e),f=xd(n,s,c,a,u),m=Pe(n,e,at(i));return Md(n,t,m),f}const En=w("clear-selected-contents");function lc(n,e){d(En,$(n,e.block),"not a text kind block");const{start:t,end:o}=e;d(En,t.isSimple(),"not a simple block position"),d(En,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;d(En,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function o0(n,e,t){const o=q(e),r=Me(e),i=t.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});t.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function Qv(n,e){const{block:t,start:o,end:r}=e;if($(n,t)){lc(n,e);return}if(Ke(t)||o.isSimple()){d(En,r.isSimple(),"invalid range");const s=_(t),l=K(t),c=n.insertTextBlock("",q(s),l);n.selection.selectBlock(c,0),n.deleteBlock(t);return}d(En,ce(n,t),"invalid block kind"),d(En,!o.isSimple()&&!r.isSimple(),"invalid range"),sr(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{o0(n,s,{focus:l===0})})}function Yv(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(d(En,t.length>0,"no selected block"),t.length===1){Qv(n,t[0]);return}const o=t[0],r=o.block,i=_(r);d(En,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if($(n,r)){lc(n,o);const u=Pe(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),$(n,l)){lc(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(u);return}n.deleteBlock(l),n.selection.setRange(u);return}if($(n,l)){lc(n,s),t.slice(0,t.length-1).reverse().forEach(u=>n.deleteBlock(u.block)),n.selection.selectBlock(s.block,0);return}if(t.length===Qt(i)){o0(n,i,{focus:!0});return}const c=ye(r),a=fe(l);d(En,c||a,"no prev or next block"),t.forEach(u=>n.deleteBlock(u.block))}function Od(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),Yv(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const Jv=w("core");function r0(n,e,t){const o=_(e),r=q(o),i=K(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),pt(n,e)}function i0(n,e,t){if(!n.isBlockWritable(e)){Jv.error("block is not writable");return}const o=n.getBlockText(e),r=dt.diff(o,t);r0(n,e,r)}function cc(n,e,t){const o=pt(n,e),r=typeof t=="string"?bo(t):t,i=dt.diff(o,r);return r0(n,e,i)}const as=w("update-block-data");function ac(n,e,t,o){const r=_(e),i=q(r),s=K(e),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),u=new Set(Object.keys(t));return a.forEach(m=>{if(!u.has(m)){if(m==="id"||m==="type"||m==="text")return;as.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(t).forEach(([m,p])=>{d(as,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const b=l[m];if(p==null){b!=null&&(as.debug(`delete key: ${m}`),c.delete.push(m));return}b!==p&&(_i.default(b,p)||m==="text"&&dt.diff(b,p).length===0||(a.has(m)?(as.debug(`replace key: ${m}`),c.delete.push(m)):as.debug(`insert key: ${m}`),c.insert[m]=p))}),n.doc.localUpdateBlockData(i,s,c,o),yo(n,e)}function s0(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Fd(n,e,t){if(!ce(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=Tt(n,e).getChildContainers(n,e)[0],i=$e(r);Fd(n,i,t)}function dr(n){const e=[];let t={};return n.forEach(o=>{e.push(...o.blocks.root);const{root:r,...i}=o.blocks;t={...t,...i}}),{blocks:{...t,root:e},meta:{},comments:{}}}const us=w("clone-block");function ko(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(u,f)=>(d(us,t!==f,"invalid child block"),ko(n,u,t,o)));let i={};const s=new Map,l=Q.default(t);l.children&&(l.children=l.children.map(u=>{const f=N(),m=e.blocks[u];d(us,Array.isArray(m),"invalid child blocks");const p=m.map(T=>ko(n,e,T,o)),b=dr(p),{root:k,...v}=b.blocks;return i={...i,...v},i[f]=b.blocks.root,s.set(u,f),f}));const c=Array.from(s.entries()),a=u=>{for(const f of c){const[m,p]=f;{const b=`${m}/`;if(u.startsWith(b)){const k=u.substring(b.length),v=`${p}/${k}`;return us.debug(`replace key: ${u} -> ${v}`),v}}{const b=`${m}_`;if(u.startsWith(b)){const k=u.substring(b.length),v=`${p}_${k}`;return us.debug(`replace key: ${u} -> ${v}`),v}}}return u};return Array.from(Object.entries(l)).forEach(([u,f])=>{const m=a(u);m!==u&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((u,f)=>o.containerIdMap.set(f,u))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Pd(n,e,t,o){const r=e.blocks[t];d(us,Array.isArray(r),"invalid child blocks");const i=r.map(l=>ko(n,e,l,o));return dr(i)}function Nd(n,e,t){const o=e.blocks.root.map(r=>ko(n.editorBlocks,e,r,t));return Q.default(dr(o))}const l0=w("insert-doc");function c0(n,e,t,o,r){if(ce(n,e)){l0.warn("failed to insert doc into a complex block");return}const i=Nd(n,o,r),s=_(e),l=K(e),c=q(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var E,R,L;Object.entries(i.blocks).forEach(([F,V])=>{F!=="root"&&n.doc.localInsertChildContainer(F,V)});const a=i.blocks.root;if(Ke(e)){n.deleteBlock(e);let F;a.reverse().forEach(V=>{const ee=n.insertBlock(c,l,V);F||(F=ee)}),F&&n.selection.selectBlock(F,G(n,F));return}if(d(l0,$(n,e),"not a text block"),Ie(n,e)){const F=K(e);let V;a.forEach((ee,se)=>{const pe=n.insertBlock(c,F+se,ee);se===a.length-1&&(V=pe)}),V&&n.selection.selectBlock(V,G(n,V));return}if(a.length===1){const F=a[0];if(Qi(n,F.type)){n.insertTextToBlock(e,t,(E=F.text)!=null?E:[]);return}n.breakTextBlock(e,t),n.insertBlock(c,l+1,F);return}const u=t===G(n,e),f=t===0,m=a[0],p=a[a.length-1];let b;!u&&!f?b=n.breakTextBlock(e,t,{forceInsertAfter:!0}):b=e;const k=f?l:l+1;u?(b=n.insertBlock(c,l+1,p),n.selection.selectBlock(b,G(n,b))):(n.selection.selectBlock(b,0),Qi(n,p.type)?n.insertTextToBlock(b,0,(R=p.text)!=null?R:[]):n.insertBlock(c,k,p));const v=n.selection.range;let T=k;Qi(n,m.type)?f?(n.insertBlock(c,k,m),T+=1):n.insertTextToBlock(e,t,(L=m.text)!=null?L:[]):(n.insertBlock(c,k,m),T+=1),a.slice(1,a.length-1).reverse().forEach(F=>{n.insertBlock(c,T,F)}),n.selection.setRange(v)}),n.doc.endBatchUpdate()}function $d(n,e,t,o,r){const i=Nd(n,o,r),s=q(e),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,u])=>{a!=="root"&&n.doc.localInsertChildContainer(a,u)}),i.blocks.root.reverse().forEach(a=>{const u=n.insertBlock(s,t,a);l.push(u)})}),l}function a0(n,e,t){const o=Qt(e);$d(n,e,o,t);for(let r=0;r<o;r++){const i=$e(e);n.deleteBlock(i)}}const ds=w("add-text-attribute");function Kv(n,e,t,o){const{start:r,end:i}=t;d(ds,r.blockId===i.blockId&&r.blockId===z(e),"invalid range"),d(ds,o,"invalid attribute name");const s=n.getBlockText(e),l=zr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function u0(n,e,t,o,r){const{start:i,end:s}=t;d(ds,i.blockId===s.blockId&&i.blockId===z(e),"invalid range"),d(ds,o,"invalid attribute name");const l=n.getBlockText(e),c=ts(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,c),c}function Wr(n,e,t,o,r){const{start:i,end:s}=t;d(ds,i.blockId===s.blockId&&i.blockId===z(e),"invalid range");const l=n.getBlockText(e),c=Cp(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,c),c}function d0(n,e,t,o){const r=tn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!$(n,s))return;if(Ie(n,s)){o(n,z(s),e,t);return}const a=We(n,{anchor:l,focus:c});e==="color"||e==="backgroundColor"?Wr(n,s,a,e,t):(Wr(n,s,a,"color",null),Wr(n,s,a,"backgroundColor",null))})})}function h0(n,e,t){const o=tn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!$(n,i))return;if(Ie(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,z(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,z(i),"backgroundColor",null);return}const c=We(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Wr(n,i,c,"color",null),(e==="clearBackground"||e==="clearAll")&&Wr(n,i,c,"backgroundColor",null)})})}function _d(n,e){const t=tn(n,{simpleBlockOnly:!0}).filter(s=>$(n,s.block));if(t.length===0)return[null,null];const o=s=>{if(G(n,s.block)===0)return e(n,z(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return vp(l.offset,c.offset-l.offset,a)};let[r,i]=o(t[0]);return r===null&&i===null?[r,i]:(t.forEach(s=>{const[l,c]=o(s);l===null||r===null?r=null:r=l===r?r:null,c===null||i===null?i=null:i=c===i?i:null}),[r,i])}const St=w("adjust-selection-pos");function f0(n){const e=[];for(;n;){const t=_(n);if(e.unshift(t),Ae(t))return e;const o=j(t);d(St,o,"child container has not parent container"),n=o}d(St,!1,"should not come here: getParentContainers")}function m0(n,e){for(;e;){const t=_(e);if(t===n)return e;const o=j(t);d(St,o,"could not find parent block for a child container"),e=o}d(St,!1,"no parent block in specified container")}function Xv(n,e){const t=f0(n),o=f0(e);d(St,t.length>0&&o.length>0,"block has not parent container"),d(St,t[0]===o[0],"root container does not equal");let r=t[0];for(let l=1;l<t.length||o.length;l++)if(t[l]!==o[l]){r=t[l-1];break}const i=m0(r,n),s=m0(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function g0(n,e){let t=j(e);for(d(St,t,"element is not in a block");t;){const o=_(t);d(St,Xt(o),"not a child container");const r=j(o);if(d(St,r,"child container has not parent block"),r===n)return o;t=r}d(St,!1,"failed to find parent container in complex block")}function uc(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof qe&&t instanceof qe?{anchor:e,focus:t}:e instanceof en&&t instanceof en?zl(n,o,e,t):null;const i=_(o),s=_(r);if(i===s)return e instanceof en&&(e=U(o,0,"home")),t instanceof en&&(t=U(r,G(n,r),"end")),d(St,e instanceof qe,"not valid position type"),d(St,t instanceof qe,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof qe&&t instanceof en){const b=n.getContainerById(t.childContainerId);if(b===i)return{anchor:t,focus:t};const k=j(i);if(k&&k===j(b)){const v=xe(k,q(i)),T=xe(k,q(b));return zl(n,k,v,T)}}return null}const l=Dl(o,r)>0,{newBlock1:c,newBlock2:a}=Xv(o,r);if(c===a){const b=c,k=g0(b,o),v=g0(b,r);return e=xe(c,q(k)),t=xe(c,q(v)),St.debug(`select in complex block: ${k.id}, ${v.id}`),zl(n,b,e,t)}let u=l?G(n,c):0;c===o&&e instanceof qe&&(u=e.offset);let m=l?0:G(n,a);return a===r&&t instanceof qe&&(m=t.offset),e=U(c,u,l?"end":"home"),t=U(a,m,l?"home":"end"),{anchor:e,focus:t}}const ey=w("move-complex-block-position");function ty(n,e,t){const o=n.getBlockById(e.blockId);d(ey,ce(n,o),"is not a complex block");const r=Tt(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?xe(o,q(s)):null}const hs=w("move-simple-block-position");function p0(n,e){const t=yt(n,e,{visibleOnly:!0});d(hs,t.length>0,"complex block has not any child container");const o=t[0];return $e(o)}function C0(n,e){const t=yt(n,e,{visibleOnly:!0});d(hs,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Je(o)}function A0(n,e,t){const o=t?p0(n,e):C0(n,e);return ce(n,o)?A0(n,o,t):o}function ny(n,e){const t=n.getBlockById(e.blockId);return ce(n,t)&&e.offset===0?p0(n,t):rr(t)}function oy(n,e){const t=n.getBlockById(e.blockId);return ce(n,t)&&e.offset===1?C0(n,t):or(t)}function Hd(n){return n==="ArrowLeft"||n==="ArrowUp"}function jd(n,e,t){const o=_(e);if(Ae(o))return null;const r=j(o);d(hs,r,"child container has not parent block"),d(hs,ce(n,r),"is not a complex block");const i=Tt(n,r).getNextContainer(n,r,o,t);return i?Hd(t)?Je(i):$e(i):jd(n,r,t)}function ry(n,e,t){const o=_(e);if(Ae(o))return null;const r=j(o);if(d(hs,r,"child container has not parent block"),Hd(t)){const l=ye(r);if(l)return l}else{const l=fe(r);if(l)return l}const i=jd(n,r,t);if(i)return i;let s=r;for(;!Ae(_(s));)s=j(_(s));return Hd(t)?ye(s):fe(s)}function iy(n,e,t){return!ce(n,e)||Tt(n,e).enableKeyboardSelect?e:A0(n,e,t==="ArrowDown"||t==="ArrowRight")}function sy(n,e,t){const o=n.getBlockById(e.blockId),i=me(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?ny(n,e):oy(n,e);if(s||(s=jd(n,o,t),s||(s=ry(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Ae(_(o)))return null;const l=n.insertTextBlock("",q(n.rootContainer),Qt(n.rootContainer));return U(l,0,"home")}return null}if(s=iy(n,s,t),$(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return Fb(n,s,o,e,l);if(t==="ArrowUp")return Ob(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?U(s,G(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?U(s,0,"home"):null}function ly(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if($(n,r))return o;const i=fe(r);if(i)return U(i,0,"home");if(!Ae(_(r))||n.readonly)return o;const s=n.insertTextBlock("",q(n.rootContainer),Qt(n.rootContainer));return U(s,0,"home")}function cy(n,e,t){const o=n.selection.range;let r;if(o instanceof Xe)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=ly(n,e,o):r=sy(n,o.getFocusedPos(),e);else if(r=ty(n,o.focus,e),t==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(e==="ArrowLeft"||e==="ArrowUp"){const l=Je(s);r=U(l,0,"home")}else{const l=$e(s);r=U(l,G(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:uc(n,o.anchor,r):null}function wo(n,e,t){const o=cy(n,e,t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(e==="ArrowLeft"||e==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function b0(n){return wo(n,"ArrowLeft","move"),!0}function v0(n){return wo(n,"ArrowRight","move"),!0}function y0(n){return wo(n,"ArrowUp","move"),!0}function k0(n){if(wo(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=_(e);if(Ae(t)||Je(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",q(o),Qt(o)),!0}function w0(n){return wo(n,"ArrowDown","select"),!0}function B0(n){return wo(n,"ArrowLeft","select"),!0}function E0(n){return wo(n,"ArrowRight","select"),!0}function I0(n){return wo(n,"ArrowUp","select"),!0}const x0=w("word-offset");function zd(n,e){const t=n.selection.range.focus;d(x0,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(Ie(n,o))return U(o,0,"home");if(t.offset===0||!$(n,o)){const s=ye(o);if(!s)return null;const l=U(s,G(n,s),"end");if(e==="select"&&$(n,s)){const c=bd(n,s,l.offset);return U(s,c,"normal")}return l}const r=bd(n,o,t.offset);return U(o,r,"normal")}function Ud(n,e){const t=n.selection.range.focus;d(x0,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(Ie(n,o))return U(o,0,"end");if(t.offset===G(n,o)||!$(n,o)){const s=fe(o);if(!s)return null;const l=U(s,0,"home");if(e==="select"&&$(n,s)){const c=vd(n,s,l.offset);return U(s,c,"end")}return l}const r=vd(n,o,t.offset);return U(o,r,"normal")}function T0(n){if(!n.selection.range.focus.isSimple())return!1;const t=zd(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function D0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Ud(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function S0(n){if(!n.selection.range.focus.isSimple())return!1;const t=zd(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function L0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Ud(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function Vd(n,e){if(!ce(n,e))return e;const o=Tt(n,e).getChildContainers(n,e)[0],i=Me(o)[0];return Vd(n,i)}function qd(n,e){if(!ce(n,e))return e;const t=Tt(n,e).getChildContainers(n,e),o=t[t.length-1],r=Me(o),i=r[r.length-1];return qd(n,i)}function M0(n){const e=qd(n,Je(n.rootContainer)),t=U(e,G(n,e),"end");return n.selection.setSelection(t),!0}function R0(n){const e=Vd(n,n.getFirstBlock()),t=U(e,0,"home");return n.selection.setSelection(t),!0}function O0(n){const e=Vd(n,n.getFirstBlock()),t=U(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Wd(n){const e=qd(n,Je(n.rootContainer)),t=U(e,G(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const F0=w("line-offset");function P0(n){const e=n.selection.range.focus;d(F0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!$(n,t))return U(t,0,"home");let r=op(t,e).start;const{next:i}=_l(t,r);return i&&Nt(i)&&Zi(i)==="br"&&(r+=1),U(t,r,"home")}function N0(n){const e=n.selection.range.focus;d(F0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===G(n,t)||!$(n,t))return U(t,G(n,t),"end");const o=op(t,e);return U(t,o.end,"end")}function $0(n){if(!n.selection.range.focus.isSimple())return!1;const t=P0(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function _0(n){if(!n.selection.range.focus.isSimple())return!1;const t=N0(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function H0(n){if(!n.selection.range.focus.isSimple())return!1;const t=P0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function j0(n){if(!n.selection.range.focus.isSimple())return!1;const t=N0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const z0=w("find-block-position");function ay(n,e,t,o){d(z0,ce(n,e),"is not a complex block");const r=Tt(n,e).getChildContainers(n,e);d(z0,r.length>0,"complex block has not any child container");const i=Kt(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,c=Wg(n,e,s,l);return Gd(n,c,t,o)}function Gd(n,e,t,o){if(ce(n,e))return ay(n,e,t,o);const r=z(e);let i=Number.MAX_SAFE_INTEGER;const s=Kt(n,t,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=U(r,0,"home");const u=G(n,e);for(let f=0;f<=u;f++){const m=U(r,f,"normal"),p=Kt(n,e,m),b=bn(p,l,c);b<i&&(i=b,a=m)}return a}const U0=w("page-offset");function uy(n,e){const t=jp(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<Ov(n))return n.getFirstBlock();const i=ye(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ye(s)}return n.getFirstBlock()}function dy(n,e){const t=jp(n)*.9,o=e.getBoundingClientRect(),r=Fv(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=fe(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=fe(l)}return n.getLastBlock()}function V0(n){const e=n.selection.range.focus;d(U0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=uy(n,t);let r;return o===n.getFirstBlock()?r=U(o,0,"home"):r=Gd(n,o,t,e),r}function q0(n){const e=n.selection.range.focus;d(U0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=dy(n,t);let r;return o===n.getLastBlock()?r=U(o,G(n,o),"end"):r=Gd(n,o,t,e),r}function W0(n){if(!n.selection.range.focus.isSimple())return!1;const t=V0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function G0(n){if(!n.selection.range.focus.isSimple())return!1;const t=q0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function Z0(n){if(!n.selection.range.focus.isSimple())return!1;const t=V0(n);if(!t)return!1;const o=uc(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function Q0(n){if(!n.selection.range.focus.isSimple())return!1;const t=q0(n);if(!t)return!1;const o=uc(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const fs=w("select-all");function Y0(n,e){const t=$e(n),o=Je(n);return e.start.offset===0&&e.start.blockId===z(t)&&e.end.offset===G(e.getEditor(),o)&&e.end.blockId===z(o)}function hy(n,e){const t=e.getEditor(),o=Tt(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=z(n);return e.start.blockId===s&&e.start.childContainerId===q(r)&&e.end.blockId===s&&e.end.childContainerId===q(i)}function fy(n,e){d(fs,e,"no parent block"),d(fs,ce(n,e),"not a complex block");const t=Tt(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(We(n,{anchor:xe(e,q(o)),focus:xe(e,q(r))}))}function J0(n,e){const t=_(e);Zd(n,t)}function K0(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&$(n,e)){const r=t.start,i=t.end,s=G(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return M(n.rootContainer,"select-all"),J0(n,$e(n.rootContainer)),!1}return d(fs,!t.isSimple(),"invalid range type"),hy(e,t)?(J0(n,e),!1):(d(fs,e,"no parent block"),d(fs,ce(n,e),"not a complex block"),fy(n,e),!0)}function Zd(n,e){const t=Me(e),o=t[0],r=t[t.length-1],i=U(o,0,"home"),s=U(r,G(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function X0(n){Wd(n),n.focus()}const Qd=w("selected-block-to-doc");function e2(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{e2(n,i,t)}),t.blocks[o]=Q.default(r)})}function dc(n,e){const t=me(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=Q.default(yo(n,e.block));if($(n,e.block)){const i=e.start,s=e.end;if(d(Qd,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Ge(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Ke(e.block))return{blocks:{root:[o]},meta:{},comments:{}};d(Qd,ce(n,e.block),"not complex block"),d(Qd,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return e2(n,o,r),r}function Yd(n,e){const t=U(e,0,"normal"),o=U(e,G(n,e),"end");return dc(n,{block:e,start:t,end:o})}const my=w("block-to-doc");function gy(n,e){d(my,e.length>0,"invalid params, no blocks");const t=e.map(o=>Yd(n,o));return dr(t)}function hc(n){const t=n.selection.range.getSelectedBlocks().map(o=>dc(n,o));return dr(t)}function t2(n,e){const t=n.getContainerById(e),i=Me(t).map(s=>({start:U(s,0,"home"),end:U(s,G(n,s),"end"),block:s})).map(s=>dc(n,s));return dr(i)}const fc=w("editor-selection");class py{constructor(e){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(Vp(t,i)){fc.debug("adjust selection because remote deleted current block");const s=qp(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=z(t);this.caret=new Lv(e);const r=U(o,0,"normal");this._range=We(e,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const e=this.range.focus;return this.editor.getBlockById(e.blockId)}getStartBlock(){const e=this.range.start;return this.editor.getBlockById(e.blockId)}getEndBlock(){const e=this.range.end;return this.editor.getBlockById(e.blockId)}selectBlock(e,t,o){const r=U(e,t,"normal");let i;o&&(i=U(e,o,"normal")),this.setSelection(r,i)}setSelection(e,t,o){if(t||(t=e),this.verifyPos(e),this.verifyPos(t),!this.selectionChanging(e,t))return this.range;const r=We(this.editor,{anchor:e,focus:t});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),ne(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!_v(this.editor,r))&&H(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(e,t){return this.setSelection(e.anchor,e.focus,t)}updateSelection(){this.caret.update(),Mv(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(e,t){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const e=this.range.focus;if(!Wn(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=Kt(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){$v(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=G(this.editor,t)||d(fc,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||d(fc,!1,"invalid complex block position, no container found")}}updateFocusedBlock(e){if(e&&this.range.start.blockId===e.start.blockId)return;let t;e&&e.start.blockId===e.end.blockId&&(t=this.editor.findBlockById(e.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;t&&ne(t,"focused")&&(H(t,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,t!=null?t:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(e){const t=hc(this.editor);return e==="text"?is(this.editor,t):e==="markdown"?ss(this.editor,t):Gp(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{H(e,"focused"),H(e,"child-focused")})}setBlockFocused(e){if(ne(e,"focused"))return!1;M(e,"focused");let t=_(e);for(;Xt(t);){const o=j(t);d(fc,o,"parent block not found"),M(o,"child-focused"),t=_(o)}return!0}}function Cy(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,G(n,t))}function Ay(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!$(n,t))return;let o=zd(n,"select"),r=Ud(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=U(t,0,"home")),r.blockId!==i&&(r=U(t,G(n,t),"end")),n.selection.setSelection(o,r)}class by{constructor(e){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",e=>{this.mouseDownEvent=e;const t=Qg(this.editor,e.x,e.y);if(t){if(t instanceof kn)return;const o=this.editor.selection.range;if(e.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,t.focus),this.startPos=t.start}else this.editor.selection.setSelection(t.anchor,t.focus),this.startPos=t.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",e=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-e.x)<3&&Math.abs(this.mouseDownEvent.y-e.y)<3)return;const t=Ul(this.editor,e.x,e.y);if(!t)return;const o=uc(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",e=>{this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){Ay(this.editor)}handleTripleClick(e){Cy(this.editor)}}function vy(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function yy(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const n2=w("delete-text");function o2(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof qe||d(n2,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(n2,$(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!ut(s,l-t)){const c=Ao(s,l);t=l-c}}else if(e==="forward"&&l+t>G(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function r2(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const ky=w("handle-backspace");function Jd(n,e){if(!Ie(n,e))return;const t=_(e);Qt(t)!==1&&n.deleteBlock(e)}function wy(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if($(n,o))if(t.offset===0){if(r2(n,o))return;const r=ye(o);if(r){if(!n.isBlockWritable(r))return;if($(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ce(n,r)){Jd(n,o);const i=Hr(n,r);i?n.selection.selectBlock(i,G(n,i)):n.selection.selectBlock(r,0,G(n,r))}else Jd(n,o),d(ky,Ke(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=_(o);if(Xt(i)){const s=Ug(n,i);if(s){if(!n.isBlockWritable(s))return;Jd(n,o),n.selection.selectBlock(s,G(n,s))}}}}else o2(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=K(o),i=_(o);n.insertTextBlock("",q(i),r),n.deleteBlock(o)}}function By(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if($(n,o))if(t.offset===G(n,o)){const r=fe(o);if(r){if(!n.isBlockWritable(r))return;$(n,r)?n.mergeTextBlock(o,r,{focus:!0}):Ie(n,o)?n.deleteBlock(o,Pe(n,r,0)):n.deleteBlock(r)}}else o2(n,"forward",1,null);else{const r=K(o),i=_(o);n.insertTextBlock("",q(i),r),n.deleteBlock(o)}}function Ey(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!ce(n,r))return!1;if(Wn(t))return!0;const s=sr(n,r,t,o),l=yt(n,r);return s.length===l.length}function Iy(n,e){if(Ey(n)){const o=n.getFocusedBlock(),r=K(o),i=q(_(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const t=n.getFocusedBlock();if($(n,t)){if(Ie(n,t)&&r2(n,t))return;const o=n.selection.range.start,r=n.breakTextBlock(t,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function xy(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!$(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const Ty=w("input-handler-actions");function Dy(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Iy(n),!0))}function Sy(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(By(n),!0))}function Ly(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(wy(n),!0))}function My(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(xy(n),!0))}function Ry(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e)}).catch(e=>{Ty.error(e)}),!0)}const mc={ArrowDown:k0,ArrowUp:y0,ArrowLeft:b0,ArrowRight:v0,"Shift+ArrowDown":w0,"Shift+ArrowUp":I0,"Shift+ArrowLeft":B0,"Shift+ArrowRight":E0,"CtrlOrCmd+ArrowLeft":T0,"CtrlOrCmd+ArrowRight":D0,"CtrlOrCmd+Shift+ArrowLeft":S0,"CtrlOrCmd+Shift+ArrowRight":L0,"CtrlOrCmd+ArrowUp":R0,"CtrlOrCmd+ArrowDown":M0,"CtrlOrCmd+Shift+ArrowUp":O0,"CtrlOrCmd+Shift+ArrowDown":Wd,"CtrlOrCmd+A":K0,Home:H0,End:j0,"Shift+Home":$0,"Shift+End":_0,PageUp:W0,PageDown:G0,"Shift+PageUp":Z0,"Shift+PageDown":Q0,"CtrlOrCmd+Z":vy,"CtrlOrCmd+Shift+Z":yy,Enter:Dy,Delete:Sy,Backspace:Ly,"Shift+Enter":My,"CtrlOrCmd+Shift+V":Ry};function i2(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function s2(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);l&&(i.src=l)}return}const o=e.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=t.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{s2(n,l,t)})})}function l2(n,e,t){if(t.size===0)return;e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,t):s2(e,r,t)})}async function Oy(n,e){const t=e.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(t),r=new Map;if(t.length!==o.length)return r;for(let i=0;i<t.length;i++)r.set(t[i],o[i]);return r}function Fy(n,e){var i,s;const o=e.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function Py(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(Fy(n,e)){const s=Array.from(Object.keys(o));r=await Oy(n,s),l2(n,e,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&l2(n,e,i)}async function Ny(n,e,t){await Py(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Ke(i)){const s=_(i),l=n.getBlockIndex(i),[c]=n.insertDocAt(s,l+1,e,t);c&&n.selection.selectBlock(c,G(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=Ur(n);n.insertDoc(s,l,e,t)}})}const $y=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function _y(n){let e;for(const t of $y)if(e=n[t],e)break;return e||null}function c2(n,e,t){if(e.type==="embed"){const s=e.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))t.add(l);return}const o=e.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&t.add(i.attributes.src)});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{c2(n,l,t)})})}function Hy(n,e){const t=new Set;return e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{t.add(s)}):c2(e,r,t)}),Array.from(t)}function gc(n,e){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Ko(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function pc(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=Hy(n,e),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),e.meta={...t,resources:r}}function jy(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=hc(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),pc(n,o);const i=rc(n,o),s=ss(n,o),l=gc(i,o);e.clipboardData.setData("text/html",l),e.clipboardData.setData("text/plain",s),e.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Cc(n,e){const t=Yd(n,e);pc(n,t);const o=rc(n,t),r=ss(n,t),i=gc(o,t);return Du([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class zy{constructor(e){h(this,"editor");h(this,"handlers",[]);h(this,"onPasteText",async e=>{const t=new DataTransfer;t.setData("text/plain",e);const o=await this.editor.dataConverter.fromData(this.editor,t);o&&this.pasteDocs(o,null)});this.editor=e}onInsertText(e,t){if(!$(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Ur(this.editor);this.handleBeforeInsertText(o,r,i,t)||(this.defaultInsertText(this.editor,o,r,i,t),this.handleAfterInsertText(o,r,i,t),this.editor.selection.updateLastCaretRect())}onKeyDown(e){if(this.handleBeforeKeyDown(e))return!0;const t=this.defaultHandleKeydown(this.editor,e);return this.handleAfterKeyDown(e)?!0:t}onChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleChanged&&o.handleChanged(this.editor,e)}}onRemoteChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,e)}}onCompositionStart(e){this.editor.updateCompositionText("",!1);const{containerId:t,blockIndex:o,offset:r}=Ur(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,t,o,r)}}onUpdateCompositionText(e,t,o){this.editor.updateCompositionText(t,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Ur(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(e){jy(this.editor,e,(t,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,e)===!0)return}if(this.onCopy(e),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Ke(o)&&this.editor.deleteBlock(o)}else Od(this.editor)}onPaste(e){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;this.editor.dataConverter.fromData(this.editor,e.clipboardData).then(async o=>{o&&this.pasteDocs(o,e)})}onFocus(){M(this.editor.rootElement,"active")}onBlur(){H(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);t!==-1&&this.handlers.splice(t)}handleBeforeInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,e,t,o,r))return!0}return!1}handleAfterInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,e,t,o,r))return!0}return!1}handleBeforeKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}handleAfterKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}defaultInsertText(e,t,o,r,i){Td(this.editor,i)}defaultHandleKeydown(e,t){return i2(this.editor,t)?(t.preventDefault(),t.stopPropagation(),!0):!1}async pasteDoc(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,e))return}const t={blockIdMap:new Map,containerIdMap:new Map};await Ny(this.editor,e,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,e,t))return}}async pasteDocs(e,t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,t,e))return}const o=_y(e);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,t,e))return}}}destroy(){this.handlers.forEach(e=>{var t;(t=e.destroy)==null||t.call(e,this.editor)}),this.handlers=[]}}function Uy(n,e,t){const o=Pr(e,t);return o.remove(),o}w("copy-dom-attributes");const a2=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function Vy(n,e){for(let l=0;l<a2.length;l++){const c=a2[l];e[c]=n[c]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const c=t[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];t.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{e.setAttribute(l.name,l.value)}),i.forEach(l=>{e.setAttribute(l.name,l.value)}),s.forEach(l=>{e.removeAttribute(l.name)})}function u2(n){const e=Array.from(n.childNodes).filter(t=>!rg(t));return e.forEach(t=>{t.remove()}),e}function d2(n,e,t){var a;const o=n.getContainerById(e),r=Pr(o,t),i=mo(r),s=n.doc.getBlockData(e,t),l=me(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=u2(u);u2(r),f.forEach(p=>{r.appendChild(p)});const m=Nl(u);if(m){const p=Nl(r);p&&p.remove(),r.appendChild(m)}Vy(u,r)}kg(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const qy=w("transform-selection");function h2(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;d(qy,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const a=dt.transformCursor(i.offset,t,o);l=U(e,a,"normal")}let c=s;if(s.blockId===e){const a=dt.transformCursor(s.offset,t,o);c=U(e,a,"normal")}return We(n,{anchor:l,focus:c})}const Wy=w("handle-block-text-changed");function Gy(n,e,t,o,r){const i=n.getContainerById(e),s=Pr(i,t),l=n.doc.getBlockData(e,t);if(d(Wy,l.text,"no block text"),pg(n,s).setBlockText(n,s,l.text),!r){const c=h2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Zy(n,e){const t=Q.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function f2(n,e,t,o){const r=me(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function Qy(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{f2(n,i,o,{child:!0})}),f2(n,r,o,{child:!1})}const on=w("editor-doc");class Yy extends zi{constructor(t,o,r){super();h(this,"localEvents",[]);this.editor=t,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(t){this.localEvents.push(t)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(t){return this.externalDoc.getContainerBlocks(t)}getBlockData(t,o){return this.externalDoc.getBlockData(t,o)}verifyBlockWritable(t,o){const r=this.editor.getBlockByIndex(t,o);d(on,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){d(on,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;d(on,l,`no text, ${t}, ${o}`);const c=h2(this.editor,s.id,r,!0),a=dt.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(t,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(t,o,r,i){d(on,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const u=Array.from(r.delete).filter(m=>m!=="comments"),f=Object.keys(r.insert).filter(m=>m!=="comments");(u.length>0||f.length>0)&&d(on,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=Q.default(this.getBlockData(t,o)),c=Q.default(Zy(l,r));this.localEvents.forEach(u=>u.onBeforeUpdateBlockData(t,l.id,l,c,i));const a=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(go(this.editor,i)),a}localInsertBlock(t,o,r,i,s){d(on,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return this.editor.selection.setRange(go(this.editor,i),s),l}localDeleteBlock(t,o,r){d(on,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=Q.default(this.getBlockData(t,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(t,o,i,r));const s=this.externalDoc.localDeleteBlock(t,o,r);return this.editor.selection.setRange(go(this.editor,r)),s}localDeleteChildContainers(t){return d(on,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=Q.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainer(t,o){return d(on,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(t,Q.default(o))),this.externalDoc.localInsertChildContainer(t,o)}onRequestReload(t){on.debug(`reload doc: ${t}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,t)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,t,o,r,i)}),Gy(this.editor,t,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,i)}),d2(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);HA(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){Qy(this.editor,t,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,r)});const i=this.editor.getContainerById(t);Uy(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(t,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,t,o,r)})}onDeleteChildContainer(t,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,t)})}onStatusChanged(t){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)})}onError(t){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,t)})}uploadResource(t,o){return this.externalDoc.uploadResource(t,o)}addResources(t){return this.externalDoc.addResources(t)}buildResourceUrl(t,o){return this.externalDoc.buildResourceUrl(t,o)}request(t,o){return this.externalDoc.request(t,o)}broadcastMessage(t){return this.externalDoc.broadcastMessage(t)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var t,o,r;return(r=(o=(t=this.externalDoc).getServerMeta)==null?void 0:o.call(t))!=null?r:{}}reset(t){on.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function m2(n,e){if(n.length===0){n.push(e);return}const t=n[n.length-1];if(!t.combinable(e)){n.push(e);return}t.combine(e)}const Kd=w("undo-action");class Gr{constructor(e,t,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=t,this.beforeRange=e.selection.range.clone().toDocRange(),this.afterRange=o}undo(e){return!1}redo(e){return!1}combinable(e){return d(Kd,e,"no other action"),!1}combine(e){d(Kd,!1,"no other")}setAfterRange(e){this.afterRange&&Kd.warn("after range has already set"),this.afterRange=e}}const Jy=w("block-action");class g2 extends Gr{constructor(t,o,r,i,s){super(t,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Q.default(i),this.blockIndex=r}deleteBlock(t,o){if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);return i?(d(Jy,this.blockIndex===K(i),"invalid block index"),Ld(t,i,go(t,o)),!0):!1}insertBlock(t,o){return Vr(t,this.containerId,this.blockIndex,Q.default(this.blockData),o),!0}}class Ky extends g2{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class Xy extends g2{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class ek extends Gr{constructor(t){super(t,q(t.rootContainer),t.selection.range.toDocRange());h(this,"actions",[])}addAction(t){m2(this.actions,t),this.afterRange=t.afterRange}undo(t){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(t)&&(o=!0)}),o}redo(t){let o=!1;return this.actions.forEach(r=>{r.redo(t)&&(o=!0)}),o}setAfterRange(t){this.afterRange=t;const o=this.actions[this.actions.length-1];!o||o instanceof Gr&&(o.afterRange||o.setAfterRange(t))}}const hr=w("update-block-data-action");class Ac extends Gr{constructor(t,o,r,i,s,l){super(t,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(hr,this.blockId===i.id,"invalid block id"),d(hr,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Q.default(i),this.afterBlockData=Q.default(s),d(hr,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){d(hr,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return d(hr,r,"no container"),ac(t,o,Ac.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){d(hr,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return d(hr,r,"no container"),ac(t,o,Ac.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=Q.default(t);return delete o.id,delete o.type,o}}const Xd=w("update-block-text-action");class ms extends Gr{constructor(t,o,r,i,s,l){super(t,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Q.default(i),this.afterRichTextData=Q.default(s),this.type=ms.calType(i,s)}static calType(t,o){d(Xd,t,"no old data"),d(Xd,o,"no new data");const i=dt.diff(t,o),s=new Set;let l=!1;const c=u=>Nm(u)?`cjk_${u}`:Fm(u)?"number":Sl(u)?"space":Pm(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(cc(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(cc(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof ms)||t.type.begin||this.type.textType!==t.type.textType||t.blockId!==this.blockId)return!1;const o=t.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(t){d(Xd,t instanceof ms,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}class p2 extends Gr{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return e.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(e){return e.doc.localInsertChildContainer(this.containerId,Q.default(this.blocks)),!0}}class tk extends p2{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class nk extends p2{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const rn=w("undo");class ok{constructor(e){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(this,"handleSelectionChange",e=>{if(this.currentGroup){this.currentGroup.setAfterRange(e.selection.range.toDocRange());return}const t=this.actions[this.actions.length-1];!t||t.afterRange||t.setAfterRange(e.selection.range.toDocRange())});this.editor=e,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(e){this.currentGroup?this.currentGroup.addAction(e):(m2(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(d(rn,!this.currentGroup,"current group already exists"),this.currentGroup=new ek(this.editor),this.groupCounter=1):(d(rn,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(rn,this.currentGroup,"current group not exists"),d(rn,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?rn.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(e){this.beginGroup();try{const t=e();return setTimeout(()=>this.editor.selection.caret.update()),t}catch(t){throw rn.error(`failed to run action: ${t.message}`),t}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const e=this.actions[this.undoCursor];if(e.undo(this.editor)){try{this.editor.selection.setRange(go(this.editor,e.beforeRange))}catch(t){rn.error(`undo: failed to restore caret pos: ${t.message}`)}return this.editor.input.handleChanged(e),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const e=this.actions[this.undoCursor];if(this.undoCursor+=1,e.redo(this.editor)){try{const t=e.afterRange;t?this.editor.selection.setRange(go(this.editor,t)):rn.warn("no after range")}catch(t){rn.error(`redo: failed to set caret pos after redo: ${t.message}`)}return this.editor.input.handleChanged(e),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var t;const e=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(t=this.actions[e])!=null?t:null}undoTo(e){for(;;){const t=this.lastAction();if(!t||t===e)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(e,t,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),dt.diff(o,r).length!==0&&this.addAction(new ms(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Ac(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(rn,t>=0,"invalid block index"),d(rn,o,"no block data"),this.addAction(new Ky(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Xy(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new tk(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new nk(this.editor,e,t)))}}class rk{async fromData(e,t){const o=t.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class ik{constructor(){h(this,"converters",[]);this.addConverter(new rk)}async fromData(e,t){let o={};for(const r of this.converters){const i=await r.fromData(e,t);i&&(o={...o,...i})}return o}addConverter(e){this.converters.push(e)}}class sk{constructor(e){h(this,"renders",[]);this.editor=e}registerRender(e){this.renders.push(e)}renderText(e,t){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,e,t);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(e,t,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,t,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(e,t,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,e,t,o,r)})}}class Se extends Ve.TypedEmitter{constructor(t){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",t=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,t))return}const o=document.elementFromPoint(t.x,t.y);if(!o){this.setHoveringBlock(null,t,null);return}let r=j(o);if((!r||!Ce(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(t),!r)){this.setHoveringBlock(null,t,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,t,i)});this.editor=t,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(t=>t.destroy()),this.filters=[],this.finders.forEach(t=>t.destroy()),this.finders=[]}addFilter(t){this.filters.push(t)}addFinder(t){this.finders.push(t)}hoveringBlockId(){return this.hoveringBlock?z(this.hoveringBlock):""}findBlockByFinders(t){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,t);if(i)return i}return null}setHoveringBlock(t,o,r){if(this.hoveringBlock===t&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==t){const s=this.hoveringBlock&&Ce(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&H(s,"hover"),t&&M(t,"hover"),this.hoveringBlock=t,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(t){return t.addCustom("standard-hovering-block",()=>new Se(t))}getParentTextContentChild(t,o){if(!$(this.editor,t))return null;const r=le(t);return o.parentElement===r?o:Pu(o)}}const C2="style-color-",A2="style-bg-color-";class lk{renderText(e,t,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(C2)?i["data-style-color"]=s.substring(C2.length):s.startsWith(A2)?i["data-style-bg-color"]=s.substring(A2.length):s.startsWith("style")&&r.push(s):typeof l=="string"&&s==="link"&&(r.push("link"),i.link=l)}),{classes:r,attributes:i}}renderBlock(e,t,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=e.selection)==null?void 0:l.range)==null?void 0:c.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Se.get(e).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(e,t,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&M(o,"focused"),Se.get(e).hoveringBlockId()===r.id&&M(o,"hover")}}function ck(n){n.editorBlocks.registerBlockClass(wt),n.editorBlocks.registerBlockClass(zg),n.editorBoxes.registerBoxClass(Lp),n.editorBoxes.registerBoxClass(Mp),n.editorBoxes.registerBoxClass(Fp),n.editorInsertions.registerInsertionClass(Pp),n.editorBlockRenders.registerRender(new lk)}function ak(n,e){ck(n),e!=null&&e.blocks&&e.blocks.forEach(t=>n.editorBlocks.registerBlockClass(t)),e!=null&&e.boxes&&e.boxes.forEach(t=>n.editorBoxes.registerBoxClass(t)),e!=null&&e.embeds&&e.embeds.forEach(t=>n.editorEmbeds.registerEmbedClass(t)),e!=null&&e.insertions&&e.insertions.forEach(t=>n.editorInsertions.registerInsertionClass(t)),e!=null&&e.decorators&&e.decorators.forEach(t=>n.editorDecorators.registerDecorator(t)),e!=null&&e.dataConverters&&e.dataConverters.forEach(t=>n.dataConverter.addConverter(t)),e!=null&&e.commandProviders&&e.commandProviders.forEach(t=>n.editorCommandProviders.registerCommandProvider(t)),e!=null&&e.textRenders&&e.textRenders.forEach(t=>n.editorBlockRenders.registerRender(t))}const b2=w("range-commands");function v2(n,e){n.forEach(t=>{t.source=e,t.children&&v2(t.children,e)})}function y2(n,e,t){const o=z(e);d(b2,o===t.start.blockId,"invalid start range"),d(b2,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);v2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),ce(n,e)&&sr(n,e,t.start,t.end).forEach(l=>{Me(l).forEach(a=>{const u=G(n,a),f=We(n,{anchor:U(a,0,"home"),focus:U(a,u,"end")}),m=y2(n,a,f);i.push(...m)})}),i}function k2(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[];return t.forEach(r=>{const i=We(e,{anchor:r.start,focus:r.end});y2(e,r.block,i).forEach(l=>{o.push(l)})}),o}function w2(n,e,t,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,e,t,o,r,{}))return i[z(e)]=c,!0;let a=!1;return ce(n,e)&&sr(n,e,t.start,t.end).forEach(m=>{Me(m).forEach(b=>{const k=G(n,b),v=We(n,{anchor:U(b,0,"home"),focus:U(b,k,"end")});w2(n,b,v,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,e,t,o,r,i)}),a}function B2(n,e,t){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(e.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,e,t,r)||n.getSelectedBlocks().forEach(l=>{const c=We(o,{anchor:l.start,focus:l.end});w2(o,l.block,c,e,t,r)}),r}const uk=w("command-providers");class E2{constructor(e){h(this,"providers",[]);this.editor=e}registerCommandProvider(e){this.providers.push(e)}getCommandProviders(){return this.providers}getCommandProvider(e){const t=this.providers.find(o=>o.id===e);return d(uk,t,`no command provider, id=${e}`),t}getCommands(e){return k2(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>B2(e,t,o))}getEmptyBlockTextAttributes(e,t){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,e,t);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function dk(n,e){const t=_(e),o=q(t),r=K(e);d2(n,o,r)}const hk=w("table-scroll");class I2{constructor(e,t,o,r,i){h(this,"handleEvent",e=>{this.handler(this.editor,e,this.data)});this.editor=e,this.dom=t,this.name=o,this.handler=r,this.data=i,t.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class fk{constructor(e){h(this,"handlers",new Map);this.editor=e}destroy(){Array.from(this.handlers.entries()).forEach(([e,t])=>{t.forEach(o=>o.destroy()),this.handlers.delete(e)})}addEventListener(e,t,o,r){const i=this.handlers.get(e);if(i){if(i.find(s=>s.handler===o&&s.name===t)){hk.warn(`event has already registered: ${t}`);return}i.push(new I2(this.editor,e,t,o,r))}else{const s=new I2(this.editor,e,t,o,r);this.handlers.set(e,[s])}}removeEventListener(e,t,o){if(!e){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(t)t===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(e);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===t);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(e)}}}removeAllListeners(e,t){const o=this.handlers.get(e);if(o)if(t)for(let r=0;r<o.length;r++){const i=o[r];i.name===t&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(e)}}const x2=w("update-block-text");function mk(n,e){const t=n.getBoxById(e.id),o=j(t);d(x2,o,"no parent block"),d(x2,$(n,o),"not a text block");const r=n.getBlockText(o),i=kp(r,"id",e.id,e);i0(n,o,i)}function gk(n,e){for(const t of n.blockHooks)if(t.writable){const o=t.writable(n,e);if(typeof o=="boolean")return o}return!0}function pk(n){return n.readonly?!1:!tn(n).find(o=>!n.isBlockWritable(o.block))}class Ck{constructor(e){this.editor=e}getKey(e){return`${this.editor.id}-${e}`}getItem(e){return window.localStorage.getItem(this.getKey(e))}setItem(e,t){if(!t){this.removeItem(e);return}window.localStorage.setItem(this.getKey(e),t)}removeItem(e){window.localStorage.removeItem(this.getKey(e))}}class Ak{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(e,t){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(zn(t,s)){const c=l(e,t);if(c!==void 0)return c}}}}const Yn=w("editor");class bk extends Ve.TypedEmitter{constructor(t,o,r){var i,s,l,c,a,u,f;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Ak);h(this,"dataConverter",new ik);h(this,"editorBlocks",new $g(this));h(this,"editorBoxes",new Op(this));h(this,"editorInsertions",new $p(this));h(this,"editorEmbeds",new Hg(this));h(this,"editorDecorators",new _p(this));h(this,"editorCommandProviders",new E2(this));h(this,"editorBlockRenders",new sk(this));h(this,"blockHooks",[]);h(this,"domEvents",new fk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new zy(this));h(this,"settingsProvider");h(this,"_readonly",!1);Yn.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(c=r==null?void 0:r.settingsProvider)!=null?c:new Ck(this),ak(this,r==null?void 0:r.components),this.blockHooks.push(...(u=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?u:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new ok(this),this.doc=new Yy(this,o,this.undoManager),this.parent=t,this.rootElement=A("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=A("div",["editor-content"],this.rootElement),this.rootContainerObject=Fg(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new Sv(this,this.inputHandlers),this.selection=new py(this),this.selectionHandler=new by(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),ot.isMobile&&M(this.rootElement,"mobile"),ot.isSafari&&M(this.rootElement,"safari"),this._readonly&&M(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?M(this.rootElement,"readonly"):H(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:vn(this.rootContainer)}addCustom(t,o){const r=this.customs.get(t);if(r)return r;const i=o(this);return this.customs.set(t,i),i}getCustom(t){const o=this.customs.get(t);return d(Yn,o,`${t} does not exists`),o}replaceCustom(t,o){const r=this.customs.get(t);return r&&r.destroy(),this.customs.set(t,o),o}findCustom(t){return this.customs.get(t)}findCustomByType(t){const o=this.customs.values();for(const r of o)if(r instanceof t)return r;return null}destroyCustom(t){const o=this.customs.get(t);o&&(this.customs.delete(t),o.destroy())}getComponentOptions(t){return this.options.componentsOptions[t]}registerLocalEvents(t){this.doc.registerLocalEvents(t)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(t,o,r){return this.editorBlocks.createBlock(t,o,r)}createBox(t,o){return this.editorBoxes.createBox(t,o)}createInsertion(t,o){return this.editorInsertions.createInsertion(t,o)}destroy(){Yn.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(t=>t.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(t,o){Fd(this,t,o)}isWritable(){return pk(this)}isBlockWritable(t){return gk(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return d(Yn,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),d(Yn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(t,o,r){return Pg(this,t,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const t=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return t[t.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&d(Yn,er(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&d(Yn,Fu(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return d(Yn,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return d(Yn,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Pr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return K(o)}return K(t)}getContainerById(t){return _r(this,t)}getParentContainer(t){return _(t)}reloadBlock(t){dk(this,t)}contains(t){const o=t instanceof Element?t:t.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(t,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Vr(this,t,o,r,i!=null?i:c,s)}insertEmbed(t,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Md(this,t,o)}mergeTextBlock(t,o){return n0(this,t,o)}breakTextBlock(t,o,r){return qr(this,t,o,r).newBlock}getTextPosition(){return Ur(this)}getBlockString(t,o){const r=this.getBlockText(t);return ve(r,o)}getBlockData(t){return yo(this,t)}getBoxData(t){return Dp(this,t)}getBlockText(t){return pt(this,t)}setBlockText(t,o){i0(this,t,o)}deleteTextFromBlock(t,o,r,i){return Dd(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return Qp(this,t,o,r,i)}insertBoxToBlock(t,o,r){return Yp(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){c0(this,t,o,r,i)}insertDocAt(t,o,r,i){return $d(this,t,o,r,i)}deleteChildContainers(t){t0(this,t)}replaceBlockText(t,o){return cc(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...c}=i;return ac(this,t,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return s0(this,t,o,r)}updateBoxData(t){mk(this,t)}getSelectedText(){const t=hc(this);return is(this,t)}clearSelectedContents(){Od(this)}insertTextBlock(t,o,r,i){const s=Zn(t!=null?t:"");return e0(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(t,o){if(t&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!t&&!o){Kp(this);return}o?(this.compositingText="",ku()||Td(this,t)):(this.compositingText=t,Jp(this))}getColor(t){const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]}}function gs(n,e,t){return new bk(n,e,t)}function vk(n){const e=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=du.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const yk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class bc extends Ve.TypedEmitter{constructor(t){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=t&&t.length>0?t:yk}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&_i.default(o,t))return;this.cursors.set(t.user.userId,t);const r=new Set([t.range.anchor.blockId,t.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(t){this.addingUser=!0,t.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(t){this.users.set(t.userId,t),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(t){var o;return(o=this.users.get(t))!=null?o:null}removeUser(t){this.users.delete(t),this.cursors.delete(t),this.emit("change",Array.from(this.users.values()))}updateUsers(t){this.users.clear(),this.addingUser=!0;try{t.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(t){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===t&&Kl(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(t){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===t||o.range.focus.blockId===t)}onUpdateBlockText(t,o,r){if(!t.text)return;this.getCursors(t.id).forEach(l=>{if(Kl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===t.id&&(c.offset=dt.transformCursor(c.offset,o,r)),a.blockId===t.id&&(a.offset=dt.transformCursor(a.offset,o,r))}})}getFixedUserColor(t,o){let r=0;Array.from(t).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const rt=w("local-doc");class eh extends zi{constructor(t,o){super();h(this,"doc");h(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[Zn("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Q.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);d(rt,r,`no container data: ${t}`);const i=r[o];return d(rt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);d(rt,i.text,"no text for data");const s=dt.apply(i.text,r);return i.text=s,d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,t,o,r,!0)}),s}localUpdateBlockData(t,o,r){const i=this.getBlockData(t,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,!0)}),i}localInsertBlock(t,o,r){const i=this.getContainerBlocks(t);return d(rt,i,`no container data: ${t}`),d(rt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,t,o,r,!0)}),r}localDeleteBlock(t,o){const r=this.getContainerBlocks(t);d(rt,r,`no container data: ${t}`),d(rt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,!0)}),i}localInsertChildContainer(t,o){this.doc.blocks[t]=o,d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,o,!0)})}localDeleteChildContainers(t){rt.debug(`delete child containers: ${t}`),t.forEach(o=>{d(rt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(t,o){d(rt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){d(rt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new bc}setDoc(t){this.doc=Q.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class kk{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function th(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new kk(o)})}const T2=w("find-block");function D2(n,e){const t=or(e);if(!t){if(Ft(e))return null;const o=tr(e);return d(T2,o,"no parent block"),D2(n,o)}return ce(n,t)?Hr(n,t,{visibleOnly:!0}):t}function S2(n,e){const t=rr(e);if(!t){if(Ft(e))return null;const o=tr(e);return d(T2,o,"no parent block"),S2(n,o)}return ce(n,t)?Ku(n,t,{visibleOnly:!0}):t}const wk=w("remote-cursor");class Bk{constructor(){h(this,"remoteUsers",new bc)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):wk.debug(`unknown remote message received: ${e}`)}handleUpdateUsers(e){this.remoteUsers.updateUsers(e)}handleUpdateCaret(e){const t=this.remoteUsers.findUser(e.userId);!t||this.remoteUsers.setCursor({oneseditor:"cursor",user:t,range:e.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function Ek(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function Ik(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function ps(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=Ek(Q.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function Bo(n){return n==="root"?"blocks":n}function Zr(n){return n==="blocks"?"root":n}const xk={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ct.default(n)},apply(n,e){const t=new ct.default(n),o=new ct.default(e);return t.compose(o).ops},compose(n,e){const t=new ct.default(n),o=new ct.default(e);return t.compose(o).ops},diff(n,e){const t=new ct.default(n),o=new ct.default(e);return t.diff(o).ops},transform(n,e,t){const o=new ct.default(n);return new ct.default(e).transform(o,t==="left").ops},transformCursor(n,e,t){return e.transformPosition(n,!t)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,e,t){if(!n)return null;const o=new ct.default(e),r=this.transformCursor(n.index,o,t),i=this.transformCursor(n.index+n.length,o,t);return{...n,index:r,length:i-r}}}};var Cs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Eo={},nh=mm.default.EventEmitter;Eo.EventEmitter=nh,Eo.mixin=Tk;function Tk(n){for(var e in nh.prototype)n.prototype[e]=nh.prototype[e]}var L2=["info","warn","error"];function M2(){var n={};L2.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var Dk=M2;M2.prototype.setMethods=function(n){n=n||{};var e=this;L2.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var Sk=Dk,Lk=new Sk,R2=Lk;function fr(n,e){this.code=n,this.message=e||"",Error.captureStackTrace?Error.captureStackTrace(this,fr):this.stack=new Error().stack}fr.prototype=Object.create(Error.prototype),fr.prototype.constructor=fr,fr.prototype.name="ShareDBError",fr.CODES={ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT:"ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT",ERR_APPLY_SNAPSHOT_NOT_PROVIDED:"ERR_APPLY_SNAPSHOT_NOT_PROVIDED",ERR_CLIENT_ID_BADLY_FORMED:"ERR_CLIENT_ID_BADLY_FORMED",ERR_CANNOT_PING_OFFLINE:"ERR_CANNOT_PING_OFFLINE",ERR_CONNECTION_SEQ_INTEGER_OVERFLOW:"ERR_CONNECTION_SEQ_INTEGER_OVERFLOW",ERR_CONNECTION_STATE_TRANSITION_INVALID:"ERR_CONNECTION_STATE_TRANSITION_INVALID",ERR_DATABASE_ADAPTER_NOT_FOUND:"ERR_DATABASE_ADAPTER_NOT_FOUND",ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE:"ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE",ERR_DATABASE_METHOD_NOT_IMPLEMENTED:"ERR_DATABASE_METHOD_NOT_IMPLEMENTED",ERR_DEFAULT_TYPE_MISMATCH:"ERR_DEFAULT_TYPE_MISMATCH",ERR_DOC_MISSING_VERSION:"ERR_DOC_MISSING_VERSION",ERR_DOC_ALREADY_CREATED:"ERR_DOC_ALREADY_CREATED",ERR_DOC_DOES_NOT_EXIST:"ERR_DOC_DOES_NOT_EXIST",ERR_DOC_TYPE_NOT_RECOGNIZED:"ERR_DOC_TYPE_NOT_RECOGNIZED",ERR_DOC_WAS_DELETED:"ERR_DOC_WAS_DELETED",ERR_INFLIGHT_OP_MISSING:"ERR_INFLIGHT_OP_MISSING",ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION:"ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION",ERR_MAX_SUBMIT_RETRIES_EXCEEDED:"ERR_MAX_SUBMIT_RETRIES_EXCEEDED",ERR_MESSAGE_BADLY_FORMED:"ERR_MESSAGE_BADLY_FORMED",ERR_MILESTONE_ARGUMENT_INVALID:"ERR_MILESTONE_ARGUMENT_INVALID",ERR_OP_ALREADY_SUBMITTED:"ERR_OP_ALREADY_SUBMITTED",ERR_OP_NOT_ALLOWED_IN_PROJECTION:"ERR_OP_NOT_ALLOWED_IN_PROJECTION",ERR_OP_SUBMIT_REJECTED:"ERR_OP_SUBMIT_REJECTED",ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM:"ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM",ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM:"ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM",ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT:"ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT",ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED:"ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED",ERR_OT_OP_BADLY_FORMED:"ERR_OT_OP_BADLY_FORMED",ERR_OT_OP_NOT_APPLIED:"ERR_OT_OP_NOT_APPLIED",ERR_OT_OP_NOT_PROVIDED:"ERR_OT_OP_NOT_PROVIDED",ERR_PRESENCE_TRANSFORM_FAILED:"ERR_PRESENCE_TRANSFORM_FAILED",ERR_PROTOCOL_VERSION_NOT_SUPPORTED:"ERR_PROTOCOL_VERSION_NOT_SUPPORTED",ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED:"ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED",ERR_SNAPSHOT_READ_SILENT_REJECTION:"ERR_SNAPSHOT_READ_SILENT_REJECTION",ERR_SNAPSHOT_READS_REJECTED:"ERR_SNAPSHOT_READS_REJECTED",ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND:"ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND",ERR_TYPE_CANNOT_BE_PROJECTED:"ERR_TYPE_CANNOT_BE_PROJECTED",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var vc=fr,As={},O2=Mk;function Mk(n,e,t,o){var r=function(s,l,c,a){e(c,s,l,"left"),e(a,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var p=[];if(r(s[m],u,f,p),m++,p.length===1)u=p[0];else if(p.length===0){for(var b=m;b<s.length;b++)o(f,s[b]);u=null;break}else{for(var k=i(s.slice(m),p),v=0;v<k[0].length;v++)o(f,k[0][v]);for(var T=0;T<k[1].length;T++)o(c,k[1][T]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?e([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var F2={exports:{}},Io=F2.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},oh=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},rh=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},yc=function(n){for(var e=0;e<n.length;e++)rh(n[e])};Io.apply=function(n,e){var t;yc(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=oh(n,r.p,r.i);else{if(t=n.slice(r.p,r.p+r.d.length),r.d!==t)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+t+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Jn=Io._append=function(n,e){if(!(e.i===""||e.d===""))if(n.length===0)n.push(e);else{var t=n[n.length-1];t.i!=null&&e.i!=null&&t.p<=e.p&&e.p<=t.p+t.i.length?n[n.length-1]={i:oh(t.i,e.p-t.p,e.i),p:t.p}:t.d!=null&&e.d!=null&&e.p<=t.p&&t.p<=e.p+e.d.length?n[n.length-1]={d:oh(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};Io.compose=function(n,e){yc(n),yc(e);for(var t=n.slice(),o=0;o<e.length;o++)Jn(t,e[o]);return t},Io.normalize=function(n){var e=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=0),Jn(e,o)}return e};var ih=function(n,e,t){return e.i!=null?e.p<n||e.p===n&&t?n+e.i.length:n:n<=e.p?n:n<=e.p+e.d.length?e.p:n-e.d.length};Io.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=ih(n,e[r],o);return n};var Rk=Io._tc=function(n,e,t,o){if(rh(e),rh(t),e.i!=null)Jn(n,{i:e.i,p:ih(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(Jn(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&Jn(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)Jn(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)Jn(n,e);else{var i={d:"",p:e.p};e.p<t.p&&(i.d=e.d.slice(0,t.p-e.p)),e.p+e.d.length>t.p+t.d.length&&(i.d+=e.d.slice(t.p+t.d.length-e.p));var s=Math.max(e.p,t.p),l=Math.min(e.p+e.d.length,t.p+t.d.length),c=e.d.slice(s-e.p,l-e.p),a=t.d.slice(s-t.p,l-t.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=ih(i.p,t),Jn(n,i))}return n},Ok=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Io.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=Ok(n[e]);return n},O2(Io,Rk,yc,Jn);var kc=function(n){return Object.prototype.toString.call(n)=="[object Array]"},Fk=function(n){return!!n&&n.constructor===Object},sn=function(n){return JSON.parse(JSON.stringify(n))},oe={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Kn={};oe.registerSubtype=function(n){Kn[n.name]=n},oe.create=function(n){return n===void 0?null:sn(n)},oe.invertComponent=function(n){var e={p:n.p};return n.t&&Kn[n.t]&&(e.t=n.t,e.o=Kn[n.t].invert(n.o)),n.si!==void 0&&(e.sd=n.si),n.sd!==void 0&&(e.si=n.sd),n.oi!==void 0&&(e.od=n.oi),n.od!==void 0&&(e.oi=n.od),n.li!==void 0&&(e.ld=n.li),n.ld!==void 0&&(e.li=n.ld),n.na!==void 0&&(e.na=-n.na),n.lm!==void 0&&(e.lm=n.p[n.p.length-1],e.p=n.p.slice(0,n.p.length-1).concat([n.lm])),e},oe.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(oe.invertComponent(e[o]));return t},oe.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!kc(n[e].p))throw new Error("Missing path")},oe.checkList=function(n){if(!kc(n))throw new Error("Referenced element not a list")},oe.checkObj=function(n){if(!Fk(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function bs(n){n.t="text0";var e={p:n.p.pop()};n.si!=null&&(e.i=n.si),n.sd!=null&&(e.d=n.sd),n.o=[e]}function vs(n){n.p.push(n.o[0].p),n.o[0].i!=null&&(n.si=n.o[0].i),n.o[0].d!=null&&(n.sd=n.o[0].d),delete n.t,delete n.o}oe.apply=function(n,e){oe.checkValidOp(e),e=sn(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&bs(r);for(var i=null,s=t,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Kn[r.t])s[l]=Kn[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)oe.checkList(s),s[l]=r.li;else if(r.li!==void 0)oe.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)oe.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(oe.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)oe.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)oe.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},oe.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},oe.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=oe.apply(n,r),t(r,n)}return n};var Pk=oe.pathMatches=function(n,e,t){if(n.length!=e.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e[o]&&(!t||o!==n.length-1))return!1;return!0};oe.append=function(n,e){if(e=sn(e),n.length===0){n.push(e);return}var t=n[n.length-1];if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(bs(e),bs(t)),Pk(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Kn[e.t]){if(t.o=Kn[e.t].compose(t.o,e.o),e.si!=null||e.sd!=null){for(var o=e.p,r=0;r<t.o.length-1;r++)e.o=[t.o.pop()],e.p=o.slice(),vs(e),n.push(e);vs(t)}}else t.na!=null&&e.na!=null?n[n.length-1]={p:t.p,na:t.na+e.na}:t.li!==void 0&&e.li===void 0&&e.ld===t.li?t.ld!==void 0?delete t.li:n.pop():t.od!==void 0&&t.oi===void 0&&e.oi!==void 0&&e.od===void 0?t.oi=e.oi:t.oi!==void 0&&e.od!==void 0?e.oi!==void 0?t.oi=e.oi:t.od!==void 0?delete t.oi:n.pop():e.lm!==void 0&&e.p[e.p.length-1]===e.lm||n.push(e);else(e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(vs(e),vs(t)),n.push(e)},oe.compose=function(n,e){oe.checkValidOp(n),oe.checkValidOp(e);for(var t=sn(n),o=0;o<e.length;o++)oe.append(t,e[o]);return t},oe.normalize=function(n){var e=[];n=kc(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),oe.append(e,o)}return e},oe.commonLengthForOps=function(n,e){var t=n.p.length,o=e.p.length;if((n.na!=null||n.t)&&t++,(e.na!=null||e.t)&&o++,t===0)return-1;if(o===0)return null;t--,o--;for(var r=0;r<t;r++){var i=n.p[r];if(r>=o||i!==e.p[r])return null}return t},oe.canOpAffectPath=function(n,e){return oe.commonLengthForOps({p:e},n)!=null},oe.transformComponent=function(n,e,t,o){e=sn(e);var r=oe.commonLengthForOps(t,e),i=oe.commonLengthForOps(e,t),s=e.p.length,l=t.p.length;if((e.na!=null||e.t)&&s++,(t.na!=null||t.t)&&l++,i!=null&&l>s&&e.p[i]==t.p[i]){if(e.ld!==void 0){var c=sn(t);c.p=c.p.slice(s),e.ld=oe.apply(sn(e.ld),[c])}else if(e.od!==void 0){var c=sn(t);c.p=c.p.slice(s),e.od=oe.apply(sn(e.od),[c])}}if(r!=null){var a=s==l,c=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(bs(e),c=sn(t),bs(c)),c.t&&Kn[c.t]){if(e.t&&e.t===c.t){var u=Kn[e.t].transform(e.o,c.o,o);if(e.si!=null||e.sd!=null)for(var f=e.p,m=0;m<u.length;m++)e.o=[u[m]],e.p=f.slice(),vs(e),oe.append(n,e);else(!kc(u)||u.length>0)&&(e.o=u,oe.append(n,e));return n}}else if(t.na===void 0){if(t.li!==void 0&&t.ld!==void 0){if(t.p[r]===e.p[r])if(a){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=sn(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&a&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&a&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&a){if(t.p[r]===e.p[r])return n;var f=t.p[r],p=e.p[r],b=e.lm;(f<b||f===b&&p<b)&&e.lm--}if(t.p[r]<e.p[r])e.p[r]--;else if(t.p[r]===e.p[r]){if(l<s)return n;if(e.ld!==void 0)if(e.li!==void 0)delete e.ld;else return n}}else if(t.lm!==void 0)if(e.lm!==void 0&&s===l){var p=e.p[r],b=e.lm,k=t.p[r],v=t.lm;if(k!==v)if(p===k)if(o==="left")e.p[r]=v,p===b&&(e.lm=v);else return n;else p>k&&e.p[r]--,p>v?e.p[r]++:p===v&&k>v&&(e.p[r]++,p===b&&e.lm++),(b>k||b===k&&b>p)&&e.lm--,b>v?e.lm++:b===v&&(v>k&&b>p||v<k&&b<p?o==="right"&&e.lm++:b>p?e.lm++:b===k&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&a){var p=t.p[r],b=t.lm;f=e.p[r],f>p&&e.p[r]--,f>b&&e.p[r]++}else{var p=t.p[r],b=t.lm;f=e.p[r],f===p?e.p[r]=b:(f>p&&e.p[r]--,(f>b||f===b&&p>b)&&e.p[r]++)}else if(t.oi!==void 0&&t.od!==void 0){if(e.p[r]===t.p[r])if(e.oi!==void 0&&a){if(o==="right")return n;e.od=t.oi}else return n}else if(t.oi!==void 0){if(e.oi!==void 0&&e.p[r]===t.p[r])if(o==="left")oe.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!a)return n;if(e.oi!==void 0)delete e.od;else return n}}}return oe.append(n,e),n},O2(oe,oe.transformComponent,oe.checkValidOp,oe.append);var Nk=F2.exports;oe.registerSubtype(Nk);var $k=oe,_k={type:$k};(function(n){n.defaultType=_k.type,n.map={},n.register=function(e){e.name&&(n.map[e.name]=e),e.uri&&(n.map[e.uri]=e)},n.register(n.defaultType)})(As);var ln={};(function(n){n.doNothing=e;function e(){}n.hasKeys=function(t){for(var o in t)return!0;return!1},n.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t},n.isValidVersion=function(t){return t===null?!0:n.isInteger(t)&&t>=0},n.isValidTimestamp=function(t){return n.isValidVersion(t)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var t=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];t=t[r]||(o===arguments.length-1?void 0:{})}return t},n.digOrCreate=function(){for(var t=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];t=t[i]||(t[i]=r===arguments.length-2?o():{})}return t},n.digAndRemove=function(){for(var t=arguments[0],o=[t],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!t.hasOwnProperty(i))break;t=t[i],o.push(t)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(t){return t&&typeof t.transformPresence=="function"},n.callEach=function(t,o){var r=!1;return t.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(t){return!!t},n.nextTick=function(t){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){t.apply(null,o)})},n.clone=function(t){return t===void 0?void 0:JSON.parse(JSON.stringify(t))}})(ln);var P2=Array.isArray,N2=Object.keys,Hk=Object.prototype.hasOwnProperty,jk=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=P2(e),r=P2(t),i,s,l;if(o&&r){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!n(e[i],t[i]))return!1;return!0}if(o!=r)return!1;var c=e instanceof Date,a=t instanceof Date;if(c!=a)return!1;if(c&&a)return e.getTime()==t.getTime();var u=e instanceof RegExp,f=t instanceof RegExp;if(u!=f)return!1;if(u&&f)return e.toString()==t.toString();var m=N2(e);if(s=m.length,s!==N2(t).length)return!1;for(i=s;i--!==0;)if(!Hk.call(t,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},$2=Eo,zk=R2,Lt=vc,wc=As,cn=ln,Uk=cn.clone,Vk=jk,Bt=Lt.CODES,qk=ae;function ae(n,e,t){$2.EventEmitter.call(this),this.connection=n,this.collection=e,this.id=t,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}$2.mixin(ae),ae.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this;e.whenNothingPending(function(){e.wantSubscribe?e.unsubscribe(function(t){if(t)return n?n(t):e.emit("error",t);e.connection._destroyDoc(e),n&&n()}):(e.connection._destroyDoc(e),n&&n())})},ae.prototype._setType=function(n){if(typeof n=="string"&&(n=wc.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new Lt(Bt.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},ae.prototype._setData=function(n){this.data=n,this._dataStateVersion++},ae.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new Lt(Bt.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return e&&this.once("no write pending",e);var t=new Lt(Bt.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}return n.v>this.version?this.fetch(e):e&&e()}if(this.version>n.v)return e&&e();this.version=n.v;var o=n.type===void 0?wc.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),e&&e()},ae.prototype.whenNothingPending=function(n){var e=this;cn.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},ae.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},ae.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},ae.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},ae.prototype._emitResponseError=function(n,e){if(n&&n.code===Bt.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,e&&e(),this._emitNothingPending();return}if(e){e(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},ae.prototype._handleFetch=function(n,e){var t=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&t.push(o),t.length&&(o=function(r){cn.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},ae.prototype._handleSubscribe=function(n,e){var t=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],t.callback&&o.push(t.callback);var r;if(o.length&&(r=function(i){cn.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=t.wantSubscribe,this.subscribed?this.ingestSnapshot(e,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},ae.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Bt.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq){this._opAcknowledged(e);return}if(this.version==null||e.v>this.version){this.fetch();return}if(!(e.v<this.version)){if(this.inflightOp){var t=Bc(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=Bc(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},ae.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},ae.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(e){return e.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},ae.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);Wk(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},ae.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},ae.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},ae.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=Gk([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},ae.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;cn.nextTick(function(){n._handleSubscribe()})}}};function Wk(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function Gk(n){return n=n.filter(cn.truthy),n.length?function(e){cn.callEach(n,e)}:null}ae.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Zk(n){delete n.op,delete n.create,delete n.del}function Bc(n,e){if(n.del)return Zk(e);if(e.del)return new Lt(Bt.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new Lt(Bt.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new Lt(Bt.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var t=n.type.transformX(n.op,e.op);n.op=t[0],e.op=t[1]}else{var o=n.type.transform(n.op,e.op,"left"),r=n.type.transform(e.op,n.op,"right");n.op=o,e.op=r}}}ae.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new Lt(Bt.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,e),!e&&this.type===wc.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var t=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,e,n.src);for(var s=t;s<this.applyStack.length;s++){var l=Bc(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,e,n.src)}this.emit("op batch",n.op,e),this._popApplyStack(t);return}this.emit("before op",n.op,e,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,e,n.src),this.emit("op batch",n.op,e);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",e);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,e);return}},ae.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var e=this.inflightOp;if(!e){var t=new Lt(Bt.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",t)}if(e.sentAt=Date.now(),e.retries=e.retries==null?0:e.retries+1,e.seq==null){if(this.connection.seq>=cn.MAX_SAFE_INTEGER)return this.emit("error",new Lt(Bt.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));e.seq=this.connection.seq++}this.connection.sendOp(this,e),e.src==null&&(e.src=n)}},ae.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new Lt(Bt.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return t?t(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,e,t),this._otApply(n,e)}catch(i){return this._hardRollback(i)}var r=this;cn.nextTick(function(){r.flush()})},ae.prototype._pushOp=function(n,e,t){if(n.source=e,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(t);return}}n.type=this.type,n.callbacks=[t],this.pendingOps.push(n)},ae.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var e=this.applyStack[0];if(this.applyStack=null,!!e){var t=this.pendingOps.indexOf(e);if(t!==-1)for(var o=this.pendingOps.splice(t),t=0;t<o.length;t++){var e=o[t],r=this._tryCompose(e);r?r.callbacks=r.callbacks.concat(e.callbacks):this.pendingOps.push(e)}}},ae.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!Vk(n.source,e.source))){if(e.create&&"op"in n)return e.create.data=this.type.apply(e.create.data,n.op),e;if("op"in e&&"op"in n&&this.type.compose)return e.op=this.type.compose(e.op,n.op),e}}},ae.prototype.submitOp=function(n,e,t){typeof e=="function"&&(t=e,e=null);var o={op:n},r=e&&e.source;this._submit(o,r,t)},ae.prototype.create=function(n,e,t,o){if(typeof e=="function"?(o=e,t=null,e=null):typeof t=="function"&&(o=t,t=null),e||(e=wc.defaultType.uri),this.type){var r=new Lt(Bt.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:e,data:n}},s=t&&t.source;this._submit(i,s,o)},ae.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new Lt(Bt.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return e?e(t):this.emit("error",t)}var o={del:!0},r=n&&n.source;this._submit(o,r,e)},ae.prototype.pause=function(){this.paused=!0},ae.prototype.resume=function(){this.paused=!1,this.flush()},ae.prototype.toSnapshot=function(){return{v:this.version,data:Uk(this.data),type:this.type.uri}},ae.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return zk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},ae.prototype._rollback=function(n){var e=this.inflightOp;if("op"in e&&e.type.invert){try{e.op=e.type.invert(e.op)}catch{return this._hardRollback(n)}for(var t=0;t<this.pendingOps.length;t++){var o=Bc(this.pendingOps[t],e);if(o)return this._hardRollback(o)}try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},ae.prototype._hardRollback=function(n){var e=[];this.inflightOp&&e.push(this.inflightOp),e=e.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var t=this;this.fetch(function(){for(var o=!!e.length,r=0;r<e.length;r++)o=cn.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},ae.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=cn.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)return this.emit("error",n)};var mr={};mr.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var _2=Eo,H2=mr.ACTIONS,Qk=ln,Yk=Et;function Et(n,e,t,o,r,i,s){_2.EventEmitter.call(this),this.action=n,this.connection=e,this.id=t,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}_2.mixin(Et),Et.prototype.hasPending=function(){return!this.ready},Et.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var e=[],t=0;t<this.results.length;t++){var o=this.results[t];e.push([o.id,o.version])}n.r=e}this.connection.send(n),this.sent=!0}},Et.prototype.destroy=function(n){this.connection.canSend&&this.action===H2.querySubscribe&&this.connection.send({a:H2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Qk.nextTick(n)},Et.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Et.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Et.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Et.prototype._handleResponse=function(n,e,t){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!e)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(e))i+=e.length,this.results=this._ingestSnapshots(e,s),this.extra=t;else for(var l in e){i++;var c=e[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},Et.prototype._ingestSnapshots=function(n,e){for(var t=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,e),t.push(i)}return t},Et.prototype._finishResponse=function(n,e){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),e?e(n):this.emit("error",n);e&&e(null,this.results,this.extra)},Et.prototype._handleError=function(n){this.emit("error",n)},Et.prototype._handleDiff=function(n){for(var e=0;e<n.length;e++){var t=n[e];t.type==="insert"&&(t.values=this._ingestSnapshots(t.values))}for(var e=0;e<n.length;e++){var t=n[e];switch(t.type){case"insert":var o=t.values;Array.prototype.splice.apply(this.results,[t.index,0].concat(o)),this.emit("insert",o,t.index);break;case"remove":var i=t.howMany||1,r=this.results.splice(t.index,i);this.emit("remove",r,t.index);break;case"move":var i=t.howMany||1,s=this.results.splice(t.from,i);Array.prototype.splice.apply(this.results,[t.to,0].concat(s)),this.emit("move",s,t.from,t.to);break}}this.emit("changed",this.results)},Et.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var j2=Eo,Jk=mr.ACTIONS,Kk=ln,z2=In;function In(n,e){if(j2.EventEmitter.call(this),!e||typeof e!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=e,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}j2.mixin(In),In.prototype.submit=function(n,e){this.value=n,this.send(e)},In.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},In.prototype.destroy=function(n){var e=this;this.submit(null,function(t){if(t)return e._callbackOrEmit(t,n);delete e.presence.localPresences[e.presenceId],n&&n()})},In.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},In.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},In.prototype._message=function(){return{a:Jk.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},In.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},In.prototype._callbackOrEmit=function(n,e){if(e)return Kk.nextTick(e,n);n&&this.emit("error",n)};var Xk=ln,U2=sh;function sh(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}sh.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},sh.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Xk.nextTick(n)};var lh={exports:{}};(function(n,e){(function(t,o){o(e)})(Cs,function(t){function o(C,y){y=y|0;for(var B=Math.max(C.length-y,0),x=Array(B),S=0;S<B;S++)x[S]=C[y+S];return x}var r=function(C){var y=o(arguments,1);return function(){var B=o(arguments);return C.apply(null,y.concat(B))}},i=function(C){return function(){var y=o(arguments),B=y.pop();C.call(this,y,B)}};function s(C){var y=typeof C;return C!=null&&(y=="object"||y=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(C){setTimeout(C,0)}function u(C){return function(y){var B=o(arguments,1);C(function(){y.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function p(C){return i(function(y,B){var x;try{x=C.apply(this,y)}catch(S){return B(S)}s(x)&&typeof x.then=="function"?x.then(function(S){b(B,null,S)},function(S){b(B,S.message?S:new Error(S))}):B(null,x)})}function b(C,y,B){try{C(y,B)}catch(x){m(k,x)}}function k(C){throw C}var v=typeof Symbol=="function";function T(C){return v&&C[Symbol.toStringTag]==="AsyncFunction"}function E(C){return T(C)?p(C):C}function R(C){return function(y){var B=o(arguments,1),x=i(function(S,D){var O=this;return C(y,function(P,W){E(P).apply(O,S.concat(W))},D)});return B.length?x.apply(this,B):x}}var L=typeof Cs=="object"&&Cs&&Cs.Object===Object&&Cs,F=typeof self=="object"&&self&&self.Object===Object&&self,V=L||F||Function("return this")(),ee=V.Symbol,se=Object.prototype,pe=se.hasOwnProperty,de=se.toString,we=ee?ee.toStringTag:void 0;function ft(C){var y=pe.call(C,we),B=C[we];try{C[we]=void 0;var x=!0}catch{}var S=de.call(C);return x&&(y?C[we]=B:delete C[we]),S}var co=Object.prototype,st=co.toString;function qt(C){return st.call(C)}var Ho="[object Null]",Dr="[object Undefined]",Sr=ee?ee.toStringTag:void 0;function jo(C){return C==null?C===void 0?Dr:Ho:Sr&&Sr in Object(C)?ft(C):qt(C)}var $a="[object AsyncFunction]",gj="[object Function]",pj="[object GeneratorFunction]",Cj="[object Proxy]";function Aj(C){if(!s(C))return!1;var y=jo(C);return y==gj||y==pj||y==$a||y==Cj}var bj=9007199254740991;function Q9(C){return typeof C=="number"&&C>-1&&C%1==0&&C<=bj}function fl(C){return C!=null&&Q9(C.length)&&!Aj(C)}var Gf={};function he(){}function zo(C){return function(){if(C!==null){var y=C;C=null,y.apply(this,arguments)}}}var Zf=typeof Symbol=="function"&&Symbol.iterator,vj=function(C){return Zf&&C[Zf]&&C[Zf]()};function yj(C,y){for(var B=-1,x=Array(C);++B<C;)x[B]=y(B);return x}function _a(C){return C!=null&&typeof C=="object"}var kj="[object Arguments]";function Y9(C){return _a(C)&&jo(C)==kj}var J9=Object.prototype,wj=J9.hasOwnProperty,Bj=J9.propertyIsEnumerable,Ej=Y9(function(){return arguments}())?Y9:function(C){return _a(C)&&wj.call(C,"callee")&&!Bj.call(C,"callee")},Cn=Array.isArray;function Ij(){return!1}var K9=typeof t=="object"&&t&&!t.nodeType&&t,X9=K9&&!0&&n&&!n.nodeType&&n,xj=X9&&X9.exports===K9,e7=xj?V.Buffer:void 0,Tj=e7?e7.isBuffer:void 0,Dj=Tj||Ij,Sj=9007199254740991,Lj=/^(?:0|[1-9]\d*)$/;function Mj(C,y){var B=typeof C;return y=y==null?Sj:y,!!y&&(B=="number"||B!="symbol"&&Lj.test(C))&&C>-1&&C%1==0&&C<y}var Rj="[object Arguments]",Oj="[object Array]",Fj="[object Boolean]",Pj="[object Date]",Nj="[object Error]",$j="[object Function]",_j="[object Map]",Hj="[object Number]",jj="[object Object]",zj="[object RegExp]",Uj="[object Set]",Vj="[object String]",qj="[object WeakMap]",Wj="[object ArrayBuffer]",Gj="[object DataView]",Zj="[object Float32Array]",Qj="[object Float64Array]",Yj="[object Int8Array]",Jj="[object Int16Array]",Kj="[object Int32Array]",Xj="[object Uint8Array]",ez="[object Uint8ClampedArray]",tz="[object Uint16Array]",nz="[object Uint32Array]",Be={};Be[Zj]=Be[Qj]=Be[Yj]=Be[Jj]=Be[Kj]=Be[Xj]=Be[ez]=Be[tz]=Be[nz]=!0,Be[Rj]=Be[Oj]=Be[Wj]=Be[Fj]=Be[Gj]=Be[Pj]=Be[Nj]=Be[$j]=Be[_j]=Be[Hj]=Be[jj]=Be[zj]=Be[Uj]=Be[Vj]=Be[qj]=!1;function oz(C){return _a(C)&&Q9(C.length)&&!!Be[jo(C)]}function rz(C){return function(y){return C(y)}}var t7=typeof t=="object"&&t&&!t.nodeType&&t,ml=t7&&!0&&n&&!n.nodeType&&n,iz=ml&&ml.exports===t7,Qf=iz&&L.process,n7=function(){try{var C=ml&&ml.require&&ml.require("util").types;return C||Qf&&Qf.binding&&Qf.binding("util")}catch{}}(),o7=n7&&n7.isTypedArray,sz=o7?rz(o7):oz,lz=Object.prototype,cz=lz.hasOwnProperty;function az(C,y){var B=Cn(C),x=!B&&Ej(C),S=!B&&!x&&Dj(C),D=!B&&!x&&!S&&sz(C),O=B||x||S||D,P=O?yj(C.length,String):[],W=P.length;for(var J in C)(y||cz.call(C,J))&&!(O&&(J=="length"||S&&(J=="offset"||J=="parent")||D&&(J=="buffer"||J=="byteLength"||J=="byteOffset")||Mj(J,W)))&&P.push(J);return P}var uz=Object.prototype;function dz(C){var y=C&&C.constructor,B=typeof y=="function"&&y.prototype||uz;return C===B}function hz(C,y){return function(B){return C(y(B))}}var fz=hz(Object.keys,Object),mz=Object.prototype,gz=mz.hasOwnProperty;function pz(C){if(!dz(C))return fz(C);var y=[];for(var B in Object(C))gz.call(C,B)&&B!="constructor"&&y.push(B);return y}function Yf(C){return fl(C)?az(C):pz(C)}function Cz(C){var y=-1,B=C.length;return function(){return++y<B?{value:C[y],key:y}:null}}function Az(C){var y=-1;return function(){var x=C.next();return x.done?null:(y++,{value:x.value,key:y})}}function bz(C){var y=Yf(C),B=-1,x=y.length;return function S(){var D=y[++B];return D==="__proto__"?S():B<x?{value:C[D],key:D}:null}}function vz(C){if(fl(C))return Cz(C);var y=vj(C);return y?Az(y):bz(C)}function Nn(C){return function(){if(C===null)throw new Error("Callback was already called.");var y=C;C=null,y.apply(this,arguments)}}function Ha(C){return function(y,B,x){if(x=zo(x||he),C<=0||!y)return x(null);var S=vz(y),D=!1,O=0,P=!1;function W(Z,te){if(O-=1,Z)D=!0,x(Z);else{if(te===Gf||D&&O<=0)return D=!0,x(null);P||J()}}function J(){for(P=!0;O<C&&!D;){var Z=S();if(Z===null){D=!0,O<=0&&x(null);return}O+=1,B(Z.value,Z.key,Nn(W))}P=!1}J()}}function Lr(C,y,B,x){Ha(y)(C,E(B),x)}function lt(C,y){return function(B,x,S){return C(B,y,x,S)}}function yz(C,y,B){B=zo(B||he);var x=0,S=0,D=C.length;D===0&&B(null);function O(P,W){P?B(P):(++S===D||W===Gf)&&B(null)}for(;x<D;x++)y(C[x],x,Nn(O))}var kz=lt(Lr,1/0),Uo=function(C,y,B){var x=fl(C)?yz:kz;x(C,E(y),B)};function Li(C){return function(y,B,x){return C(Uo,y,E(B),x)}}function r7(C,y,B,x){x=x||he,y=y||[];var S=[],D=0,O=E(B);C(y,function(P,W,J){var Z=D++;O(P,function(te,Ee){S[Z]=Ee,J(te)})},function(P){x(P,S)})}var ja=Li(r7),i7=R(ja);function Mi(C){return function(y,B,x,S){return C(Ha(B),y,E(x),S)}}var Ri=Mi(r7),Jf=lt(Ri,1),s7=R(Jf);function za(C,y){for(var B=-1,x=C==null?0:C.length;++B<x&&y(C[B],B,C)!==!1;);return C}function wz(C){return function(y,B,x){for(var S=-1,D=Object(y),O=x(y),P=O.length;P--;){var W=O[C?P:++S];if(B(D[W],W,D)===!1)break}return y}}var Bz=wz();function gl(C,y){return C&&Bz(C,y,Yf)}function Ez(C,y,B,x){for(var S=C.length,D=B+(x?1:-1);x?D--:++D<S;)if(y(C[D],D,C))return D;return-1}function Iz(C){return C!==C}function xz(C,y,B){for(var x=B-1,S=C.length;++x<S;)if(C[x]===y)return x;return-1}function Ua(C,y,B){return y===y?xz(C,y,B):Ez(C,Iz,B)}var Kf=function(C,y,B){typeof y=="function"&&(B=y,y=null),B=zo(B||he);var x=Yf(C),S=x.length;if(!S)return B(null);y||(y=S);var D={},O=0,P=!1,W=Object.create(null),J=[],Z=[],te={};gl(C,function(De,Le){if(!Cn(De)){Ee(Le,[De]),Z.push(Le);return}var tt=De.slice(0,De.length-1),ao=tt.length;if(ao===0){Ee(Le,De),Z.push(Le);return}te[Le]=ao,za(tt,function(Ni){if(!C[Ni])throw new Error("async.auto task `"+Le+"` has a non-existent dependency `"+Ni+"` in "+tt.join(", "));$n(Ni,function(){ao--,ao===0&&Ee(Le,De)})})}),bU(),mt();function Ee(De,Le){J.push(function(){_n(De,Le)})}function mt(){if(J.length===0&&O===0)return B(null,D);for(;J.length&&O<y;){var De=J.shift();De()}}function $n(De,Le){var tt=W[De];tt||(tt=W[De]=[]),tt.push(Le)}function Wt(De){var Le=W[De]||[];za(Le,function(tt){tt()}),mt()}function _n(De,Le){if(!P){var tt=Nn(function(Ni,um){if(O--,arguments.length>2&&(um=o(arguments,1)),Ni){var dm={};gl(D,function(yU,kU){dm[kU]=yU}),dm[De]=um,P=!0,W=Object.create(null),B(Ni,dm)}else D[De]=um,Wt(De)});O++;var ao=E(Le[Le.length-1]);Le.length>1?ao(D,tt):ao(tt)}}function bU(){for(var De,Le=0;Z.length;)De=Z.pop(),Le++,za(vU(De),function(tt){--te[tt]===0&&Z.push(tt)});if(Le!==S)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function vU(De){var Le=[];return gl(C,function(tt,ao){Cn(tt)&&Ua(tt,De,0)>=0&&Le.push(ao)}),Le}};function Oi(C,y){for(var B=-1,x=C==null?0:C.length,S=Array(x);++B<x;)S[B]=y(C[B],B,C);return S}var Tz="[object Symbol]";function Dz(C){return typeof C=="symbol"||_a(C)&&jo(C)==Tz}var Sz=1/0,l7=ee?ee.prototype:void 0,c7=l7?l7.toString:void 0;function Xf(C){if(typeof C=="string")return C;if(Cn(C))return Oi(C,Xf)+"";if(Dz(C))return c7?c7.call(C):"";var y=C+"";return y=="0"&&1/C==-Sz?"-0":y}function Lz(C,y,B){var x=-1,S=C.length;y<0&&(y=-y>S?0:S+y),B=B>S?S:B,B<0&&(B+=S),S=y>B?0:B-y>>>0,y>>>=0;for(var D=Array(S);++x<S;)D[x]=C[x+y];return D}function Mz(C,y,B){var x=C.length;return B=B===void 0?x:B,!y&&B>=x?C:Lz(C,y,B)}function Rz(C,y){for(var B=C.length;B--&&Ua(y,C[B],0)>-1;);return B}function Oz(C,y){for(var B=-1,x=C.length;++B<x&&Ua(y,C[B],0)>-1;);return B}function Fz(C){return C.split("")}var Pz="\\ud800-\\udfff",Nz="\\u0300-\\u036f",$z="\\ufe20-\\ufe2f",_z="\\u20d0-\\u20ff",Hz=Nz+$z+_z,jz="\\ufe0e\\ufe0f",zz="\\u200d",Uz=RegExp("["+zz+Pz+Hz+jz+"]");function Vz(C){return Uz.test(C)}var a7="\\ud800-\\udfff",qz="\\u0300-\\u036f",Wz="\\ufe20-\\ufe2f",Gz="\\u20d0-\\u20ff",Zz=qz+Wz+Gz,Qz="\\ufe0e\\ufe0f",Yz="["+a7+"]",em="["+Zz+"]",tm="\\ud83c[\\udffb-\\udfff]",Jz="(?:"+em+"|"+tm+")",u7="[^"+a7+"]",d7="(?:\\ud83c[\\udde6-\\uddff]){2}",h7="[\\ud800-\\udbff][\\udc00-\\udfff]",Kz="\\u200d",f7=Jz+"?",m7="["+Qz+"]?",Xz="(?:"+Kz+"(?:"+[u7,d7,h7].join("|")+")"+m7+f7+")*",eU=m7+f7+Xz,tU="(?:"+[u7+em+"?",em,d7,h7,Yz].join("|")+")",nU=RegExp(tm+"(?="+tm+")|"+tU+eU,"g");function oU(C){return C.match(nU)||[]}function g7(C){return Vz(C)?oU(C):Fz(C)}function rU(C){return C==null?"":Xf(C)}var iU=/^\s+|\s+$/g;function sU(C,y,B){if(C=rU(C),C&&(B||y===void 0))return C.replace(iU,"");if(!C||!(y=Xf(y)))return C;var x=g7(C),S=g7(y),D=Oz(x,S),O=Rz(x,S)+1;return Mz(x,D,O).join("")}var lU=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,cU=/,/,aU=/(=.+)?(\s*)$/,uU=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function dU(C){return C=C.toString().replace(uU,""),C=C.match(lU)[2].replace(" ",""),C=C?C.split(cU):[],C=C.map(function(y){return sU(y.replace(aU,""))}),C}function p7(C,y){var B={};gl(C,function(x,S){var D,O=T(x),P=!O&&x.length===1||O&&x.length===0;if(Cn(x))D=x.slice(0,-1),x=x[x.length-1],B[S]=D.concat(D.length>0?W:x);else if(P)B[S]=x;else{if(D=dU(x),x.length===0&&!O&&D.length===0)throw new Error("autoInject task functions require explicit parameters.");O||D.pop(),B[S]=D.concat(W)}function W(J,Z){var te=Oi(D,function(Ee){return J[Ee]});te.push(Z),E(x).apply(null,te)}}),Kf(B,y)}function An(){this.head=this.tail=null,this.length=0}function C7(C,y){C.length=1,C.head=C.tail=y}An.prototype.removeLink=function(C){return C.prev?C.prev.next=C.next:this.head=C.next,C.next?C.next.prev=C.prev:this.tail=C.prev,C.prev=C.next=null,this.length-=1,C},An.prototype.empty=function(){for(;this.head;)this.shift();return this},An.prototype.insertAfter=function(C,y){y.prev=C,y.next=C.next,C.next?C.next.prev=y:this.tail=y,C.next=y,this.length+=1},An.prototype.insertBefore=function(C,y){y.prev=C.prev,y.next=C,C.prev?C.prev.next=y:this.head=y,C.prev=y,this.length+=1},An.prototype.unshift=function(C){this.head?this.insertBefore(this.head,C):C7(this,C)},An.prototype.push=function(C){this.tail?this.insertAfter(this.tail,C):C7(this,C)},An.prototype.shift=function(){return this.head&&this.removeLink(this.head)},An.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},An.prototype.toArray=function(){for(var C=Array(this.length),y=this.head,B=0;B<this.length;B++)C[B]=y.data,y=y.next;return C},An.prototype.remove=function(C){for(var y=this.head;y;){var B=y.next;C(y)&&this.removeLink(y),y=B}return this};function A7(C,y,B){if(y==null)y=1;else if(y===0)throw new Error("Concurrency must not be zero");var x=E(C),S=0,D=[],O=!1;function P(te,Ee,mt){if(mt!=null&&typeof mt!="function")throw new Error("task callback must be a function");if(Z.started=!0,Cn(te)||(te=[te]),te.length===0&&Z.idle())return m(function(){Z.drain()});for(var $n=0,Wt=te.length;$n<Wt;$n++){var _n={data:te[$n],callback:mt||he};Ee?Z._tasks.unshift(_n):Z._tasks.push(_n)}O||(O=!0,m(function(){O=!1,Z.process()}))}function W(te){return function(Ee){S-=1;for(var mt=0,$n=te.length;mt<$n;mt++){var Wt=te[mt],_n=Ua(D,Wt,0);_n===0?D.shift():_n>0&&D.splice(_n,1),Wt.callback.apply(Wt,arguments),Ee!=null&&Z.error(Ee,Wt.data)}S<=Z.concurrency-Z.buffer&&Z.unsaturated(),Z.idle()&&Z.drain(),Z.process()}}var J=!1,Z={_tasks:new An,concurrency:y,payload:B,saturated:he,unsaturated:he,buffer:y/4,empty:he,drain:he,error:he,started:!1,paused:!1,push:function(te,Ee){P(te,!1,Ee)},kill:function(){Z.drain=he,Z._tasks.empty()},unshift:function(te,Ee){P(te,!0,Ee)},remove:function(te){Z._tasks.remove(te)},process:function(){if(!J){for(J=!0;!Z.paused&&S<Z.concurrency&&Z._tasks.length;){var te=[],Ee=[],mt=Z._tasks.length;Z.payload&&(mt=Math.min(mt,Z.payload));for(var $n=0;$n<mt;$n++){var Wt=Z._tasks.shift();te.push(Wt),D.push(Wt),Ee.push(Wt.data)}S+=1,Z._tasks.length===0&&Z.empty(),S===Z.concurrency&&Z.saturated();var _n=Nn(W(te));x(Ee,_n)}J=!1}},length:function(){return Z._tasks.length},running:function(){return S},workersList:function(){return D},idle:function(){return Z._tasks.length+S===0},pause:function(){Z.paused=!0},resume:function(){Z.paused!==!1&&(Z.paused=!1,m(Z.process))}};return Z}function b7(C,y){return A7(C,1,y)}var Fi=lt(Lr,1);function Vo(C,y,B,x){x=zo(x||he);var S=E(B);Fi(C,function(D,O,P){S(y,D,function(W,J){y=J,P(W)})},function(D){x(D,y)})}function nm(){var C=Oi(arguments,E);return function(){var y=o(arguments),B=this,x=y[y.length-1];typeof x=="function"?y.pop():x=he,Vo(C,y,function(S,D,O){D.apply(B,S.concat(function(P){var W=o(arguments,1);O(P,W)}))},function(S,D){x.apply(B,[S].concat(D))})}}var v7=function(){return nm.apply(null,o(arguments).reverse())},hU=Array.prototype.concat,Va=function(C,y,B,x){x=x||he;var S=E(B);Ri(C,y,function(D,O){S(D,function(P){return P?O(P):O(null,o(arguments,1))})},function(D,O){for(var P=[],W=0;W<O.length;W++)O[W]&&(P=hU.apply(P,O[W]));return x(D,P)})},y7=lt(Va,1/0),k7=lt(Va,1),w7=function(){var C=o(arguments),y=[null].concat(C);return function(){var B=arguments[arguments.length-1];return B.apply(this,y)}};function pl(C){return C}function Pi(C,y){return function(B,x,S,D){D=D||he;var O=!1,P;B(x,function(W,J,Z){S(W,function(te,Ee){te?Z(te):C(Ee)&&!P?(O=!0,P=y(!0,W),Z(null,Gf)):Z()})},function(W){W?D(W):D(null,O?P:y(!1))})}}function B7(C,y){return y}var qa=Li(Pi(pl,B7)),Cl=Mi(Pi(pl,B7)),Wa=lt(Cl,1);function E7(C){return function(y){var B=o(arguments,1);B.push(function(x){var S=o(arguments,1);typeof console=="object"&&(x?console.error&&console.error(x):console[C]&&za(S,function(D){console[C](D)}))}),E(y).apply(null,B)}}var I7=E7("dir");function x7(C,y,B){B=Nn(B||he);var x=E(C),S=E(y);function D(P){if(P)return B(P);var W=o(arguments,1);W.push(O),S.apply(this,W)}function O(P,W){if(P)return B(P);if(!W)return B(null);x(D)}O(null,!0)}function om(C,y,B){B=Nn(B||he);var x=E(C),S=function(D){if(D)return B(D);var O=o(arguments,1);if(y.apply(this,O))return x(S);B.apply(null,[null].concat(O))};x(S)}function T7(C,y,B){om(C,function(){return!y.apply(this,arguments)},B)}function D7(C,y,B){B=Nn(B||he);var x=E(y),S=E(C);function D(P){if(P)return B(P);S(O)}function O(P,W){if(P)return B(P);if(!W)return B(null);x(D)}S(O)}function S7(C){return function(y,B,x){return C(y,x)}}function Ga(C,y,B){Uo(C,S7(E(y)),B)}function Al(C,y,B,x){Ha(y)(C,S7(E(B)),x)}var bl=lt(Al,1);function rm(C){return T(C)?C:i(function(y,B){var x=!0;y.push(function(){var S=arguments;x?m(function(){B.apply(null,S)}):B.apply(null,S)}),C.apply(this,y),x=!1})}function Za(C){return!C}var Qa=Li(Pi(Za,Za)),vl=Mi(Pi(Za,Za)),Ya=lt(vl,1);function L7(C){return function(y){return y==null?void 0:y[C]}}function fU(C,y,B,x){var S=new Array(y.length);C(y,function(D,O,P){B(D,function(W,J){S[O]=!!J,P(W)})},function(D){if(D)return x(D);for(var O=[],P=0;P<y.length;P++)S[P]&&O.push(y[P]);x(null,O)})}function mU(C,y,B,x){var S=[];C(y,function(D,O,P){B(D,function(W,J){W?P(W):(J&&S.push({index:O,value:D}),P())})},function(D){D?x(D):x(null,Oi(S.sort(function(O,P){return O.index-P.index}),L7("value")))})}function im(C,y,B,x){var S=fl(y)?fU:mU;S(C,y,E(B),x||he)}var Ja=Li(im),yl=Mi(im),Ka=lt(yl,1);function M7(C,y){var B=Nn(y||he),x=E(rm(C));function S(D){if(D)return B(D);x(S)}S()}var Xa=function(C,y,B,x){x=x||he;var S=E(B);Ri(C,y,function(D,O){S(D,function(P,W){return P?O(P):O(null,{key:W,val:D})})},function(D,O){for(var P={},W=Object.prototype.hasOwnProperty,J=0;J<O.length;J++)if(O[J]){var Z=O[J].key,te=O[J].val;W.call(P,Z)?P[Z].push(te):P[Z]=[te]}return x(D,P)})},R7=lt(Xa,1/0),O7=lt(Xa,1),F7=E7("log");function eu(C,y,B,x){x=zo(x||he);var S={},D=E(B);Lr(C,y,function(O,P,W){D(O,P,function(J,Z){if(J)return W(J);S[P]=Z,W()})},function(O){x(O,S)})}var P7=lt(eu,1/0),N7=lt(eu,1);function $7(C,y){return y in C}function _7(C,y){var B=Object.create(null),x=Object.create(null);y=y||pl;var S=E(C),D=i(function(P,W){var J=y.apply(null,P);$7(B,J)?m(function(){W.apply(null,B[J])}):$7(x,J)?x[J].push(W):(x[J]=[W],S.apply(null,P.concat(function(){var Z=o(arguments);B[J]=Z;var te=x[J];delete x[J];for(var Ee=0,mt=te.length;Ee<mt;Ee++)te[Ee].apply(null,Z)})))});return D.memo=B,D.unmemoized=C,D}var tu;c?tu=process.nextTick:l?tu=setImmediate:tu=a;var H7=u(tu);function sm(C,y,B){B=B||he;var x=fl(y)?[]:{};C(y,function(S,D,O){E(S)(function(P,W){arguments.length>2&&(W=o(arguments,1)),x[D]=W,O(P)})},function(S){B(S,x)})}function j7(C,y){sm(Uo,C,y)}function z7(C,y,B){sm(Ha(y),C,B)}var lm=function(C,y){var B=E(C);return A7(function(x,S){B(x[0],S)},y,1)},U7=function(C,y){var B=lm(C,y);return B.push=function(x,S,D){if(D==null&&(D=he),typeof D!="function")throw new Error("task callback must be a function");if(B.started=!0,Cn(x)||(x=[x]),x.length===0)return m(function(){B.drain()});S=S||0;for(var O=B._tasks.head;O&&S>=O.priority;)O=O.next;for(var P=0,W=x.length;P<W;P++){var J={data:x[P],priority:S,callback:D};O?B._tasks.insertBefore(O,J):B._tasks.push(J)}m(B.process)},delete B.unshift,B};function V7(C,y){if(y=zo(y||he),!Cn(C))return y(new TypeError("First argument to race must be an array of functions"));if(!C.length)return y();for(var B=0,x=C.length;B<x;B++)E(C[B])(y)}function nu(C,y,B,x){var S=o(C).reverse();Vo(S,y,B,x)}function ou(C){var y=E(C);return i(function(x,S){return x.push(function(O,P){if(O)S(null,{error:O});else{var W;arguments.length<=2?W=P:W=o(arguments,1),S(null,{value:W})}}),y.apply(this,x)})}function q7(C){var y;return Cn(C)?y=Oi(C,ou):(y={},gl(C,function(B,x){y[x]=ou.call(this,B)})),y}function W7(C,y,B,x){im(C,y,function(S,D){B(S,function(O,P){D(O,!P)})},x)}var G7=Li(W7),cm=Mi(W7),Z7=lt(cm,1);function Q7(C){return function(){return C}}function ru(C,y,B){var x=5,S=0,D={times:x,intervalFunc:Q7(S)};function O(Z,te){if(typeof te=="object")Z.times=+te.times||x,Z.intervalFunc=typeof te.interval=="function"?te.interval:Q7(+te.interval||S),Z.errorFilter=te.errorFilter;else if(typeof te=="number"||typeof te=="string")Z.times=+te||x;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof C=="function"?(B=y||he,y=C):(O(D,C),B=B||he),typeof y!="function")throw new Error("Invalid arguments for async.retry");var P=E(y),W=1;function J(){P(function(Z){Z&&W++<D.times&&(typeof D.errorFilter!="function"||D.errorFilter(Z))?setTimeout(J,D.intervalFunc(W)):B.apply(null,arguments)})}J()}var Y7=function(C,y){y||(y=C,C=null);var B=E(y);return i(function(x,S){function D(O){B.apply(null,x.concat(O))}C?ru(C,D,S):ru(D,S)})};function J7(C,y){sm(Fi,C,y)}var iu=Li(Pi(Boolean,pl)),kl=Mi(Pi(Boolean,pl)),su=lt(kl,1);function K7(C,y,B){var x=E(y);ja(C,function(D,O){x(D,function(P,W){if(P)return O(P);O(null,{value:D,criteria:W})})},function(D,O){if(D)return B(D);B(null,Oi(O.sort(S),L7("value")))});function S(D,O){var P=D.criteria,W=O.criteria;return P<W?-1:P>W?1:0}}function X7(C,y,B){var x=E(C);return i(function(S,D){var O=!1,P;function W(){var J=C.name||"anonymous",Z=new Error('Callback function "'+J+'" timed out.');Z.code="ETIMEDOUT",B&&(Z.info=B),O=!0,D(Z)}S.push(function(){O||(D.apply(null,arguments),clearTimeout(P))}),P=setTimeout(W,y),x.apply(null,S)})}var gU=Math.ceil,pU=Math.max;function CU(C,y,B,x){for(var S=-1,D=pU(gU((y-C)/(B||1)),0),O=Array(D);D--;)O[x?D:++S]=C,C+=B;return O}function lu(C,y,B,x){var S=E(B);Ri(CU(0,C,1),y,S,x)}var e8=lt(lu,1/0),t8=lt(lu,1);function n8(C,y,B,x){arguments.length<=3&&(x=B,B=y,y=Cn(C)?[]:{}),x=zo(x||he);var S=E(B);Uo(C,function(D,O,P){S(y,D,O,P)},function(D){x(D,y)})}function o8(C,y){var B=null,x;y=y||he,bl(C,function(S,D){E(S)(function(O,P){arguments.length>2?x=o(arguments,1):x=P,B=O,D(!O)})},function(){y(B,x)})}function r8(C){return function(){return(C.unmemoized||C).apply(null,arguments)}}function am(C,y,B){B=Nn(B||he);var x=E(y);if(!C())return B(null);var S=function(D){if(D)return B(D);if(C())return x(S);var O=o(arguments,1);B.apply(null,[null].concat(O))};x(S)}function i8(C,y,B){am(function(){return!C.apply(this,arguments)},y,B)}var s8=function(C,y){if(y=zo(y||he),!Cn(C))return y(new Error("First argument to waterfall must be an array of functions"));if(!C.length)return y();var B=0;function x(D){var O=E(C[B++]);D.push(Nn(S)),O.apply(null,D)}function S(D){if(D||B===C.length)return y.apply(null,arguments);x(o(arguments,1))}x([])},AU={apply:r,applyEach:i7,applyEachSeries:s7,asyncify:p,auto:Kf,autoInject:p7,cargo:b7,compose:v7,concat:y7,concatLimit:Va,concatSeries:k7,constant:w7,detect:qa,detectLimit:Cl,detectSeries:Wa,dir:I7,doDuring:x7,doUntil:T7,doWhilst:om,during:D7,each:Ga,eachLimit:Al,eachOf:Uo,eachOfLimit:Lr,eachOfSeries:Fi,eachSeries:bl,ensureAsync:rm,every:Qa,everyLimit:vl,everySeries:Ya,filter:Ja,filterLimit:yl,filterSeries:Ka,forever:M7,groupBy:R7,groupByLimit:Xa,groupBySeries:O7,log:F7,map:ja,mapLimit:Ri,mapSeries:Jf,mapValues:P7,mapValuesLimit:eu,mapValuesSeries:N7,memoize:_7,nextTick:H7,parallel:j7,parallelLimit:z7,priorityQueue:U7,queue:lm,race:V7,reduce:Vo,reduceRight:nu,reflect:ou,reflectAll:q7,reject:G7,rejectLimit:cm,rejectSeries:Z7,retry:ru,retryable:Y7,seq:nm,series:J7,setImmediate:m,some:iu,someLimit:kl,someSeries:su,sortBy:K7,timeout:X7,times:e8,timesLimit:lu,timesSeries:t8,transform:n8,tryEach:o8,unmemoize:r8,until:i8,waterfall:s8,whilst:am,all:Qa,allLimit:vl,allSeries:Ya,any:iu,anyLimit:kl,anySeries:su,find:qa,findLimit:Cl,findSeries:Wa,forEach:Ga,forEachSeries:bl,forEachLimit:Al,forEachOf:Uo,forEachOfSeries:Fi,forEachOfLimit:Lr,inject:Vo,foldl:Vo,foldr:nu,select:Ja,selectLimit:yl,selectSeries:Ka,wrapSync:p};t.default=AU,t.apply=r,t.applyEach=i7,t.applyEachSeries=s7,t.asyncify=p,t.auto=Kf,t.autoInject=p7,t.cargo=b7,t.compose=v7,t.concat=y7,t.concatLimit=Va,t.concatSeries=k7,t.constant=w7,t.detect=qa,t.detectLimit=Cl,t.detectSeries=Wa,t.dir=I7,t.doDuring=x7,t.doUntil=T7,t.doWhilst=om,t.during=D7,t.each=Ga,t.eachLimit=Al,t.eachOf=Uo,t.eachOfLimit=Lr,t.eachOfSeries=Fi,t.eachSeries=bl,t.ensureAsync=rm,t.every=Qa,t.everyLimit=vl,t.everySeries=Ya,t.filter=Ja,t.filterLimit=yl,t.filterSeries=Ka,t.forever=M7,t.groupBy=R7,t.groupByLimit=Xa,t.groupBySeries=O7,t.log=F7,t.map=ja,t.mapLimit=Ri,t.mapSeries=Jf,t.mapValues=P7,t.mapValuesLimit=eu,t.mapValuesSeries=N7,t.memoize=_7,t.nextTick=H7,t.parallel=j7,t.parallelLimit=z7,t.priorityQueue=U7,t.queue=lm,t.race=V7,t.reduce=Vo,t.reduceRight=nu,t.reflect=ou,t.reflectAll=q7,t.reject=G7,t.rejectLimit=cm,t.rejectSeries=Z7,t.retry=ru,t.retryable=Y7,t.seq=nm,t.series=J7,t.setImmediate=m,t.some=iu,t.someLimit=kl,t.someSeries=su,t.sortBy=K7,t.timeout=X7,t.times=e8,t.timesLimit=lu,t.timesSeries=t8,t.transform=n8,t.tryEach=o8,t.unmemoize=r8,t.until=i8,t.waterfall=s8,t.whilst=am,t.all=Qa,t.allLimit=vl,t.allSeries=Ya,t.any=iu,t.anyLimit=kl,t.anySeries=su,t.find=qa,t.findLimit=Cl,t.findSeries=Wa,t.forEach=Ga,t.forEachSeries=bl,t.forEachLimit=Al,t.forEachOf=Uo,t.forEachOfSeries=Fi,t.forEachOfLimit=Lr,t.inject=Vo,t.foldl=Vo,t.foldr=nu,t.select=Ja,t.selectLimit=yl,t.selectSeries=Ka,t.wrapSync=p,Object.defineProperty(t,"__esModule",{value:!0})})})(lh,lh.exports);var V2={exports:{}},ch=V2.exports=function(n,e){if(e||(e=16),n===void 0&&(n=128),n<=0)return"0";for(var t=Math.log(Math.pow(2,n))/Math.log(e),o=2;t===1/0;o*=2)t=Math.log(Math.pow(2,n/o))/Math.log(e)*o;for(var r=t-Math.floor(t),i="",o=0;o<Math.floor(t);o++){var s=Math.floor(Math.random()*e).toString(e);i=s+i}if(r){var l=Math.pow(e,r),s=Math.floor(Math.random()*l).toString(e);i=s+i}var c=parseInt(i,e);return c!==1/0&&c>=Math.pow(2,n)?ch(n,e):i};ch.rack=function(n,e,t){var o=function(i){var s=0;do{if(s++>10)if(t)n+=t;else throw new Error("too many ID collisions, use more bits");var l=ch(n,e)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=e||16,o};var q2=Eo,ew=z2,tw=U2,Ec=ln,ah=lh.exports,nw=V2.exports,W2=mr.ACTIONS,G2=_e;function _e(n,e){if(q2.EventEmitter.call(this),!e||typeof e!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=e,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}q2.mixin(_e),_e.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},_e.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},_e.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||nw();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},_e.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this,t=Object.keys(e.localPresences);this.unsubscribe(function(o){if(o)return e._callbackOrEmit(o,n);var r=Object.keys(e._remotePresenceInstances);ah.parallel([function(i){ah.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();ah.each(r,function(s,l){e._remotePresenceInstances[s].destroy(l)},i)}],function(i){e._wantsDestroy&&delete e.connection._presences[e.channel],e._callbackOrEmit(i,n)})})},_e.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?W2.presenceSubscribe:W2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},_e.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},_e.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},_e.prototype._receiveUpdate=function(n,e){var t=Ec.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=Ec.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},_e.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},_e.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var e in this.localPresences){var t=this.localPresences[e];t.value!==null&&t.send()}},_e.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},_e.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},_e.prototype._resubscribe=function(){var n=[];for(var e in this._subscriptionCallbacksBySeq){var t=this._subscriptionCallback(e);n.push(t)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},_e.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},_e.prototype._callbackOrEmit=function(n,e){if(e)return Ec.nextTick(e,n);n&&this.emit("error",n)},_e.prototype._createLocalPresence=function(n){return new ew(this,n)},_e.prototype._createRemotePresence=function(n){return new tw(this,n)},_e.prototype._callEachOrEmit=function(n,e){var t=Ec.callEach(n,e);!t&&e&&this.emit("error",e)};var ys=z2,Z2=vc,ow=ln,Q2=Z2.CODES,rw=an;function an(n,e){ys.call(this,n,e),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}an.prototype=Object.create(ys.prototype),an.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:Q2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(t,e)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,ys.prototype.submit.call(this,n,e)},an.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),ys.prototype.destroy.call(this,n)},an.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(e){e.t=n._doc.type.uri,e.v=n._doc.version,n.connection.send(e)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},an.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},an.prototype._transformAgainstOp=function(n,e){var t=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=t._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=t._transformPresence(r.p,n,e),t._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=t._getCallback(r.pv);t._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,e)}catch(r){this.emit("error",r)}},an.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},an.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},an.prototype._message=function(){var n=ys.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},an.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!ow.supportsPresence(o))throw new Z2(Q2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var Y2={};(function(n){var e=As,t=vc,o=ln,r=t.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=e.map[c];if(a==null||typeof a!="object")return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new t(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new t(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new t(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return e.map[l]&&e.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=e.map[a.type];if(!u)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=e.map[l.type];if(!a)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new t(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new t(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=e.map[l],!l))return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=e.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===e.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var p=m.p,b=u,k=0;k<p.length;k++){var v=p[k];Object.prototype.toString.call(b)=="[object Array]"?p[k]=+v:b.constructor===Object&&(p[k]=v.toString()),b=b[v]}f<a.length-1&&(u=e.defaultType.apply(u,[m]))}}}}})(Y2);var ks=U2,iw=Y2,sw=Ht;function Ht(n,e){ks.call(this,n,e),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}Ht.prototype=Object.create(ks.prototype),Ht.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},Ht.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createDelHandler),this._doc.removeListener("del",this._createDelHandler),this._doc.removeListener("load",this._loadHandler),ks.prototype.destroy.call(this,n)},Ht.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createDelHandler),this._doc.on("del",this._createDelHandler),this._doc.on("load",this._loadHandler)},Ht.prototype._setPendingPresence=function(){if(!this._pendingSetPending){this._pendingSetPending=!0;var n=this;this._doc.whenNothingPending(function(){if(n._pendingSetPending=!1,!!n._pending){if(n._pending.pv<n.presenceVersion)return n._pending=null;if(n._pending.v>n._doc.version)return n._doc.fetch();!n._catchUpStalePresence()||(n.value=n._pending.p,n.presenceVersion=n._pending.pv,n._pending=null,n.presence._updateRemotePresence(n))}})}},Ht.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},ks.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},ks.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},Ht.prototype._transformAgainstOp=function(n,e){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,e)}catch(t){return this.presence.emit("error",t)}this.presence._updateRemotePresence(this)}},Ht.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],e=n.op,t=n.isOwnOp;e===null?(this._pending.p=null,this._pending.v++):iw.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},Ht.prototype._startCachingOps=function(){this._opCache=[]},Ht.prototype._stopCachingOps=function(){this._opCache=null},Ht.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var J2=G2,lw=rw,cw=sw;function Qr(n,e,t){var o=Qr.channel(e,t);J2.call(this,n,o),this.collection=e,this.id=t}var aw=Qr;Qr.prototype=Object.create(J2.prototype),Qr.channel=function(n,e){return n+"."+e},Qr.prototype._createLocalPresence=function(n){return new lw(this,n)},Qr.prototype._createRemotePresence=function(n){return new cw(this,n)};var uw=dw;function dw(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var hw=uw,K2=Eo,X2=ws;function ws(n,e,t,o,r){if(K2.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=e,this.connection=n,this.id=o,this.collection=t,this.callback=r,this.sent=!1}K2.mixin(ws),ws.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},ws.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},ws.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new hw(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var e5=X2,fw=ln,mw=mr.ACTIONS,gw=uh;function uh(n,e,t,o,r,i){if(e5.call(this,n,e,t,o,i),!fw.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}uh.prototype=Object.create(e5.prototype),uh.prototype._message=function(){return{a:mw.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var t5=X2,pw=ln,Cw=mr.ACTIONS,Aw=dh;function dh(n,e,t,o,r,i){if(t5.call(this,n,e,t,o,i),!pw.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}dh.prototype=Object.create(t5.prototype),dh.prototype._message=function(){return{a:Cw.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var bw=qk,vw=Yk,yw=G2,n5=aw,kw=gw,ww=Aw,o5=Eo,Yr=vc,be=mr.ACTIONS,r5=As,un=ln,Bs=R2,Es=Yr.CODES;function i5(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var Bw=X;function X(n){o5.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=i5(n),this.bindToSocket(n)}o5.mixin(X),X.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var e=i5(n);this._setState(e),this.canSend=!1;var t=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Bs.warn("Failed to parse message",o);return}t.debug&&Bs.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){un.nextTick(function(){t.emit("error",s)})}},n.readyState===1&&t._initializeHandshake(),n.onopen=function(){t._setState("connecting"),t._initializeHandshake()},n.onerror=function(o){t.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?t._setState("closed",o):o==="stopped"||o==="Stopped by server"?t._setState("stopped",o):t._setState("disconnected",o)}},X.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=s5(n.error,n),delete n.error),n.a){case be.initLegacy:return this._handleLegacyInit(n);case be.handshake:return this._handleHandshake(e,n);case be.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case be.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case be.queryUnsubscribe:return;case be.queryUpdate:var t=this.queries[n.id];if(!t)return;if(e)return t._handleError(e);n.diff&&t._handleDiff(n.diff),n.hasOwnProperty("extra")&&t._handleExtra(n.extra);return;case be.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case be.bulkSubscribe:case be.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case be.snapshotFetch:case be.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case be.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case be.subscribe:case be.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case be.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case be.presence:return this._handlePresence(e,n);case be.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case be.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case be.presenceRequest:return this._handlePresenceRequest(e,n);case be.pingPong:return this._handlePingPong(e);default:Bs.warn("Ignoring unrecognized message",n)}};function s5(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}X.prototype._handleBulkMessage=function(n,e,t){if(e.data)for(var o in e.data){var r=e.data[o],i=this.getExisting(e.c,o);i&&(n?i[t](n):r.error?i[t](s5(r.error)):i[t](null,r))}else if(Array.isArray(e.b))for(var s=0;s<e.b.length;s++){var o=e.b[s],i=this.getExisting(e.c,o);i&&i[t](n)}else if(e.b)for(var o in e.b){var i=this.getExisting(e.c,o);i&&i[t](n)}else Bs.error("Invalid bulk message",e)},X.prototype._reset=function(){this.agent=null},X.prototype._setState=function(n,e){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var t=new Yr(Es.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",t)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,e),this.emit("state",n,e)}},X.prototype.startBulk=function(){this.bulk||(this.bulk={})},X.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var e=this.bulk[n];this._sendBulk("f",n,e.f),this._sendBulk("s",n,e.s),this._sendBulk("u",n,e.u)}this.bulk=null},X.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var c=t[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:e,d:l})}else o.length&&this.send({a:"b"+n,c:e,b:o});if(i===1){var a=r[s];this.send({a:n,c:e,d:s,v:a})}else i&&this.send({a:"b"+n,c:e,b:r})}},X.prototype._sendActions=function(n,e,t){if(this._addDoc(e),this.bulk){var o=this.bulk[e.collection]||(this.bulk[e.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(e.id);return r[e.id]=t,i}else{var s={a:n,c:e.collection,d:e.id,v:t};this.send(s)}},X.prototype.sendFetch=function(n){return this._sendActions(be.fetch,n,n.version)},X.prototype.sendSubscribe=function(n){return this._sendActions(be.subscribe,n,n.version)},X.prototype.sendUnsubscribe=function(n){return this._sendActions(be.unsubscribe,n)},X.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:be.op,c:n.collection,d:n.id,v:n.version,src:e.src,seq:e.seq,x:{}};"op"in e&&(t.op=e.op),e.create&&(t.create=e.create),e.del&&(t.del=e.del),n.submitSource&&(t.x.source=e.source),this.send(t)},X.prototype.send=function(n){this.debug&&Bs.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},X.prototype.ping=function(){if(!this.canSend)throw new Yr(Es.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:be.pingPong};this.send(n)},X.prototype.close=function(){this.socket.close()},X.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},X.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new bw(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},X.prototype._destroyDoc=function(n){!n._wantsDestroy||(un.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},X.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},X.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new vw(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},X.prototype._destroyQuery=function(n){delete this.queries[n.id]},X.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(be.queryFetch,n,e,t,o)},X.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(be.querySubscribe,n,e,t,o)},X.prototype.hasPending=function(){return!!(this._firstDoc(Ic)||this._firstQuery(Ic)||this._firstSnapshotRequest())};function Ic(n){return n.hasPending()}X.prototype.hasWritePending=function(){return!!this._firstDoc(Ew)};function Ew(n){return n.hasWritePending()}X.prototype.whenNothingPending=function(n){var e=this._firstDoc(Ic);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(Ic);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}un.nextTick(n)},X.prototype._nothingPendingRetry=function(n){var e=this;return function(){un.nextTick(function(){e.whenNothingPending(n)})}},X.prototype._firstDoc=function(n){for(var e in this.collections){var t=this.collections[e];for(var o in t){var r=t[o];if(n(r))return r}}},X.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},X.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},X.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new kw(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},X.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new ww(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},X.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},X.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},X.prototype._initializeHandshake=function(){this.send({a:be.handshake,id:this.id})},X.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},X.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},X.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Yr(Es.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(r5.map[n.type]!==r5.defaultType)return this.emit("error",new Yr(Es.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Yr(Es.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},X.prototype.getPresence=function(n){var e=this,t=un.digOrCreate(this._presences,n,function(){return new yw(e,n)});return t._wantsDestroy=!1,t},X.prototype.getDocPresence=function(n,e){var t=n5.channel(n,e),o=this,r=un.digOrCreate(this._presences,t,function(){return new n5(o,n,e)});return r._wantsDestroy=!1,r},X.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},X.prototype._addPresence=function(n){un.digOrCreate(this._presences,n.channel,function(){return n})},X.prototype._handlePresenceSubscribe=function(n,e){var t=un.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},X.prototype._handlePresenceUnsubscribe=function(n,e){var t=un.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},X.prototype._handlePresence=function(n,e){var t=un.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},X.prototype._handlePresenceRequest=function(n,e){var t=un.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var l5=Bw,Iw=As;const xc={err:1001,msg:"user auth error",name:"AuthError"},xw={err:1002,msg:"you don't have required permission",name:"PermissionError"},hh={err:1003,msg:"Too many user connected",name:"MaxUserError"},Is={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},Tw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Dw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},xs="x-live-editor-token",Tc="x-live-editor-base-url",Ct=w("auth-connection");function Sw(n){try{n()}catch(e){Ct.error(e)}}class Lw{constructor(e,t){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new hm.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=e,this.reauthFunc=t,this.retryCount=0}getBaseURL(){const e=new URL(this.url);return`${e.protocol==="wss:"?"https:":"http:"}//${e.host}${e.pathname}`}getBase64BaseURL(){return Ko(this.getBaseURL())}async auth(e){d(Ct,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[xs]:e.token,[Tc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=e.token,await o.json()}async logout(){if(!this.token)return;const e=`${this.getBaseURL()}/logout`;await window.fetch(e,{method:"GET",headers:{[Tc]:Ko(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new O8.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(l5.prototype),d(Ct,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},l5.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Ct.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const e=await this.reauthFunc();await this.auth(e),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})}}}catch(e){Ct.error(e),setTimeout(()=>this.handleAuthError(),0)}}else Ct.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error(xc.msg);e.code=xc.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(Is.msg);e.code=Is.err,this.events.emit("requestReloadError",e)}emitWriteConflictError(e,t){e.orgMsg=t,this.events.emit("writeConflictError",e)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(e){const t=e;if(t.a==="pong")return;const o=t.err;if(o===xc.err)Ct.warn("auth error"),this.handleAuthError();else if(o===hh.err)Ct.warn(hh.msg),this.emitMaxUsersError();else if(o===Is.err){Ct.warn(Is.msg);try{this.emitRequestReloadError()}catch(r){Ct.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Ct.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return d(Ct,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(d(Ct,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){d(Ct,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){d(Ct,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",e)}end(e){var t;this.reauthFunc=void 0,this.events.removeAllListeners(),Sw(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(t=this.ws)==null||t.close(),this.ws=void 0,e&&this.logout()}}w("utils/file");function Mw(){function n(){return new Promise(e=>{const t=new FileReader;t.onload=()=>{e(t.result)},t.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}Mw();async function Rw(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new F8.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>t&&(c=t);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return Ko(i)}const xn=w("sharedb-doc/client");class Ow{constructor(e,t,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(xn,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const t=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=t,await e(t),xn.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;Iw.register(Bl.type),this.connection=new Lw(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return d(xn,e.endsWith(t),`invalid api server: ${e}, ${t}`),e.substr(0,e.length-t.length)}close(e){this.connection.end(e),this.doc=null}on(e,t){this.connection.addEventListener(e,o=>{(e==="error"||this.doc)&&t(o)})}onWriteConflictError(e){this.connection.onWriteConflictError(e)}onMaxUsersError(e){this.connection.onMaxUsersError(e)}onRequestReloadError(e){this.connection.onRequestReloadError(e)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const e=this.connection.url;if(e.startsWith("ws://"))return`http://${e.substring(5)}`;if(e.startsWith("wss://"))return`https://${e.substring(6)}`;throw new Error(`invalid server url: ${e}`)}async getFileUrlByHash(e,t,o,r,i){try{const s=`${e}/${t}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(e){const o=`${this.apiServer()}/resources`;let r=[];e.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[xs]:this.connection.token}));return await Promise.all(i)}async uploadFile(e,t,o,r,i){let s=t.size;if(s===0)throw new Error("file is empty");s+=500;const l=p=>{xn.info(`on progress: ${p.loaded}`);let b=p.loaded*100/s;b>100&&(b=100),r(b)},c=await Rw(t),a=await this.getFileUrlByHash(e,c,t.name,t.size,o);if(a)return r(-1),a;let u=e;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${t.size}`),f.append("file-hash",c),f.append("file",t,t.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return xn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;d(xn,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[xs]:this.connection.token},t,o);return d(xn,s,"no result"),s}async request(e,t){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=t||{};c.url=e,c.headers||(c.headers={}),d(xn,o,"no token"),c.headers={...c.headers,[xs]:o,[Tc]:this.connection.getBase64BaseURL()};try{return await M8.default(e,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(xn,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions`,r=(await this.request(t)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(e){const o=`${this.apiServer()}/versions/${e}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const t=`${this.apiServer()}/versions/latest`,o=await this.request(t);return JSON.parse(o.data.data)}async getVersionOps(e,t){let r=`${this.apiServer()}/versions/before/${e}?withOp=true`;t!==void 0&&t!==0&&(r+=`&from=${t}`);const i=await this.request(r),s=i.data.ops,l=R8.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(xn,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async updateVersionExtra(e,t,o){const i=`${this.apiServer()}/versions/${e}/tags/${t}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(e){const o=`${this.apiServer()}/versions/revert/${e}`;await this.request(o,{method:"post",data:{}})}async createVersion(e,t){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:t,tag:e}})).data}async recognizeLink(e){const o=`${this.apiServer()}/resources/external/${Ko(e)}`;return(await this.request(o)).data}buildResourceUrl(e,t){if(!e)return"";if(e.startsWith("https:")||e.startsWith("http:")||e.startsWith("file:")||e.startsWith("data:")||e.startsWith("blob:"))return e;let r=`${this.apiServer()}/resources/${encodeURIComponent(e)}`;const i=[];if(t!=null&&t.withToken&&i.push(`token=${this.getResourceToken()}`),t!=null&&t.downloadFileName&&i.push(`&fileName=${encodeURIComponent(t.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function Fw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const fh=w("block-ids");class Pw{constructor(){h(this,"ids",new Map)}onInsertBlock(e){const t=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<t.length;r++){const i=t[r];if(i>=e){const s=this.ids.get(i);d(fh,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(e,o)}onDeleteBlock(e){this.ids.delete(e);const t=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<t.length;o++){const r=t[o];if(r>e){const i=this.ids.get(r);d(fh,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(e){let t=this.ids.get(e);return t||(t=N(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class Nw{constructor(){h(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new Pw,this.ids.set(e,t)),t}onInsertBlock(e,t){this.getContainerIds(e).onInsertBlock(t)}onDeleteBlock(e,t){this.getContainerIds(e).onDeleteBlock(t)}getBlockId(e,t){return this.getContainerIds(e).getId(t)}getBlockIndexById(e){const t=Array.from(this.ids.entries());for(let o=0;o<t.length;o++){const r=t[o],i=r[1].getById(e);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(fh,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class c5{constructor(e=new Set,t=new Map){this.deletedKeys=e,this.insertedValues=t}insert(e,t){this.insertedValues.set(e,t)}delete(e){this.deletedKeys.add(e)}toDocBlockDelta(){const e={};return this.insertedValues.forEach((t,o)=>{e[o]=t}),{insert:e,delete:Array.from(this.deletedKeys)}}}const Dc=w("op-parse-handler");class $w{constructor(e,t){h(this,"actions",[]);this.outerHandler=e,this.local=t}pushActions(e){if(!e.containerId){this.actions.push(e);return}const o={...e,containerId:(r=>r==="blocks"?"root":r)(e.containerId)};this.actions.push(o)}onDeleteBlock(e,t){this.pushActions({type:"deleteBlock",containerId:e,blockIndex:t})}onInsertBlock(e,t,o){this.pushActions({type:"insertBlock",containerId:e,blockIndex:t,data:o})}onDeleteBlockData(e,t,o){this.pushActions({type:"deleteBlockData",containerId:e,blockIndex:t,key:o})}onInsertBlockData(e,t,o,r){this.pushActions({type:"insertBlockData",containerId:e,blockIndex:t,key:o,value:r})}onUpdateBlockText(e,t,o){this.pushActions({type:"updateBlockText",containerId:e,blockIndex:t,richTextData:o})}onDeleteContainer(e){this.pushActions({type:"deleteContainer",containerId:e})}onCreateContainer(e,t){this.pushActions({type:"createContainer",containerId:e,data:t})}onDeleteComment(e){this.pushActions({type:"deleteComment",commentId:e})}onCreateComment(e){this.pushActions({type:"createComment",commentId:e})}onUpdateComment(e){this.pushActions({type:"updateComment",commentId:e})}end(){const e=this.actions,t=new Set,o=new Map,r=new Nw,i=e.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,c=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const a=o.get(c);a&&(Dc.debug(`ignore update object data before delete block: ${JSON.stringify(a)}`),o.delete(c));const u=`${l.containerId}-${l.blockIndex}`;t.add(u),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(t.has(c)){Dc.warn("delete block data after delete block, ignore it");continue}const a=r.getBlockId(l.containerId,l.blockIndex);let u=o.get(a);u||(u=new c5,o.set(a,u)),u.delete(l.key)}else d(Dc,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=r.getBlockId(l.containerId,l.blockIndex);let a=o.get(c);a||(a=new c5,o.set(c,a)),a.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(o.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:a}=r.getBlockIndexById(s);Dc.debug(`update block data: ${c}, ${a}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(c,a,l.toDocBlockDelta(),this.local)})}}const He=w("op-parser");class a5{}class mh{constructor(e){h(this,"key");this.key=e}}function _w(n,e,t){const o=e.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d(He,s.id,"block id is required"),d(He,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return t.onInsertBlock(n,r,s),!0}function gh(n,e,t,o){if(t==="upsert"&&_w(n,e,o))return;d(He,Array.isArray(e),`invalid block op: ${n}, ${JSON.stringify(e)}`);const r=e.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d(He,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),d(He,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d(He,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(He,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(He,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(He,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&t==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&t==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&t==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else t==="remove"&&a.r&&s.push(new mh(c)),t==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;t==="remove"&&c.r&&s.push(new a5),t==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(He,typeof l=="string","data is not string"),d(He,l!=="text","data !== 'text'"),d(He,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];t==="remove"&&a.r&&s.push(new mh(c)),t==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof a5?o.onDeleteBlock(n,i):l instanceof mh?o.onDeleteBlockData(n,i,l.key):d(He,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function Hw(n,e,t){He.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function jw(n,e,t){const o=n[1],r=n[2];d(He,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(He,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?He.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?e==="upsert"&&t.onUpdateComment(o):r.i?e==="upsert"&&t.onCreateComment(o):r.r?e==="remove"&&t.onDeleteComment(o):He.error(`unknown comment op, ${JSON.stringify(n)}`)}function ph(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{ph(s,e,t)});return}const r=o;if(d(He,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){Hw(n);return}if(r==="comments"){jw(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{gh(i,s,e,t)}):n.slice(1).forEach(s=>{gh(i,s,e,t)});else if(typeof n[1]=="object"){const s=n[1];s.r&&e==="remove"&&t.onDeleteContainer(i),s.i&&e==="upsert"&&t.onCreateContainer(i,s.i)}else d(He,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),gh(i,n.slice(1),e,t)}function u5(n,e,t){const o=new $w(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Q.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{ph(c,i,o)}):ph(s,i,o)}o.end()}const zw=w("sharedb-comments");function Ch(n){const e=n.blocks;d(zw,e,"no comment blocks");const t={blocks:{root:e},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(t.blocks[o]=r)}),Q.default(t)}function d5(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function Ah(n,e){const t=Ik(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},c=Q.default(l);return delete c.children,c}const ke=w("sharedb-doc/doc-container"),h5="ot-json1";Bl.type.registerSubtype(xk.type),Bl.type.name=h5,Bl.type.invert=null;class Ts extends zi{constructor(t,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new Bk);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});h(this,"handleReset",async t=>{const o=new Error(`reset doc: ${t}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});h(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,c])=>{if(!_i.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){ke.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(ke.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),ke.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ke.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));h(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,h5,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(t,o)=>{const r=[Bo(t),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async t=>{const o=[Bo(t),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(t,o,r)=>{const i=[Bo(t),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(t,o)=>{const r=[Bo(t),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Bo(t),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(t,o,r)=>{const i=[Bo(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(t,o,r)=>{if(this.destroyed){ke.warn("handleOp: destroyed");return}u5(t,this,!!o)});this.client=t,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(ke,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new Ow(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new Ts(o,r,t.disableLogout);if(r.type===null){if(t.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(t.templateData||Fw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ke.error(o),ke.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((t,o)=>{if(this.localPresence)t();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return ps(this.data())}getContainerBlocks(t){const o=this.data();d(ke,o,"no doc data");const r=o[Bo(t)];return d(ke,r,`no container data: ${t}`),Q.default(r)}getBlockData(t,o){const r=this.data();d(ke,r,"no doc data");const i=r[Bo(t)];d(ke,i,`no container data: ${t}`);const s=i[o];return d(ke,s,`no block data: ${o}`),Q.default(s)}localInsertBlock(t,o,r){return this.submitInsertBlock(t,o,r),this.getBlockData(t,o)}localDeleteBlock(t,o){const r=this.getBlockData(t,o);return this.submitDeleteBlock(t,o),r}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);d(ke,i.text,"no block text");const s=Q.default(i.text);this.submitUpdateRichText(t,o,r);const l=dt.apply(s,r);return d(ke,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=Q.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainer(t,o){this.submitInsertChildContainer(t,o)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>d5(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return Ch(o)}localCreateComment(t,o){const r=Ah(t,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(t){const o=["comments",t,{r:!0}];return this.submitOp(o)}localUpdateComment(t,o){const r=Ah(t,o),i=["comments",t.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var t;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(t=this.localPresence)==null||t.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(t,o,r){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Zr(t),o,r)})}onInsertBlock(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Zr(t),o,r,i)})}onUpdateBlockData(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Zr(t),o,r,i)})}onUpdateBlockText(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Zr(t),o,r,i)})}onDeleteContainer(t,o){d(ke,this.callbacks.length>0,"no callbacks"),d(ke,t!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Zr(t),o)})}onCreateContainer(t,o,r){d(ke,this.callbacks.length>0,"no callbacks"),d(ke,t!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Zr(t),o,r)})}onDeleteComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,t,o)})}onCreateComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,t,o)})}onUpdateComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){const o=t;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:t,clientId:"-"};this.onCustomMessage(r)})}async addResources(t){return await this.client.getFileUrlsByHashes(t)}async uploadResource(t,o){var i;return{resourceId:await this.client.uploadResource(t,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(t,o){return this.client.buildResourceUrl(t,o)}request(t,o){return this.client.request(t,o)}getUser(){const t=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:t,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(t){const o=await this.client.getVersion(t);return ps(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return ps(t)}async getHistoryData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ps(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:ps(r),versionData:i}}async updateVersionExtra(t,o,r){await this.client.updateVersionExtra(t,o,r)}revertVersion(t){return this.client.revertVersion(t)}createVersion(t,o){return this.client.createVersion(t,o)}async recognizeLink(t){return this.client.recognizeLink(t)}parseHistoryData(t,o){u5(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class f5{constructor(e){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",nt.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));h(this,"handleRemoteCaretsChanged",e=>{e.forEach(t=>{const o=this.editor.findBlockById(t);o&&this.editor.reloadBlock(o)})});this.editor=e,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const m5=w("remote-cursor-decorator");class bh{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];d(m5,typeof s=="string","invalid path containerId"),d(m5,typeof l=="number","invalid path blockIndex");const c=e.doc.getBlockData(s,l),a=at(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const p=f.map(k=>({id:N(),type:"remote-cursor",name:k.user.displayName,time:k.time,rainbowIndex:k.user.rainbowIndex})),b=i.get(m);b?b.push(...p):i.set(m,p)}),{insertions:i}}}class g5 extends Ve.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Ae(_r(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=j(this.editor.getContainerById(e));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(e,t){this.handleChild(e,t,"data-change")}onUpdateBlockText(e,t){this.handleChild(e,t,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function Uw(n,e){n.addCustom("child-block-tracker",()=>new g5(n)).addListener("change",e)}function Vw(n,e){n.addCustom("child-block-tracker",()=>new g5(n)).removeListener("change",e)}const jV="",qw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Ww={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Gw={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};I.mergeLang({"zh-CN":qw,"en-US":Ww,"js-JP":Gw});const zV="";w("button");function xo(n,e,t,o,r){const i=A("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,e),t?typeof t=="string"?t.startsWith("<")?i.innerHTML=t:i.innerText=t:i.appendChild(t):i.innerText=e,o&&(o.indexOf("checked")!==-1&&M(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function p5(n,e,t){t?n.setAttribute(`data-editor-tooltip-${t}`,e):n.innerText=e}const UV="",Jr=w("ui-command-bar-base"),Zw={itemElementTag:"div",tippyArrow:!1},qf=class extends Ve.TypedEmitter{constructor(t,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"options");h(this,"id");h(this,"handleDocumentKeydown",t=>{if(!!this.isVisible&&!t.isComposing&&!Nr(t.target)){if(this.subBar){this.subBar.handleDocumentKeydown(t);return}if(this.items.length!==0){if(t.key==="Escape"){this.close();return}if(t.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(t.key==="ArrowLeft")this.parentItem&&this.close();else if(t.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",t=>{if(t.target instanceof Element&&!this.isInCommandBar(t.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,t)===!1)return;this.close()}});h(this,"handleHidden",()=>{this.close(),this.emit("close",this),Wm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&M(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&qm(this.id)});h(this,"lastEnterPauseTime",0);h(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});h(this,"handleItemMouseEnter",t=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",t=>{var r,i;const o=this.getParentCommandItemElement(t.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(H(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",t=>{const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close())}});h(this,"handleWheel",t=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=t.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=vn(r);if(!Ce(this.content,i)){t.stopPropagation(),t.preventDefault();return}t.deltaY<0?i.scrollTop===0&&(t.stopPropagation(),t.preventDefault()):t.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(t.stopPropagation(),t.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...Zw,...r},this.items=t,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(t)}close(){this.subBar&&this.subBar.close(),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(t,o){this.emit("click",this,t,o)}createPopperOptions(){var r,i;const t={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=t==null?void 0:t.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=t==null?void 0:t.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),t}destroy(){var t;this.close(),this.removeAllListeners(),(t=this.subBar)==null||t.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(t){var r;this.subBar&&t.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=t;const o=this.createCommandBarContent(t);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const t=this.getSelectedItem();return t?this.items.indexOf(t):-1}getPrevItemIndex(t){if(t<=0)return this.items.length-1;let o=t-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(t){let o=t+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const t=this.getSelectedItem();if(!t)return;const o=this.getItemElementById(t.id);o&&H(o,"selected")}selectItem(t){const o=this.getSelectedItem();if(o){if(o.id===t)return;const i=o.id,s=this.getItemElementById(i);s&&H(s,"selected")}const r=this.getItemElementById(t);r?(M(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(t){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close();return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=qf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,t?{id:t}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,H(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),M(r,"active")}isInCommandBar(t){if(!t||!(t instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Ce(o,t)||Ce(this.content,t)?!0:this.subBar?this.subBar.isInCommandBar(t):!1}createCommandItem(t){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";t.element&&(o="div");const r=A(o,["command-item"],null);return r.setAttribute("data-id",t.id),t.type==="separator"?r.classList.add("separator"):t.type==="section"?(r.classList.add("section","text"),t.element&&(typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element))):((s=t.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=t.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=t.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,t.element?typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element):r.classList.add("standard")),this.initItemElement(t,r),r}getItemById(t){const o=this.items.find(r=>r.id===t);return d(Jr,o,`can not find command item for id: ${t}`),o}getSelectedItem(){const t=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(t){const o=this.getItemElementId(t),r=this.items.find(i=>i.id===o);return d(Jr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(t){const o=t.getAttribute("data-id");return d(Jr,o,"no data-id attribute"),o}getItemElementById(t){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${t}"]`);return d(Jr,o,`no exists command item, id=${t}`),o}getParentCommandItemElement(t){if(!t||!(t instanceof Element))return null;if(ne(t,"command-item"))return t;const o=t.closest(".command-item");return o||null}createCommandBarContent(t){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=A("div",["editor-command-bar-root"],null),r=A("div",["editor-command-bar"],o);return this.options.header&&A("div",["editor-command-bar-header"],r).appendChild(this.options.header),t.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(t){var o;return{placement:(o=t.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(t,o){this.commandBarCreators.set(t,o)}static createSubCommandBar(t,o,r){var l;d(Jr,t.children&&t.children.length>0,"no item children");const i=(l=t.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Jr,s,`no creator for command type: ${i}`),s(t,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let To=qf;h(To,"commandBarCreators",new Map),w("ui-command-bar");class Sc extends To{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(t,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=P8.default(t,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(){var t;super.close(),this.isVisible&&((t=this.tippyInstance)==null||t.hide())}destroy(){var t;(t=this.tippyInstance)==null||t.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var t,o;return(o=(t=this.tippyInstance)==null?void 0:t.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const C5=w("ui-base");class Ds extends Sc{constructor(e,t){var i;const r=[{id:(i=t==null?void 0:t.id)!=null?i:`popup-${N()}`,name:"",element:e}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(e){M(e,"popper")}initItemElement(e,t){}get popupContent(){const e=this.items[0];d(C5,e,"no dialog item");const t=typeof e.element=="function"?e.element(e):e.element;return d(C5,t,"no item element"),t}}const Do=w("filterable-list");function A5(n){var t,o;const e=A("div",["list-item"],null);return e.setAttribute("data-id",n.id),e.appendChild(A("div",["list-item-text"],null,n.name)),(t=n.states)!=null&&t.includes("selected")&&M(e,"selected"),(o=n.states)!=null&&o.includes("disabled")&&M(e,"disabled"),e}function b5(n){const e=A("div",["list-root"],null);return n.forEach(t=>{e.appendChild(A5(t))}),n.length||e.appendChild(A5({id:"placeholder",states:["disabled"],name:I.t("search.emptyTips")})),e}function v5(n,e){let t=n;return e&&(t=n.map(o=>({...o,states:o.id===e?["selected"]:void 0}))),t}function Qw(n,e){const t=A("div",["filterable-list"],null),o=A("div",["filter"],t),r=A("div",["filter-container"],o),i=A("input",["filter-input"],r);e&&e.placeholder&&(i.placeholder=e.placeholder);const s=A("div",["list"],t),l=b5(v5(n,e==null?void 0:e.initialSelectedId));return s.appendChild(l),t}function y5(n,e,t){const o=n.querySelector(".list");d(Do,o,"no list root");const r=b5(v5(e,t)),i=o.querySelector(".list-root");if(d(Do,i,"no exists menu"),Wi(i,r),t){const s=o.querySelector(".list-item.selected");s&&(d(Do,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class Yw{constructor(e,t){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",e=>{this.processKeyDown(e)});h(this,"handleInputChanged",()=>{const e=this.root.querySelector(".filter-input");d(Do,e,"no input");const t=e.value.toLocaleLowerCase();this.setFilter(t)});h(this,"handleClick",e=>{this.processClick(e)});var o;this.items=e,this.options=t,this.root=Qw(e,t),this.bindEvents(),this.selectedId=(o=t==null?void 0:t.initialSelectedId)!=null?o:"",this.visibleItems=e}bindEvents(){const e=this.root.querySelector(".filter-input");d(Do,e,"no input"),e.addEventListener("keyup",this.handleInputChanged),e.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const e=this.root.querySelector(".filter-input");d(Do,e,"no input"),e.removeEventListener("keyup",this.handleInputChanged),e.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(e=>e.id===this.selectedId):-1}setSelectedId(e){this.selectedId=e,y5(this.root,this.visibleItems,e)}focus(){const e=this.root.querySelector(".filter-input");d(Do,e,"no input"),e.focus()}reset(){this.setFilter("");const e=this.root.querySelector(".filter-input");d(Do,e,"no input"),e.value=""}setFilter(e){this.filter!==e&&(this.filter=e,this.visibleItems=this.items.filter(t=>t.name.toLocaleLowerCase().includes(e)),y5(this.root,this.visibleItems,this.selectedId))}processClick(e){var s,l;const t=e.target;if(!(t instanceof HTMLElement))return;const o=t.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(e){var t;if(e.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="Enter"){const o=(t=this.visibleItems.find(r=>r.id===this.selectedId))!=null?t:null;this.onSelected&&this.onSelected(this,o)}}}class Jw extends Yw{constructor(t,o,r){super(t,r);h(this,"popup");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.popup=new Ds(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(t){this.reset(),this.popup.manualShow(t,{theme:"dropdown-list"}),this.focus()}processKeyDown(t){super.processKeyDown(t),(t.key==="Esc"||t.key==="Enter")&&this.popup.close()}processClick(t){super.processClick(t);const o=t.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close()}}const VV="",qV="";function Kw(n,e){const t=document.createElement("div");t.classList.add("toast","show"),e!=null&&e.theme&&t.setAttribute("data-theme",e.theme),e!=null&&e.id&&t.setAttribute("data-id",e.id),e!=null&&e.html?t.innerHTML=n:t.textContent=n,e!=null&&e.position&&(t.style.left=`${e.position.x}px`,t.style.top=`${e.position.y}px`,t.classList.add("positioned")),document.body.appendChild(t),setTimeout(()=>{t.classList.remove("show"),setTimeout(()=>{t.remove()},500)},(e==null?void 0:e.duration)||3e3)}const k5=`<?xml version="1.0" ?>