@ones-editor/editor 0.0.3-beta.224 → 0.0.3-beta.225
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
|
@@ -24,7 +24,7 @@ Available method signatures are:
|
|
|
24
24
|
`:""}const C6={boxType:"br",updateBoxContent:NI,convertTo:$I},A6=S("editor-boxes");class b6{constructor(e){m(this,"boxes",new Map);this.editor=e}registerBoxClass(e){const t=e.boxType,o=this.boxes.get(t);g(A6,!o,`duplicated box type: ${t}`),this.boxes.set(t,e)}getBoxClass(e){const t=this.boxes.get(e);return g(A6,t,`unknown box type: ${e}`),t}createBox(e,t){const o=Q5(t),r=J5(o);return this.getBoxClass(t.type).updateBoxContent(this.editor,o,r,t),o}forEach(e){this.boxes.forEach(e)}}function HI(n,e,t,o){const r=o,{width:i,height:s,src:l}=r,a=["editor-box-image"];r.link&&a.push("editor-box-image-link");const d=k("img",a,t);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const v6={boxType:"image",updateBoxContent:HI},jI="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function UI(n,e,t){W(t,"editor-box-anchor"),Bm(jI,[],t)}const y6={boxType:"anchor",updateBoxContent:UI};function zI(n,e,t,o){k("span",[],t,o.text)}const k6={insertionType:"inputting",updateInsertionContent:zI},w6=S("editor-insertion");class B6{constructor(e){m(this,"insertions",new Map);this.editor=e}registerInsertionClass(e){const t=e.insertionType,o=this.insertions.get(t);g(w6,!o,`duplicated insertion type: ${t}`),this.insertions.set(t,e)}getInsertionClass(e){const t=this.insertions.get(e);return g(w6,t,`unknown insertion type: ${e}`),t}createInsertion(e,t){const o=K5(t.type,t.id),r=e4(o);return this.getInsertionClass(t.type).updateInsertionContent(this.editor,o,r,t),o}}class VI{constructor(e){m(this,"cursors",new Map);m(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=X5(this.editor,t);r&&re(r,"active"),this.cursors.delete(t)}})},1e3)}destroy(){clearInterval(this.timer)}}function WI(n,e,t,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new VI(d)).add(r.id,r.time),W(e,"active")),k("span",[],t,"|").setAttribute("data-cursor-name",r.name),e.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const xg={insertionType:"remote-cursor",updateInsertionContent:WI};class E6{constructor(e){m(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=me.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:a}=s;l&&Array.from(l.entries()).forEach(([d,h])=>{const p=r.get(d);p?p.push(...h):r.set(d,h)}),a&&(o=me.default(a))}}}),{insertions:r,text:o}}}const Ig=S("editor-input");class qI{constructor(e,t){m(this,"editor");m(this,"composing",!1);m(this,"callbacks");m(this,"inputElement");m(this,"handleDocumentClick",e=>{const t=this.editor.rootContainer,o=e.target;if(o&&t.contains(o)&&!Ds(o)){this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus();return}this.editor.emit("blur",this.editor),this.callbacks.onBlur()});m(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var t;const e=(t=document.getSelection())==null?void 0:t.focusNode;e&&this.editor.contains(e)&&!Ds(e)||(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});m(this,"handleEditorSelectionChanged",()=>{const t=!this.editor.isWritable();this.inputElement.readOnly=t});m(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});m(this,"handleCompositionstart",e=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(e))});m(this,"handleCompositionend",e=>{this.composing=!1,this.callbacks.onUpdateCompositionText(e,this.inputElement.value,!0),this.inputElement.value=""});m(this,"handleInput",e=>{if(e instanceof InputEvent&&!!e.data){if(this.editor.readonly||!this.editor.isWritable()){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(e,e.data,!1):(this.callbacks.onInsertText(e,e.data),this.inputElement.value="")}});m(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="")})}});m(this,"handleCopy",e=>{this.callbacks.onCopy(e)});m(this,"handleCut",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onCut(e),Ig.debug("on cut")});m(this,"handlePaste",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onPaste(e)});m(this,"handlePasteText",(e,t)=>{this.callbacks.onPasteText(e,t)});this.editor=e,this.callbacks=t;const o=k("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("click",this.handleDocumentClick),document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("click",this.handleDocumentClick),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(),Zt.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){g(Ig,e===this.editor,"invalid editor"),this.callbacks.defaultInsertText(e,t,o,r,i)}defaultHandleKeydown(e,t){return g(Ig,e===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(e,t)}}function x6(n){const e=n.rootElement,t=e.getBoundingClientRect(),o=ro(e),r=window.innerWidth,i=window.innerHeight,s=t.left<0?0:t.left,l=t.top<0?0:t.top,a=t.right>r?r:t.right,d=t.bottom>i?i:t.bottom,h=(s+a)/2,p=(l+d)/2,C=0-t.left+h,v=0-t.top+p,B=n.input.inputElement;B.style.left=`${C/o}px`,B.style.top=`${v/o}px`}const Tg=S("editor-caret");class GI{constructor(e){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=e,this.caretElem=k("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 Ut))return!1;const t=this.editor.getBlockById(e.blockId);return!!ne(this.editor,t)}update(){if(l5(this.editor.rootElement))return;const e=this.caretElem;if(this.hasCaret())e.style.display="";else{e.style.display="none",x6(this.editor);return}const{range:t}=this.editor.selection;g(Tg,t.isCollapsed,"range is not collapsed");const o=t.start;g(Tg,o instanceof Ut,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(Tg,ne(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=bs(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Vn(r,o);const l=this.editor.contentElement.getBoundingClientRect(),a=i.left-l.left,d=i.top-l.top;e.style.left=`${a}px`,e.style.top=`${d}px`,e.style.height=`${i.height}px`;const h=this.editor.input.inputElement;h.style.left=`${a}px`,h.style.top=`${d+i.height-24}px`,Zt.isMobileSafari&&(h.style.left=`${a-4}px`,h.style.height=`${i.height}px`);const C=so(r,{horizontal:!0}).getBoundingClientRect(),v=C.left-l.left,B=v+C.width;a<v||a>B?(x6(this.editor),e.style.display="none"):e.style.display=""}}function ZI(n){i4(n),n.selection.range.getSelectedBlocks().forEach(e=>s4(n,e.block,e.start,e.end))}const QI=S("editor-dom");function I6(n){return so(n.rootContainer).clientHeight}function YI(n){return n.getFirstBlock().getBoundingClientRect().top}function JI(n){return n.getLastBlock().getBoundingClientRect().bottom}function Dg(n){const t=so(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 KI(n,e){const t=Dg(n),o=n.getBlockById(e.blockId),i=Lo(n,o,e);return ys(t,i.x,i.y)&&ys(t,i.right,i.bottom)}function T6(n,e){const t=Dg(n),o=e.getBoundingClientRect();return o.top>=t.top&&o.top<=t.bottom||o.bottom<=t.bottom&&o.bottom>=t.top}function XI(n,e){const t=Dg(n),o=e.getBoundingClientRect();return ys(t,o.x,o.y)||ys(t,o.right,o.bottom)}function eT(n){if(!Tm(n.rootContainer)){QI.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 p=o,C=n.getContainerById(p.childContainerId);XI(n,C)||C.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const p=n.getBlockById(t.range.start.blockId);if(It(p)&&T6(n,p)||Me(n,p)&&T6(n,p))return}const r=o,i=n.getBlockById(r.blockId);if(KI(n,r))return;const s=Lo(n,i,r),l=i.getBoundingClientRect(),a=tt(i),d=k("div",["editor-block-anchor"],a),h=ro(i);d.style.top=`${(s.top-l.top)/h}px`,Kd(d,{elementToScroll:so(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function tT(n,e){if(e.isCollapsed())return!1;const t=yt(n.rootContainer),o=Qt(n.rootContainer),{start:r,end:i}=e;return r.blockId===ie(t)&&r.offset===0&&i.blockId===ie(o)&&i.offset===ue(n,o)}const D6=S("range-in-block");function S6(n,e){const t=e.getEditor(),o=t.getBlockById(e.start.blockId),r=t.getBlockById(e.end.blockId),i=o===n||et(n,o),s=r===n||et(n,r);return!!(i||s)}function L6(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=at(e);if(i){for(;i&&!o.has(ie(i));)i=at(i);g(D6,i,"no prev block while deleting a block"),r=kt(n,i,ue(n,i))}else{const s=Qe(e);g(D6,s,"no prev and next block while deleting a block"),r=kt(n,s,0)}return r}const nT=S("block-to-html");function Sg(n,e,t,o){const r=Ss(n,e.type);if(r.convertTo)return r.convertTo(n,e,t,"html",o);if(r.blockKind!=="text")return`[${e.type}]`;g(nT,e.text,"no text");const i=it(e.text);return`<div>${d5(i)}</div>`}const M6=S("block-to-text");function oT(n,e,t){let o="";return e.forEach(r=>{if(g(M6,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 Sh(n,e,t,o){const r=Ss(n,e.type);return r.convertTo?r.convertTo(n,e,t,"text",o):r.blockKind!=="text"?`[${e.type}]`:(g(M6,e.text,"no text"),oT(n,e.text,t))}function Lg(n,e,t,o){const r=Ss(n,e.type);return r.convertTo?r.convertTo(n,e,t,"markdown",o):Sh(n,e,t,o)}function Lh(n,e){return e.blocks.root.map((r,i)=>Sg(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
|
|
25
25
|
`)}function R6(n,e){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${Lh(n,e)}</body></html>`}function Na(n,e){return e.blocks.root.map((r,i)=>Sh(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
|
|
26
26
|
`)}function $a(n,e){const t=e.blocks.root.map((r,i)=>Lg(n,r,e,[{containerId:"root",blockIndex:i}]));return t[t.length-1]=t[t.length-1].trimEnd(),t.join(`
|
|
27
|
-
`)}const rT=S("get-text-position");function Zl(n,e){const t=e!=null?e:n.selection.range.start;t instanceof Ut||g(rT,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=be(r),s=oe(r),l=ce(s),{offset:a}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Ql=S("insert-text");function Mg(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(g(Ql,r,"no block data"),g(Ql,r.text,"no block text"),rn(r.text)===0)return g(Ql,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Vt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function iT(n,e,t){const o=oe(e),r=ce(o),i=be(e);return Mg(n,r,i,t)}function O6(n,e,t,o,r){const i=oe(e),s=ce(i),l=be(e),a=iT(n,e,t),d=vh(t,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),pn(n,e)}function _6(n,e,t,o){const r=oe(e),i=ce(r),s=be(e),l=vh(t," ",o);return n.doc.localUpdateBlockText(i,s,l),pn(n,e)}function sT(n,e){let t=0;if(e===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Ql,typeof r.insert=="string","invalid text op, no insert");const i=t+yh(r);if(i===e)return!1;if(i>e)return!0;t=i}return!1}function Rg(n,e,t,o,r){const i=n.doc.getBlockData(t,o);g(Ql,i,"no block data"),g(Ql,i.text,"no block text");const s=Mg(n,t,o,r);s&&Object.keys(s).includes("link")&&(sT(i.text,r)||delete s.link);const l=vh(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),pn(n,n.getBlockById(i.id))}function Og(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=Zl(n);Rg(n,e,t,o,r)}const Mh=S("update-composition-text");function F6(n){const e=n.selection.range.start;e instanceof Ut||g(Mh,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);g(Mh,ne(n,o),"not a text kind block");const r=oe(o),i=ce(r),s=be(o),l=n.doc.getBlockData(i,s);g(Mh,l,"no block data in doc"),g(Mh,l.text,"no text data in text block");const a=Le(o);ph(n,Ri(o),t,a,l.text)}function P6(n){Px(n)}function Yl(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const Ha=S("delete-block-text");function _g(n,e,t,o,r){if(!n.isBlockWritable(e))return Ha.error("block is not writable"),0;g(Ha,ne(n,e),"block is not a text kind block");const i=oe(e),s=ce(i),l=be(e),a=n.doc.getBlockData(s,l);g(Ha,a,"no block data in doc"),g(Ha,a.text,"no text data in text block");let d=t;sn(e,t)||(d=_i(e,d));let h=t+o;g(Ha,h<=ue(n,e),`invalid offset and count: ${t}, ${o}`),sn(e,h)||(h=Os(e,h));const p=h-d,C=G4(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const Fg=S("break-text-block");function N6(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function Jl(n,e,t,o){g(Fg,ne(n,e),`block is not a text kind block: ${De(e)}`),g(Fg,t>=0&&t<=ue(n,e),`invalid offset: ${t}`);const r=oe(e),i=ce(r),s=be(e),l=o!=null&&o.copyBlockAttributes?N6(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===ue(n,e))){const v=t===0?s:s+1,B={...ur(""),...l,...o==null?void 0:o.newBlockData},D=kt(n,e.id,0),x=Yl(n,i,v,B,D);return{block:e,newBlock:x}}g(Fg,sn(e,t),"not a valid offset");const a=pn(n,e),{right:d}=Tn(a,t),h=rn(d);h>0&&_g(n,e,t,h);const p={...ur(d),...l,...o==null?void 0:o.newBlockData},C=Yl(n,i,s+1,p,kt(n,p.id,0));return{block:e,newBlock:C}}const lT=S("prepare-insert-new-block");function cT(n,e,t){if(e&&t!==void 0&&t!==null){const d=n.getContainerById(e),h=mt(d);return g(lT,t>=0&&t<=h.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=ce(oe(r)),t=be(r),!ne(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===ue(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const a=Jl(n,r,s).newBlock;return{containerId:e,blockIndex:be(a)}}const aT=S("auto-insert-block");function $6(n,e,t,o,r,i){const s=cT(n,t,o);g(aT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},a={anchor:l,focus:l};return Yl(n,s.containerId,s.blockIndex,e,r!=null?r:a,i)}const uT=S("delete-block");function Rh(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Rh(n,i,t)})}))}function Oh(n,e,t){const o=oe(e),r=ce(o),i=be(e),s=n.doc.getBlockData(r,i);return g(uT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,zt(n,{anchor:t.start,focus:t.end})),s}function Pg(n,e,t){return n.undoManager.runInGroup(()=>{const o=oe(e);To(o)===1&&n.insertTextBlock("",ce(o),0);let r=t?Oi(n,t):null;if(!r){const l=n.selection.range;S6(e,l)?r=L6(n,e):r=l}const i=Oh(n,e,r),s=[];return Rh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function dT(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{Rh(n,r,t)}),n.doc.localDeleteChildContainers(t)}function H6(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Rh(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Ng=S("merge-text-block");function j6(n,e,t){g(Ng,ne(n,e),"only text block can be merged"),g(Ng,ne(n,t),"only text block can be merged");const o=Pi(n,e),r=Pi(n,t),i=o.text,s=r.text;g(Ng,i&&s,"block data has no text");const l=oe(e),a=ce(l),d=be(e),h=ue(n,e),p=Rg(n,s,a,d,h),C=kt(n,e,rn(i));return Pg(n,t,C),p}const dr=S("clear-selected-contents");function _h(n,e){g(dr,ne(n,e.block),"not a text kind block");const{start:t,end:o}=e;g(dr,t.isSimple(),"not a simple block position"),g(dr,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;g(dr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function U6(n,e,t){const o=ce(e),r=mt(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 hT(n,e){const{block:t,start:o,end:r}=e;if(ne(n,t)){_h(n,e);return}if(It(t)||o.isSimple()){g(dr,r.isSimple(),"invalid range");const s=oe(t),l=be(t),a=n.insertTextBlock("",ce(s),l);n.selection.selectBlock(a,0),n.deleteBlock(t);return}g(dr,Me(n,t),"invalid block kind"),g(dr,!o.isSimple()&&!r.isSimple(),"invalid range"),Vl(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{U6(n,s,{focus:l===0})})}function fT(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(g(dr,t.length>0,"no selected block"),t.length===1){hT(n,t[0]);return}const o=t[0],r=o.block,i=oe(r);g(dr,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if(ne(n,r)){_h(n,o);const h=kt(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),ne(n,l)){_h(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(ne(n,l)){_h(n,s),t.slice(0,t.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(t.length===To(i)){U6(n,i,{focus:!0});return}const a=at(r),d=Qe(l);g(dr,a||d,"no prev or next block"),t.forEach(h=>n.deleteBlock(h.block))}function $g(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),fT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const mT=S("core");function z6(n,e,t){const o=oe(e),r=ce(o),i=be(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),pn(n,e)}function V6(n,e,t){if(!n.isBlockWritable(e)){mT.error("block is not writable");return}const o=n.getBlockText(e),r=ln.diff(o,t);z6(n,e,r)}function Fh(n,e,t){const o=pn(n,e),r=typeof t=="string"?Fi(t):t,i=ln.diff(o,r);return z6(n,e,i)}const ja=S("update-block-data");function Ph(n,e,t,o){const r=oe(e),i=ce(r),s=be(e),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(t));return d.forEach(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;ja.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(t).forEach(([C,v])=>{g(ja,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(ja.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(fa.default(B,v)||C==="text"&&ln.diff(B,v).length===0||(d.has(C)?(ja.debug(`replace key: ${C}`),a.delete.push(C)):ja.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Pi(n,e)}function W6(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Hg(n,e,t){if(!Me(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=zn(n,e).getChildContainers(n,e)[0],i=yt(r);Hg(n,i,t)}function Ps(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 Ua=S("clone-block");function Ni(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(h,p)=>(g(Ua,t!==p,"invalid child block"),Ni(n,h,t,o)));let i={};const s=new Map,l=me.default(t);l.children&&(l.children=l.children.map(h=>{const p=K(),C=e.blocks[h];g(Ua,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Ni(n,e,_,o)),B=Ps(v),{root:D,...x}=B.blocks;return i={...i,...x},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[C,v]=p;{const B=`${C}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return Ua.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${C}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return Ua.debug(`replace key: ${h} -> ${x}`),x}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const C=d(h);C!==h&&delete l.key,l[C]=p}),l.id=K(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function jg(n,e,t,o){const r=e.blocks[t];g(Ua,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Ni(n,e,l,o));return Ps(i)}function Ug(n,e,t){const o=e.blocks.root.map(r=>Ni(n.editorBlocks,e,r,t));return me.default(Ps(o))}const q6=S("insert-doc");function G6(n,e,t,o,r){if(Me(n,e)){q6.warn("failed to insert doc into a complex block");return}const i=Ug(n,o,r),s=oe(e),l=be(e),a=ce(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,z,Q;const d=[];Object.entries(i.blocks).forEach(([ee,fe])=>{ee!=="root"&&d.push({containerId:ee,blocks:fe})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(It(e)){n.deleteBlock(e);let ee;h.reverse().forEach(fe=>{const ve=n.insertBlock(a,l,fe,void 0,{noFocus:!0});ee||(ee=ve)}),ee&&n.selection.selectBlock(ee,ue(n,ee));return}if(g(q6,ne(n,e),"not a text block"),ut(n,e)){const ee=a==="root"&&n.getBlockByIndex(a,0)===e,fe=be(e);let ve;h.forEach((ze,He)=>{const Ke=n.insertBlock(a,fe+He,ze,void 0,{noFocus:!0});He===h.length-1&&(ve=Ke)}),ve&&n.selection.selectBlock(ve,ue(n,ve)),ee&&n.deleteBlock(e);return}if(h.length===1){const ee=h[0];if(xa(n,ee.type)){n.insertTextToBlock(e,t,(H=ee.text)!=null?H:[]);return}n.breakTextBlock(e,t),n.insertBlock(a,l+1,ee);return}const p=t===ue(n,e),C=t===0,v=h[0],B=h[h.length-1];let D;!p&&!C?D=n.breakTextBlock(e,t,{forceInsertAfter:!0}):D=e;const x=C?l:l+1;p?(D=n.insertBlock(a,l+1,B),n.selection.selectBlock(D,ue(n,D))):(n.selection.selectBlock(D,0),xa(n,B.type)?n.insertTextToBlock(D,0,(z=B.text)!=null?z:[]):n.insertBlock(a,x,B));const _=n.selection.range;let R=x;xa(n,v.type)?C?(n.insertBlock(a,x,v),R+=1):n.insertTextToBlock(e,t,(Q=v.text)!=null?Q:[]):(n.insertBlock(a,x,v),R+=1),h.slice(1,h.length-1).reverse().forEach(ee=>{n.insertBlock(a,R,ee)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function zg(n,e,t,o,r){const i=Ug(n,o,r),s=ce(e),l=[];return n.undoManager.runInGroup(()=>{const a=[];Object.entries(i.blocks).forEach(([h,p])=>{h!=="root"&&a.push({containerId:h,blocks:p})}),n.doc.localInsertChildContainers(a),i.blocks.root.reverse().forEach(h=>{const p=n.insertBlock(s,t,h,void 0,{noFocus:!0,noScroll:!0});l.push(p)})}),l}function Z6(n,e,t){const o=To(e);zg(n,e,o,t);for(let r=0;r<o;r++){const i=yt(e);n.deleteBlock(i)}}const za=S("add-text-attribute");function gT(n,e,t,o){const{start:r,end:i}=t;g(za,r.blockId===i.blockId&&r.blockId===ie(e),"invalid range"),g(za,o,"invalid attribute name");const s=n.getBlockText(e),l=Gl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function Q6(n,e,t,o,r){const{start:i,end:s}=t;g(za,i.blockId===s.blockId&&i.blockId===ie(e),"invalid range"),g(za,o,"invalid attribute name");const l=n.getBlockText(e),a=Oa(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function Kl(n,e,t,o,r){const{start:i,end:s}=t;g(za,i.blockId===s.blockId&&i.blockId===ie(e),"invalid range");const l=n.getBlockText(e),a=n6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function Y6(n,e,t,o){const r=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!ne(n,s))return;if(ut(n,s)){o(n,ie(s),e,t);return}const d=zt(n,{anchor:l,focus:a});e==="color"||e==="backgroundColor"?Kl(n,s,d,e,t):(Kl(n,s,d,"color",null),Kl(n,s,d,"backgroundColor",null))})})}function J6(n,e,t){const o=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!ne(n,i))return;if(ut(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,ie(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,ie(i),"backgroundColor",null);return}const a=zt(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Kl(n,i,a,"color",null),(e==="clearBackground"||e==="clearAll")&&Kl(n,i,a,"backgroundColor",null)})})}function K6(n,e,t){const o=e.getSelectedBlocks().filter(l=>ne(n,l.block));if(o.length===0)return[null,null];const r=l=>{if(ue(n,l.block)===0)return t(n,ie(l.block));const a=l.start,d=l.end,h=n.getBlockText(l.block);return i6(a.offset,d.offset-a.offset,h)};let[i,s]=r(o[0]);return i===null&&s===null?[i,s]:(o.forEach(l=>{const[a,d]=r(l);a===null||i===null?i=null:i=a===i?i:null,d===null||s===null?s=null:s=d===s?s:null}),[i,s])}const Wn=S("adjust-selection-pos");function X6(n){const e=[];for(;n;){const t=oe(n);if(e.unshift(t),Ge(t))return e;const o=te(t);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function eA(n,e){for(;e;){const t=oe(e);if(t===n)return e;const o=te(t);g(Wn,o,"could not find parent block for a child container"),e=o}g(Wn,!1,"no parent block in specified container")}function pT(n,e){const t=X6(n),o=X6(e);g(Wn,t.length>0&&o.length>0,"block has not parent container"),g(Wn,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=eA(r,n),s=eA(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function tA(n,e){let t=te(e);for(g(Wn,t,"element is not in a block");t;){const o=oe(t);g(Wn,Mo(o),"not a child container");const r=te(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;t=r}g(Wn,!1,"failed to find parent container in complex block")}function Nh(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof Ut&&t instanceof Ut?{anchor:e,focus:t}:e instanceof Ro&&t instanceof Ro?mh(n,o,e,t):null;const i=oe(o),s=oe(r);if(i===s)return e instanceof Ro&&(e=se(o,0,"home")),t instanceof Ro&&(t=se(r,ue(n,r),"end")),g(Wn,e instanceof Ut,"not valid position type"),g(Wn,t instanceof Ut,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof Ut&&t instanceof Ro){const B=n.getContainerById(t.childContainerId);if(B===i)return{anchor:t,focus:t};const D=te(i);if(D&&D===te(B)){const x=ft(D,ce(i)),_=ft(D,ce(B));return mh(n,D,x,_)}}return null}const l=Yd(o,r)>0,{newBlock1:a,newBlock2:d}=pT(o,r);if(a===d){const B=a,D=tA(B,o),x=tA(B,r);return e=ft(a,ce(D)),t=ft(a,ce(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),mh(n,B,e,t)}let h=l?ue(n,a):0;a===o&&e instanceof Ut&&(h=e.offset);let C=l?0:ue(n,d);return d===r&&t instanceof Ut&&(C=t.offset),e=se(a,h,l?"end":"home"),t=se(d,C,l?"home":"end"),{anchor:e,focus:t}}const CT=S("move-complex-block-position");function AT(n,e,t){const o=n.getBlockById(e.blockId);g(CT,Me(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?ft(o,ce(s)):null}const Va=S("move-simple-block-position");function nA(n,e){const t=gn(n,e,{visibleOnly:!0});g(Va,t.length>0,"complex block has not any child container");const o=t[0];return yt(o)}function oA(n,e){const t=gn(n,e,{visibleOnly:!0});g(Va,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Qt(o)}function rA(n,e,t){const o=t?nA(n,e):oA(n,e);return Me(n,o)?rA(n,o,t):o}function bT(n,e){const t=n.getBlockById(e.blockId);return Me(n,t)&&e.offset===0?nA(n,t):Ts(t)}function vT(n,e){const t=n.getBlockById(e.blockId);return Me(n,t)&&e.offset===1?oA(n,t):Is(t)}function Vg(n){return n==="ArrowLeft"||n==="ArrowUp"}function Wg(n,e,t){const o=oe(e);if(Ge(o))return null;const r=te(o);g(Va,r,"child container has not parent block"),g(Va,Me(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,t);return i?Vg(t)?Qt(i):yt(i):Wg(n,r,t)}function yT(n,e,t){const o=oe(e);if(Ge(o))return null;const r=te(o);if(g(Va,r,"child container has not parent block"),Vg(t)){const l=at(r);if(l)return l}else{const l=Qe(r);if(l)return l}const i=Wg(n,r,t);if(i)return i;let s=r;for(;!Ge(oe(s));)s=te(oe(s));return Vg(t)?at(s):Qe(s)}function kT(n,e,t){return!Me(n,e)||zn(n,e).enableKeyboardSelect?e:rA(n,e,t==="ArrowDown"||t==="ArrowRight")}function wT(n,e,t){const o=n.getBlockById(e.blockId),i=Ye(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?bT(n,e):vT(n,e);if(s||(s=Wg(n,o,t),s||(s=yT(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Ge(oe(o)))return null;const l=n.insertTextBlock("",ce(n.rootContainer),To(n.rootContainer));return se(l,0,"home")}return null}if(s=kT(n,s,t),ne(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return Qx(n,s,o,e,l);if(t==="ArrowUp")return Zx(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?se(s,ue(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?se(s,0,"home"):null}function BT(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if(ne(n,r))return o;const i=Qe(r);if(i)return se(i,0,"home");if(!Ge(oe(r))||n.readonly)return o;const s=n.insertTextBlock("",ce(n.rootContainer),To(n.rootContainer));return se(s,0,"home")}function ET(n,e,t){const o=n.selection.range;let r;if(o instanceof Yt)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=BT(n,e,o):r=wT(n,o.getFocusedPos(),e);else if(r=AT(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=Qt(s);r=se(l,0,"home")}else{const l=yt(s);r=se(l,ue(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:Nh(n,o.anchor,r):null}function $i(n,e,t){const o=ET(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 iA(n){return $i(n,"ArrowLeft","move"),!0}function sA(n){return $i(n,"ArrowRight","move"),!0}function lA(n){return $i(n,"ArrowUp","move"),!0}function cA(n){if($i(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=oe(e);if(Ge(t)||Qt(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",ce(o),To(o)),!0}function aA(n){return $i(n,"ArrowDown","select"),!0}function uA(n){return $i(n,"ArrowLeft","select"),!0}function dA(n){return $i(n,"ArrowRight","select"),!0}function hA(n){return $i(n,"ArrowUp","select"),!0}const fA=S("word-offset");function qg(n,e){const t=n.selection.range.focus;g(fA,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(ut(n,o))return se(o,0,"home");if(t.offset===0||!ne(n,o)){const s=at(o);if(!s)return null;const l=se(s,ue(n,s),"end");if(e==="select"&&ne(n,s)){const a=Bg(n,s,l.offset);return se(s,a,"normal")}return l}const r=Bg(n,o,t.offset);return se(o,r,"normal")}function Gg(n,e){const t=n.selection.range.focus;g(fA,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(ut(n,o))return se(o,0,"end");if(t.offset===ue(n,o)||!ne(n,o)){const s=Qe(o);if(!s)return null;const l=se(s,0,"home");if(e==="select"&&ne(n,s)){const a=Eg(n,s,l.offset);return se(s,a,"end")}return l}const r=Eg(n,o,t.offset);return se(o,r,"normal")}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const t=qg(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const t=Gg(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function pA(n){if(!n.selection.range.focus.isSimple())return!1;const t=qg(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function CA(n){if(!n.selection.range.focus.isSimple())return!1;const t=Gg(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Zg(n,e){if(!Me(n,e))return e;const o=zn(n,e).getChildContainers(n,e)[0],i=mt(o)[0];return Zg(n,i)}function Qg(n,e){if(!Me(n,e))return e;const t=zn(n,e).getChildContainers(n,e),o=t[t.length-1],r=mt(o),i=r[r.length-1];return Qg(n,i)}function Yg(n){const e=Qg(n,Qt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(t),!0}function AA(n){const e=Zg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(t),!0}function bA(n){const e=Zg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Jg(n){const e=Qg(n,Qt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const vA=S("line-offset");function yA(n){const e=n.selection.range.focus;g(vA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!ne(n,t))return se(t,0,"home");let r=U4(t,e).start;const{next:i}=uh(t,r);return i&&co(i)&&Ea(i)==="br"&&(r+=1),se(t,r,"home")}function kA(n){const e=n.selection.range.focus;g(vA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===ue(n,t)||!ne(n,t))return se(t,ue(n,t),"end");const o=U4(t,e);return se(t,o.end,"end")}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const t=yA(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const t=kA(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function EA(n){if(!n.selection.range.focus.isSimple())return!1;const t=yA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function xA(n){if(!n.selection.range.focus.isSimple())return!1;const t=kA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const IA=S("find-block-position");function xT(n,e,t,o){g(IA,Me(n,e),"is not a complex block");const r=zn(n,e).getChildContainers(n,e);g(IA,r.length>0,"complex block has not any child container");const i=Lo(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,a=L4(n,e,s,l);return Kg(n,a,t,o)}function Kg(n,e,t,o){if(Me(n,e))return xT(n,e,t,o);const r=ie(e);let i=Number.MAX_SAFE_INTEGER;const s=Lo(n,t,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=se(r,0,"home");const h=ue(n,e);for(let p=0;p<=h;p++){const C=se(r,p,"normal"),v=Lo(n,e,C),B=nr(v,l,a);B<i&&(i=B,d=C)}return d}const TA=S("page-offset");function IT(n,e){const t=I6(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<YI(n))return n.getFirstBlock();const i=at(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=at(s)}return n.getFirstBlock()}function TT(n,e){const t=I6(n)*.9,o=e.getBoundingClientRect(),r=JI(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=Qe(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Qe(l)}return n.getLastBlock()}function DA(n){const e=n.selection.range.focus;g(TA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=IT(n,t);let r;return o===n.getFirstBlock()?r=se(o,0,"home"):r=Kg(n,o,t,e),r}function SA(n){const e=n.selection.range.focus;g(TA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=TT(n,t);let r;return o===n.getLastBlock()?r=se(o,ue(n,o),"end"):r=Kg(n,o,t,e),r}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const t=DA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const t=SA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function RA(n){if(!n.selection.range.focus.isSimple())return!1;const t=DA(n);if(!t)return!1;const o=Nh(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 OA(n){if(!n.selection.range.focus.isSimple())return!1;const t=SA(n);if(!t)return!1;const o=Nh(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 Wa=S("select-all");function _A(n,e){const t=yt(n),o=Qt(n);return e.start.offset===0&&e.start.blockId===ie(t)&&e.end.offset===ue(e.getEditor(),o)&&e.end.blockId===ie(o)}function DT(n,e){const t=e.getEditor(),o=zn(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=ie(n);return e.start.blockId===s&&e.start.childContainerId===ce(r)&&e.end.blockId===s&&e.end.childContainerId===ce(i)}function ST(n,e){g(Wa,e,"no parent block"),g(Wa,Me(n,e),"not a complex block");const t=zn(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(zt(n,{anchor:ft(e,ce(o)),focus:ft(e,ce(r))}))}function FA(n,e){const t=oe(e);Xg(n,t)}function PA(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&ne(n,e)){const r=t.start,i=t.end,s=ue(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return W(n.rootContainer,"select-all"),FA(n,yt(n.rootContainer)),!1}return g(Wa,!t.isSimple(),"invalid range type"),DT(e,t)?(FA(n,e),!1):(g(Wa,e,"no parent block"),g(Wa,Me(n,e),"not a complex block"),ST(n,e),!0)}function Xg(n,e){const t=mt(e),o=t[0],r=t[t.length-1],i=se(o,0,"home"),s=se(r,ue(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function LT(n){Jg(n),n.focus()}const ep=S("selected-block-to-doc");function NA(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{NA(n,i,t)}),t.blocks[o]=me.default(r)})}function $h(n,e){const t=Ye(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=me.default(Pi(n,e.block));if(ne(n,e.block)){const i=e.start,s=e.end;if(g(ep,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Vt(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(It(e.block))return{blocks:{root:[o]},meta:{},comments:{}};g(ep,Me(n,e.block),"not complex block"),g(ep,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return NA(n,o,r),r}function tp(n,e){const t=se(e,0,"normal"),o=se(e,ue(n,e),"end");return $h(n,{block:e,start:t,end:o})}const MT=S("block-to-doc");function RT(n,e){g(MT,e.length>0,"invalid params, no blocks");const t=e.map(o=>tp(n,o));return Ps(t)}function Hh(n){const t=n.selection.range.getSelectedBlocks().map(o=>$h(n,o));return Ps(t)}function $A(n,e){const t=n.getContainerById(e),i=mt(t).map(s=>({start:se(s,0,"home"),end:se(s,ue(n,s),"end"),block:s})).map(s=>$h(n,s));return Ps(i)}const jh=S("editor-selection");class OT{constructor(e){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(S6(t,i)){jh.debug("adjust selection because remote deleted current block");const s=L6(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=ie(t);this.caret=new GI(e);const r=se(o,0,"normal");this._range=zt(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=se(e,t,"normal");let i;o&&(i=se(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=zt(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),xe(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!tT(this.editor,r))&&re(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(),ZI(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(!Wr(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=Lo(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){eT(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=ue(this.editor,t)||g(jh,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||g(jh,!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&&xe(t,"focused")&&(re(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=Hh(this.editor);return e==="text"?Na(this.editor,t):e==="markdown"?$a(this.editor,t):R6(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{re(e,"focused"),re(e,"child-focused")})}setBlockFocused(e){if(xe(e,"focused"))return!1;W(e,"focused");let t=oe(e);for(;Mo(t);){const o=te(t);g(jh,o,"parent block not found"),W(o,"child-focused"),t=oe(o)}return!0}}function _T(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,ue(n,t))}function FT(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!ne(n,t))return;let o=qg(n,"select"),r=Gg(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=se(t,0,"home")),r.blockId!==i&&(r=se(t,ue(n,t),"end")),n.selection.setSelection(o,r)}class PT{constructor(e){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(e,t)=>{var r;this.mouseDownEvent=e;const o=O4(this.editor,e.x,e.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&t.autoScroll){const s=o.getSelectedBlocks(),l=so(s[0].block);this.autoScroll=new rh({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(e.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),t.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(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=gh(this.editor,e.x,e.y);if(!t)return;const o=Nh(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",e=>{var t;(t=this.autoScroll)==null||t.inactive(),this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){FT(this.editor)}handleTripleClick(e){_T(this.editor)}}function NT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function $T(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const HA=S("delete-text");function jA(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof Ut||g(HA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(HA,ne(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!sn(s,l-t)){const a=_i(s,l);t=l-a}}else if(e==="forward"&&l+t>ue(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function UA(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const HT=S("handle-backspace");function np(n,e){if(!ut(n,e))return;const t=oe(e);To(t)!==1&&n.deleteBlock(e)}function jT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ne(n,o))if(t.offset===0){if(UA(n,o))return;const r=at(o);if(r){if(!n.isBlockWritable(r))return;if(ne(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Me(n,r)){np(n,o);const i=Wl(n,r);i?n.selection.selectBlock(i,ue(n,i)):n.selection.selectBlock(r,0,ue(n,r))}else np(n,o),g(HT,It(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=oe(o);if(Mo(i)){const s=T4(n,i);if(s){if(!n.isBlockWritable(s))return;np(n,o),n.selection.selectBlock(s,ue(n,s))}}}}else jA(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=be(o),i=oe(o);n.insertTextBlock("",ce(i),r),n.deleteBlock(o)}}function UT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ne(n,o))if(t.offset===ue(n,o)){const r=Qe(o);if(r){if(!n.isBlockWritable(r))return;ne(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ut(n,o)?n.deleteBlock(o,kt(n,r,0)):n.deleteBlock(r)}}else jA(n,"forward",1,null);else{const r=be(o),i=oe(o);n.insertTextBlock("",ce(i),r),n.deleteBlock(o)}}function zT(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Me(n,r))return!1;if(Wr(t))return!0;const s=Vl(n,r,t,o),l=gn(n,r);return s.length===l.length}function VT(n,e){if(zT(n)){const s=n.getFocusedBlock(),l=be(s),a=ce(oe(s));n.insertTextBlock("",a,l+1);return}const t=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&It(t);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),ne(n,t)){if(ut(n,t)&&UA(n,t))return;const s=n.selection.range.start,l=n.breakTextBlock(t,s.offset,{copyBlockAttributes:!0});s.offset!==0?n.selection.selectBlock(l,0):n.selection.scrollIntoView()}else{const s=n.insertTextBlock();n.selection.selectBlock(s,0)}}function WT(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!ne(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const qT=S("input-handler-actions");function GT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(VT(n),!0))}function ZT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(UT(n),!0))}function QT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(jT(n),!0))}function YT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(WT(n),!0))}function JT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e,{toPlainText:!0})}).catch(e=>{qT.error(e)}),!0)}const Uh={ArrowDown:cA,ArrowUp:lA,ArrowLeft:iA,ArrowRight:sA,"Shift+ArrowDown":aA,"Shift+ArrowUp":hA,"Shift+ArrowLeft":uA,"Shift+ArrowRight":dA,"CtrlOrCmd+ArrowLeft":mA,"CtrlOrCmd+ArrowRight":gA,"CtrlOrCmd+Shift+ArrowLeft":pA,"CtrlOrCmd+Shift+ArrowRight":CA,"CtrlOrCmd+ArrowUp":AA,"CtrlOrCmd+ArrowDown":Yg,"CtrlOrCmd+Shift+ArrowUp":bA,"CtrlOrCmd+Shift+ArrowDown":Jg,"CtrlOrCmd+A":PA,Home:EA,End:xA,"Shift+Home":wA,"Shift+End":BA,PageUp:LA,PageDown:MA,"Shift+PageUp":RA,"Shift+PageDown":OA,"CtrlOrCmd+Z":NT,"CtrlOrCmd+Shift+Z":$T,Enter:GT,Delete:ZT,Backspace:QT,"Shift+Enter":YT,"CtrlOrCmd+Shift+V":JT};function zA(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function VA(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);if(l)i.src=l;else{let a="";s.split("|").forEach(h=>{const p=t.get(h);p&&(a+=a?`|${p}`:`${p}`)}),a&&(i.src=a)}}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=>{VA(n,l,t)})})}function WA(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):VA(e,r,t)})}async function KT(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 XT(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 eD(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(XT(n,e)){const s=Array.from(Object.keys(o));r=await KT(n,s),WA(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&&WA(n,e,i)}async function tD(n,e,t){await eD(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&It(i)){const s=oe(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,e,t);a&&n.selection.selectBlock(a,ue(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=Zl(n);n.insertDoc(s,l,e,t)}})}const nD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function oD(n){let e;for(const t of nD)if(e=n[t],e)break;return e||null}function qA(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=>{qA(n,l,t)})})}function rD(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)}):qA(e,r,t)}),Array.from(t)}function zh(n,e){return Zt.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Mi(JSON.stringify(e))}" id="ones-editor-doc">${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Mi(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Vh(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=rD(n,e),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),e.meta={...t,resources:r}}function iD(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=Hh(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Vh(n,o);const i=Lh(n,o),s=$a(n,o),l=zh(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 Wh(n,e){const t=tp(n,e);Vh(n,t);const o=Lh(n,t),r=$a(n,t),i=zh(o,t);return Pm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class sD{constructor(e){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(e,t)=>{const o=new DataTransfer;o.setData("text/plain",e);const r=await this.editor.dataConverter.fromData(this.editor,o,t);r&&this.pasteDocs(r,null)});this.editor=e}onInsertText(e,t){if(!ne(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Zl(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}=Zl(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}=Zl(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(e){iD(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;It(o)&&this.editor.deleteBlock(o)}else $g(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(){W(this.editor.rootElement,"active")}onBlur(){re(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e),this.handlers=this.handlers.sort((t,o)=>{var s,l;const r=(s=t.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}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){Og(this.editor,i)}defaultHandleKeydown(e,t){return zA(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 tD(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=oD(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 lD(n,e,t){const o=Hr(e,t);return o.remove(),o}S("copy-dom-attributes");const GA=["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 cD(n,e){for(let l=0;l<GA.length;l++){const a=GA[l];e[a]=n[a]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const a=t[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];t.getNamedItem(a.name)||s.push(a)}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 ZA(n){const e=Array.from(n.childNodes).filter(t=>!V5(t));return e.forEach(t=>{t.remove()}),e}function QA(n,e,t){var d;const o=n.getContainerById(e),r=Hr(o,t),i=Ri(r),s=n.doc.getBlockData(e,t),l=Ye(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=ZA(h);ZA(r),p.forEach(v=>{r.appendChild(v)});const C=ch(h);if(C){const v=ch(r);v&&v.remove(),r.appendChild(C)}cD(h,r)}c4(n,r,s),n.blockHooks.forEach(h=>{var p;(p=h.update)==null||p.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const aD=S("transform-selection");function YA(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;g(aD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const d=ln.transformCursor(i.offset,t,o);l=se(e,d,"normal")}let a=s;if(s.blockId===e){const d=ln.transformCursor(s.offset,t,o);a=se(e,d,"normal")}return zt(n,{anchor:l,focus:a})}const uD=S("handle-block-text-changed");function dD(n,e,t,o,r){const i=n.getContainerById(e),s=Hr(i,t),l=n.doc.getBlockData(e,t);if(g(uD,l.text,"no block text"),n4(n,s).setBlockText(n,s,l.text),!r){const a=YA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function hD(n,e){const t=me.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function JA(n,e,t,o){const r=Ye(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function fD(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{JA(n,i,o,{child:!0})}),JA(n,r,o,{child:!1})}const _o=S("editor-doc");class mD extends pa{constructor(t,o,r){super();m(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);g(_o,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;g(_o,l,`no text, ${t}, ${o}`);const a=YA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(t,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(t,o,r,i){g(_o,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(C=>C!=="comments"),p=Object.keys(r.insert).filter(C=>C!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=me.default(this.getBlockData(t,o)),a=me.default(hD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(t,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(Oi(this.editor,i)),d}localInsertBlock(t,o,r,i,s){g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(t,o,r){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=me.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(Oi(this.editor,r)),s}localDeleteChildContainers(t){return g(_o,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=me.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainers(t){g(_o,!this.editor.readonly,"editor is readonly");const o=me.default(t);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(t){_o.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)}),dD(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)}),QA(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);ex(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){fD(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);lD(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){_o.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function KA(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 qh=S("undo-action");class Xl{constructor(e,t,o){m(this,"beforeRange");m(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 g(qh,e,"no other action"),!1}combine(e){g(qh,!1,"no other")}setAfterRange(e){this.afterRange&&qh.warn("after range has already set"),this.afterRange=e}findContainerById(e,t){return e.doc.toJSON().blocks[t]!==void 0}findBlockById(e,t){return e.doc.getContainerBlocks(this.containerId).some(r=>r.id===t)}checkBlockData(e,t){if(Array.isArray(t.children)){const o=e.doc.toJSON();for(let r=0;r<t.children.length;r++){const i=t.children[r];if(!o.blocks[i])return qh.warn(`container (${i}) not found, deleted by others?`),!1}}return!0}}const ec=S("block-action");class XA extends Xl{constructor(t,o,r,i,s){super(t,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=me.default(i),this.blockIndex=r}deleteBlock(t,o){if(!this.findContainerById(t,this.containerId))return ec.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(t,this.blockData.id))return ec.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);if(!i)return!1;try{g(ec,this.blockIndex===be(i),"invalid block index"),Oh(t,i,Oi(t,o))}catch(s){ec.warn(s.message),t.selection.selectBlock(i,0)}return!0}insertBlock(t,o){if(!this.findContainerById(t,this.containerId))return ec.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(t,this.blockData))return!1;try{Yl(t,this.containerId,this.blockIndex,me.default(this.blockData),o)}catch(r){ec.warn(r.message);const i=t.doc.getContainerBlocks(this.containerId),s=Math.min(i.length-1,this.blockIndex),l=t.getBlockByIndex(this.containerId,s);t.selection.selectBlock(l,0)}return!0}}S("insert-block-action");class gD extends XA{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class pD extends XA{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class CD extends Xl{constructor(t){super(t,ce(t.rootContainer),t.selection.range.toDocRange());m(this,"actions",[])}addAction(t){KA(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 Xl&&(o.afterRange||o.setAfterRange(t))}}const Hi=S("update-block-data-action");class Gh extends Xl{constructor(t,o,r,i,s,l){super(t,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hi,this.blockId===i.id,"invalid block id"),g(Hi,this.blockId===s.id,"invalid block id"),this.beforeBlockData=me.default(i),this.afterBlockData=me.default(s),g(Hi,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){if(!t.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=t.getBlockById(this.blockId);if(!o||!this.checkBlockData(t,this.beforeBlockData))return!1;const r=t.getContainerById(this.containerId);return g(Hi,r,"no container"),Ph(t,o,Gh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){if(!t.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g(Hi,t,"no editor");const o=t.getBlockById(this.blockId);if(!o||!this.checkBlockData(t,this.beforeBlockData))return!1;const r=t.getContainerById(this.containerId);return g(Hi,r,"no container"),Ph(t,o,Gh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=me.default(t);return delete o.id,delete o.type,o}}const Ns=S("update-block-text-action");class qa extends Xl{constructor(t,o,r,i,s,l){super(t,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=me.default(i),this.afterRichTextData=me.default(s),this.type=qa.calType(i,s)}static calType(t,o){g(Ns,t,"no old data"),g(Ns,o,"no new data");const i=ln.diff(t,o),s=new Set;let l=!1;const a=h=>v5(h)?`cjk_${h}`:A5(h)?"number":Xd(h)?"space":b5(h)?"letter":"unknown";let d=!1;return i.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(t){if(!this.findBlockById(t,this.blockId))return Ns.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!this.findContainerById(t,this.containerId))return Ns.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(Fh(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!this.findBlockById(t,this.blockId))return Ns.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!this.findContainerById(t,this.containerId))return Ns.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(Fh(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof qa)||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){g(Ns,t instanceof qa,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}const eb=S("child-container-action");class tb extends Xl{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return this.findContainerById(e,this.containerId)?(e.doc.localDeleteChildContainers([this.containerId]),!0):(eb.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(e){return this.findContainerById(e,this.containerId)?(eb.warn(`container (${this.containerId}) already exists`),!1):(e.doc.localInsertChildContainers([{containerId:this.containerId,blocks:me.default(this.blocks)}]),!0)}}class AD extends tb{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class bD extends tb{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const Fo=S("undo");class vD{constructor(e){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(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):(KA(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new CD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.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 Fo.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(Oi(this.editor,e.beforeRange))}catch(t){Fo.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(Oi(this.editor,t)):Fo.warn("no after range")}catch(t){Fo.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(),ln.diff(o,r).length!==0&&this.addAction(new qa(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Gh(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,t>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new gD(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new pD(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new AD(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,e,t)))}}class yD{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 kD{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new yD)}prepareData(e){const t=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)t.setData(this.converterTypes[o],e.getData(this.converterTypes[o]));return t}async fromData(e,t,o){let r={};const i=this.prepareData(t);for(const s of this.converters){const l=await s.fromData(e,i,o);l&&(r={...r,...l})}return r}addConverter(e){this.converters.push(e)}}class wD{constructor(e){m(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 Ct extends vt.TypedEmitter{constructor(t){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(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=te(o);if((!r||!et(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?ie(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&&et(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&re(s,"hover"),t&&W(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 Ct(t))}getParentTextContentChild(t,o){if(!ne(this.editor,t))return null;const r=Le(t);return o.parentElement===r?o:Vm(o)}}const nb="style-color-",ob="style-bg-color-";class BD{renderText(e,t,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(nb)?i["data-style-color"]=l.substring(nb.length):l.startsWith(ob)?i["data-style-bg-color"]=l.substring(ob.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(e,t,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=e.selection)==null?void 0:l.range)==null?void 0:a.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"),Ct.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(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ct.get(e).hoveringBlockId()===r.id&&W(o,"hover")}}function ED(n){n.editorBlocks.registerBlockClass(Dn),n.editorBlocks.registerBlockClass(I4),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(C6),n.editorBoxes.registerBoxClass(v6),n.editorBoxes.registerBoxClass(y6),n.editorInsertions.registerInsertionClass(k6),n.editorBlockRenders.registerRender(new BD)}function xD(n,e){ED(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 Zh=S("range-commands");function rb(n,e){n.forEach(t=>{t.source=e,t.children&&rb(t.children,e)})}function ib(n,e,t){const o=ie(e);g(Zh,o===t.start.blockId,"invalid start range"),g(Zh,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];if(r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);rb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),Me(n,e)){g(Zh,!t.start.isSimple(),"invalid start pos"),g(Zh,!t.end.isSimple(),"invalid end pos");const s=t.start.childContainerId,l=ir(n,s),d=mt(l)[0];if(d){const h=ue(n,d),p=zt(n,{anchor:se(d,0,"home"),focus:se(d,h,"end")}),C=ib(n,d,p);i.push(...C)}}return i}function sb(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[],r=n.isReverse()?t[0]:t[t.length-1],i=zt(e,{anchor:r.start,focus:r.end});return ib(e,r.block,i).forEach(l=>{o.push(l)}),o}function lb(n,e,t,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const C=s[p];if(C.beforeExecuteCommand&&C.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,e,t,o,r,{}))return i[ie(e)]=a,!0;let d=!1;return Me(n,e)&&Vl(n,e,t.start,t.end).forEach(C=>{mt(C).forEach(B=>{const D=ue(n,B),x=zt(n,{anchor:se(B,0,"home"),focus:se(B,D,"end")});lb(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,e,t,o,r,i)}),d}function cb(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 a=zt(o,{anchor:l.start,focus:l.end});lb(o,l.block,a,e,t,r)}),o.focus()),r}const ID=S("command-providers");class ab{constructor(e){m(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 g(ID,t,`no command provider, id=${e}`),t}getCommands(e){return sb(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>cb(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 TD(n,e){const t=oe(e),o=ce(t),r=be(e);QA(n,o,r)}const DD=S("table-scroll");class ub{constructor(e,t,o,r,i){m(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 SD{constructor(e){m(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)){DD.warn(`event has already registered: ${t}`);return}i.push(new ub(this.editor,e,t,o,r))}else{const s=new ub(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 a=s[l];if(t)t===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.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 db=S("update-block-text");function LD(n,e){const t=n.getBoxById(e.id),o=te(t);g(db,o,"no parent block"),g(db,ne(n,o),"not a text block");const r=n.getBlockText(o),i=l6(r,"id",e.id,e);V6(n,o,i)}function MD(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 RD(n){if(n.readonly)return!1;const e=lr(n);return!!n.isBlockWritable(e.map(t=>t.block))}class OD{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 _D{constructor(){m(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(or(t,s)){const a=l(e,t);if(a!==void 0)return a}}}}const Yr=S("editor");class FD extends vt.TypedEmitter{constructor(t,o,r){var i,s,l,a,d,h,p,C;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new _D);m(this,"dataConverter",new kD);m(this,"editorBlocks",new w4(this));m(this,"editorBoxes",new b6(this));m(this,"editorInsertions",new B6(this));m(this,"editorEmbeds",new E4(this));m(this,"editorDecorators",new E6(this));m(this,"editorCommandProviders",new ab(this));m(this,"editorBlockRenders",new wD(this));m(this,"blockHooks",[]);m(this,"domEvents",new SD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new sD(this));m(this,"settingsProvider");m(this,"_readonly",!1);m(this,"getColor",t=>{const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]});Yr.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,enableComments:(a=r==null?void 0:r.enableComments)!=null?a:!0},this.settingsProvider=(d=r==null?void 0:r.settingsProvider)!=null?d:new OD(this),xD(this,r==null?void 0:r.components),this.blockHooks.push(...(p=(h=r==null?void 0:r.components)==null?void 0:h.blockHooks)!=null?p:[]),this.id=(C=r==null?void 0:r.id)!=null?C:K(),this.clientId=K(),this.undoManager=new vD(this),this.doc=new mD(this,o,this.undoManager),this.parent=t,this.rootElement=k("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=k("div",["editor-content"],this.rootElement),this.rootContainerObject=v4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new qI(this,this.inputHandlers),this.selection=new OT(this),this.selectionHandler=new PT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Zt.isMobile&&W(this.rootElement,"mobile"),Zt.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?W(this.rootElement,"readonly"):re(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:so(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 g(Yr,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(){Yr.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(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(t,o){Hg(this,t,o)}isWritable(){return RD(this)}isBlockWritable(t){return MD(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return(!o||!Array.isArray(o))&&(g(Yr,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),g(Yr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(t,o,r){return y4(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&&g(Yr,Bs(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&g(Yr,zm(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return g(Yr,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return g(Yr,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Hr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return be(o)}return be(t)}getContainerById(t){return ir(this,t)}getParentContainer(t){return oe(t)}reloadBlock(t){TD(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},a={anchor:l,focus:l};return Yl(this,t,o,r,i!=null?i:a,s)}insertEmbed(t,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Pg(this,t,o)}mergeTextBlock(t,o){return j6(this,t,o)}breakTextBlock(t,o,r){return Jl(this,t,o,r).newBlock}getTextPosition(){return Zl(this)}getBlockString(t,o){const r=this.getBlockText(t);return it(r,o)}getBlockData(t){return Pi(this,t)}getBoxData(t){return m6(this,t)}getBlockText(t){return pn(this,t)}setBlockText(t,o){V6(this,t,o)}deleteTextFromBlock(t,o,r,i){return _g(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return O6(this,t,o,r,i)}insertBoxToBlock(t,o,r){return _6(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){G6(this,t,o,r,i)}insertDocAt(t,o,r,i){return zg(this,t,o,r,i)}deleteChildContainers(t){H6(this,t)}replaceBlockText(t,o){return Fh(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...a}=i;return Ph(this,t,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return W6(this,t,o,r)}updateBoxData(t){LD(this,t)}getSelectedText(){const t=Hh(this);return Na(this,t)}clearSelectedContents(){$g(this)}insertTextBlock(t,o,r,i){const s=ur(t!=null?t:"");return $6(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){P6(this);return}o?(this.compositingText="",jl()||Og(this,t)):(this.compositingText=t,F6(this))}}function Ga(n,e,t){return new FD(n,e,t)}function PD(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=ym.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const ND=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Qh extends vt.TypedEmitter{constructor(t){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=t&&t.length>0?t:ND}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&fa.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.emit("change",Array.from(this.users.values()));const o=this.cursors.get(t);if(o){const r=new Set(new Set([o==null?void 0:o.range.anchor.blockId,o==null?void 0:o.range.focus.blockId]));this.cursors.delete(t),this.emit("remote-carets-change",[...r])}}updateUsers(t){this.users.forEach(o=>{t.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),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&&Eh(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(Eh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===t.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===t.id&&(d.offset=ln.transformCursor(d.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 Xt=S("local-doc");class op extends pa{constructor(t,o){super();m(this,"doc");m(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[ur("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return me.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);g(Xt,r,`no container data: ${t}`);const i=r[o];return g(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);g(Xt,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.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}),g(Xt,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 g(Xt,i,`no container data: ${t}`),g(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xt,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);g(Xt,r,`no container data: ${t}`),g(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xt,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}localInsertChildContainers(t){t.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,o,r,!0)})})}localDeleteChildContainers(t){Xt.debug(`delete child containers: ${t}`),t.forEach(o=>{g(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{g(Xt,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){g(Xt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){g(Xt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Qh}setDoc(t){this.doc=me.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class $D{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function rp(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new $D(o)})}const hb=S("find-block");function fb(n,e){const t=Is(e);if(!t){if(lo(e))return null;const o=Es(e);return g(hb,o,"no parent block"),fb(n,o)}return Me(n,t)?Wl(n,t,{visibleOnly:!0}):t}function mb(n,e){const t=Ts(e);if(!t){if(lo(e))return null;const o=Es(e);return g(hb,o,"no parent block"),mb(n,o)}return Me(n,t)?rg(n,t,{visibleOnly:!0}):t}const HD=S("remote-cursor");class jD{constructor(){m(this,"remoteUsers",new Qh)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):HD.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 UD(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function zD(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function Za(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=UD(me.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function ji(n){return n==="root"?"blocks":n}function tc(n){return n==="blocks"?"root":n}const VD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},compose(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},diff(n,e){const t=new on.default(n),o=new on.default(e);return t.diff(o).ops},transform(n,e,t){const o=new on.default(n);return new on.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 on.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 hr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ui={},ip=J3.default.EventEmitter;Ui.EventEmitter=ip,Ui.mixin=WD;function WD(n){for(var e in ip.prototype)n.prototype[e]=ip.prototype[e]}var gb=["info","warn","error"];function pb(){var n={};gb.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var qD=pb;pb.prototype.setMethods=function(n){n=n||{};var e=this;gb.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var GD=qD,ZD=new GD,Cb=ZD;function $s(n,e){this.code=n,this.message=e||"",Error.captureStackTrace?Error.captureStackTrace(this,$s):this.stack=new Error().stack}$s.prototype=Object.create(Error.prototype),$s.prototype.constructor=$s,$s.prototype.name="ShareDBError",$s.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 Yh=$s,Qa={},Ab=QD;function QD(n,e,t,o){var r=function(s,l,a,d){e(a,s,l,"left"),e(d,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],C=0;C<s.length;){var v=[];if(r(s[C],h,p,v),C++,v.length===1)h=v[0];else if(v.length===0){for(var B=C;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(C),v),x=0;x<D[0].length;x++)o(p,D[0][x]);for(var _=0;_<D[1].length;_++)o(a,D[1][_]);h=null;break}}h!=null&&o(a,h),s=p}return[s,a]};n.transform=function(s,l,a){if(!(a==="left"||a==="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],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var bb={exports:{}},zi=bb.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||""}},sp=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},lp=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")},Jh=function(n){for(var e=0;e<n.length;e++)lp(n[e])};zi.apply=function(n,e){var t;Jh(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=sp(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 Jr=zi._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:sp(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:sp(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};zi.compose=function(n,e){Jh(n),Jh(e);for(var t=n.slice(),o=0;o<e.length;o++)Jr(t,e[o]);return t},zi.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),Jr(e,o)}return e};var cp=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};zi.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=cp(n,e[r],o);return n};var YD=zi._tc=function(n,e,t,o){if(lp(e),lp(t),e.i!=null)Jr(n,{i:e.i,p:cp(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(Jr(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&Jr(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)Jr(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)Jr(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),a=e.d.slice(s-e.p,l-e.p),d=t.d.slice(s-t.p,l-t.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=cp(i.p,t),Jr(n,i))}return n},JD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};zi.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=JD(n[e]);return n},Ab(zi,YD,Jh,Jr);var Kh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},KD=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},Ie={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Kr={};Ie.registerSubtype=function(n){Kr[n.name]=n},Ie.create=function(n){return n===void 0?null:Po(n)},Ie.invertComponent=function(n){var e={p:n.p};return n.t&&Kr[n.t]&&(e.t=n.t,e.o=Kr[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},Ie.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(Ie.invertComponent(e[o]));return t},Ie.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!Kh(n[e].p))throw new Error("Missing path")},Ie.checkList=function(n){if(!Kh(n))throw new Error("Referenced element not a list")},Ie.checkObj=function(n){if(!KD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ya(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 Ja(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}Ie.apply=function(n,e){Ie.checkValidOp(e),e=Po(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&Ya(r);for(var i=null,s=t,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Kr[r.t])s[l]=Kr[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)Ie.checkList(s),s[l]=r.li;else if(r.li!==void 0)Ie.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)Ie.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(Ie.checkList(s),r.lm!=l){var h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}else if(r.oi!==void 0)Ie.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)Ie.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},Ie.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},Ie.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=Ie.apply(n,r),t(r,n)}return n};var XD=Ie.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};Ie.append=function(n,e){if(e=Po(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)&&(Ya(e),Ya(t)),XD(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Kr[e.t]){if(t.o=Kr[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(),Ja(e),n.push(e);Ja(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)&&(Ja(e),Ja(t)),n.push(e)},Ie.compose=function(n,e){Ie.checkValidOp(n),Ie.checkValidOp(e);for(var t=Po(n),o=0;o<e.length;o++)Ie.append(t,e[o]);return t},Ie.normalize=function(n){var e=[];n=Kh(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),Ie.append(e,o)}return e},Ie.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},Ie.canOpAffectPath=function(n,e){return Ie.commonLengthForOps({p:e},n)!=null},Ie.transformComponent=function(n,e,t,o){e=Po(e);var r=Ie.commonLengthForOps(t,e),i=Ie.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 a=Po(t);a.p=a.p.slice(s),e.ld=Ie.apply(Po(e.ld),[a])}else if(e.od!==void 0){var a=Po(t);a.p=a.p.slice(s),e.od=Ie.apply(Po(e.od),[a])}}if(r!=null){var d=s==l,a=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(Ya(e),a=Po(t),Ya(a)),a.t&&Kr[a.t]){if(e.t&&e.t===a.t){var h=Kr[e.t].transform(e.o,a.o,o);if(e.si!=null||e.sd!=null)for(var p=e.p,C=0;C<h.length;C++)e.o=[h[C]],e.p=p.slice(),Ja(e),Ie.append(n,e);else(!Kh(h)||h.length>0)&&(e.o=h,Ie.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(d){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=Po(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&d&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&d&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&d){if(t.p[r]===e.p[r])return n;var p=t.p[r],v=e.p[r],B=e.lm;(p<B||p===B&&v<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 v=e.p[r],B=e.lm,D=t.p[r],x=t.lm;if(D!==x)if(v===D)if(o==="left")e.p[r]=x,v===B&&(e.lm=x);else return n;else v>D&&e.p[r]--,v>x?e.p[r]++:v===x&&D>x&&(e.p[r]++,v===B&&e.lm++),(B>D||B===D&&B>v)&&e.lm--,B>x?e.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&e.lm++:B>v?e.lm++:B===D&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&d){var v=t.p[r],B=t.lm;p=e.p[r],p>v&&e.p[r]--,p>B&&e.p[r]++}else{var v=t.p[r],B=t.lm;p=e.p[r],p===v?e.p[r]=B:(p>v&&e.p[r]--,(p>B||p===B&&v>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&&d){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")Ie.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!d)return n;if(e.oi!==void 0)delete e.od;else return n}}}return Ie.append(n,e),n},Ab(Ie,Ie.transformComponent,Ie.checkValidOp,Ie.append);var eS=bb.exports;Ie.registerSubtype(eS);var tS=Ie,nS={type:tS};(function(n){n.defaultType=nS.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)})(Qa);var No={};(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))}})(No);var vb=Array.isArray,yb=Object.keys,oS=Object.prototype.hasOwnProperty,rS=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=vb(e),r=vb(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 a=e instanceof Date,d=t instanceof Date;if(a!=d)return!1;if(a&&d)return e.getTime()==t.getTime();var h=e instanceof RegExp,p=t instanceof RegExp;if(h!=p)return!1;if(h&&p)return e.toString()==t.toString();var C=yb(e);if(s=C.length,s!==yb(t).length)return!1;for(i=s;i--!==0;)if(!oS.call(t,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},kb=Ui,iS=Cb,qn=Yh,Xh=Qa,$o=No,sS=$o.clone,lS=rS,Sn=qn.CODES,cS=Fe;function Fe(n,e,t){kb.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}kb.mixin(Fe),Fe.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())})},Fe.prototype._setType=function(n){if(typeof n=="string"&&(n=Xh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new qn(Sn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},Fe.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Fe.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new qn(Sn.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 qn(Sn.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?Xh.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()},Fe.prototype.whenNothingPending=function(n){var e=this;$o.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},Fe.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Fe.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Fe.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Fe.prototype._emitResponseError=function(n,e){if(n&&n.code===Sn.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)},Fe.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){$o.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},Fe.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){$o.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()},Fe.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Sn.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=ef(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=ef(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},Fe.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))},Fe.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()},Fe.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);aS(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},Fe.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},Fe.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},Fe.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=uS([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},Fe.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;$o.nextTick(function(){n._handleSubscribe()})}}};function aS(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function uS(n){return n=n.filter($o.truthy),n.length?function(e){$o.callEach(n,e)}:null}Fe.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function dS(n){delete n.op,delete n.create,delete n.del}function ef(n,e){if(n.del)return dS(e);if(e.del)return new qn(Sn.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new qn(Sn.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}}}Fe.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new qn(Sn.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===Xh.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=ef(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 a=this.data;this._setType(null),this.emit("del",a,e);return}},Fe.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 qn(Sn.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>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Sn.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)}},Fe.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new qn(Sn.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;$o.nextTick(function(){r.flush()})},Fe.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)},Fe.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)}}},Fe.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!lS(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}}},Fe.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)},Fe.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=Xh.defaultType.uri),this.type){var r=new qn(Sn.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)},Fe.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new qn(Sn.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)},Fe.prototype.pause=function(){this.paused=!0},Fe.prototype.resume=function(){this.paused=!1,this.flush()},Fe.prototype.toSnapshot=function(){return{v:this.version,data:sS(this.data),type:this.type.uri}},Fe.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return iS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Fe.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=ef(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)},Fe.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=$o.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},Fe.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=$o.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)return this.emit("error",n)};var Hs={};Hs.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 wb=Ui,Bb=Hs.ACTIONS,hS=No,fS=Ln;function Ln(n,e,t,o,r,i,s){wb.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}wb.mixin(Ln),Ln.prototype.hasPending=function(){return!this.ready},Ln.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}},Ln.prototype.destroy=function(n){this.connection.canSend&&this.action===Bb.querySubscribe&&this.connection.send({a:Bb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&hS.nextTick(n)},Ln.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ln.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Ln.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Ln.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(h){if(h)return r._finishResponse(h,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 a=e[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Ln.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},Ln.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)},Ln.prototype._handleError=function(n){this.emit("error",n)},Ln.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)},Ln.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var Eb=Ui,mS=Hs.ACTIONS,gS=No,xb=fr;function fr(n,e){if(Eb.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={}}Eb.mixin(fr),fr.prototype.submit=function(n,e){this.value=n,this.send(e)},fr.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},fr.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()})},fr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},fr.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},fr.prototype._message=function(){return{a:mS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},fr.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},fr.prototype._callbackOrEmit=function(n,e){if(e)return gS.nextTick(e,n);n&&this.emit("error",n)};var pS=No,Ib=ap;function ap(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}ap.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},ap.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&pS.nextTick(n)};var up={exports:{}};(function(n,e){(function(t,o){o(e)})(hr,function(t){function o(w,T){T=T|0;for(var M=Math.max(w.length-T,0),F=Array(M),U=0;U<M;U++)F[U]=w[T+U];return F}var r=function(w){var T=o(arguments,1);return function(){var M=o(arguments);return w.apply(null,T.concat(M))}},i=function(w){return function(){var T=o(arguments),M=T.pop();w.call(this,T,M)}};function s(w){var T=typeof w;return w!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(w){setTimeout(w,0)}function h(w){return function(T){var M=o(arguments,1);w(function(){T.apply(null,M)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var C=h(p);function v(w){return i(function(T,M){var F;try{F=w.apply(this,T)}catch(U){return M(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(M,null,U)},function(U){B(M,U.message?U:new Error(U))}):M(null,F)})}function B(w,T,M){try{w(T,M)}catch(F){C(D,F)}}function D(w){throw w}var x=typeof Symbol=="function";function _(w){return x&&w[Symbol.toStringTag]==="AsyncFunction"}function R(w){return _(w)?v(w):w}function H(w){return function(T){var M=o(arguments,1),F=i(function(U,j){var G=this;return w(T,function(J,le){R(J).apply(G,U.concat(le))},j)});return M.length?F.apply(this,M):F}}var z=typeof hr=="object"&&hr&&hr.Object===Object&&hr,Q=typeof self=="object"&&self&&self.Object===Object&&self,ee=z||Q||Function("return this")(),fe=ee.Symbol,ve=Object.prototype,ze=ve.hasOwnProperty,He=ve.toString,Ke=fe?fe.toStringTag:void 0;function qt(w){var T=ze.call(w,Ke),M=w[Ke];try{w[Ke]=void 0;var F=!0}catch{}var U=He.call(w);return F&&(T?w[Ke]=M:delete w[Ke]),U}var Yn=Object.prototype,Ht=Yn.toString;function Rn(w){return Ht.call(w)}var Ir="[object Null]",kn="[object Undefined]",an=fe?fe.toStringTag:void 0;function Tr(w){return w==null?w===void 0?kn:Ir:an&&an in Object(w)?qt(w):Rn(w)}var ii="[object AsyncFunction]",Ao="[object Function]",oC="[object GeneratorFunction]",rC="[object Proxy]";function iC(w){if(!s(w))return!1;var T=Tr(w);return T==Ao||T==oC||T==ii||T==rC}var ns=9007199254740991;function nl(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=ns}function ol(w){return w!=null&&nl(w.length)&&!iC(w)}var si={};function Ne(){}function Dr(w){return function(){if(w!==null){var T=w;w=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Hc=function(w){return os&&w[os]&&w[os]()};function m1(w,T){for(var M=-1,F=Array(w);++M<w;)F[M]=T(M);return F}function un(w){return w!=null&&typeof w=="object"}var rl="[object Arguments]";function g1(w){return un(w)&&Tr(w)==rl}var bo=Object.prototype,p1=bo.hasOwnProperty,sC=bo.propertyIsEnumerable,il=g1(function(){return arguments}())?g1:function(w){return un(w)&&p1.call(w,"callee")&&!sC.call(w,"callee")},At=Array.isArray;function sl(){return!1}var ll=typeof t=="object"&&t&&!t.nodeType&&t,C1=ll&&!0&&n&&!n.nodeType&&n,cl=C1&&C1.exports===ll,A1=cl?ee.Buffer:void 0,al=A1?A1.isBuffer:void 0,rs=al||sl,Yu=9007199254740991,Ju=/^(?:0|[1-9]\d*)$/;function Ku(w,T){var M=typeof w;return T=T==null?Yu:T,!!T&&(M=="number"||M!="symbol"&&Ju.test(w))&&w>-1&&w%1==0&&w<T}var Xu="[object Arguments]",ed="[object Array]",td="[object Boolean]",nd="[object Date]",od="[object Error]",rd="[object Function]",lC="[object Map]",cC="[object Number]",aC="[object Object]",b1="[object RegExp]",v1="[object Set]",uC="[object String]",dC="[object WeakMap]",hC="[object ArrayBuffer]",fC="[object DataView]",y1="[object Float32Array]",mC="[object Float64Array]",gC="[object Int8Array]",pC="[object Int16Array]",id="[object Int32Array]",CC="[object Uint8Array]",sd="[object Uint8ClampedArray]",AC="[object Uint16Array]",bC="[object Uint32Array]",lt={};lt[y1]=lt[mC]=lt[gC]=lt[pC]=lt[id]=lt[CC]=lt[sd]=lt[AC]=lt[bC]=!0,lt[Xu]=lt[ed]=lt[hC]=lt[td]=lt[fC]=lt[nd]=lt[od]=lt[rd]=lt[lC]=lt[cC]=lt[aC]=lt[b1]=lt[v1]=lt[uC]=lt[dC]=!1;function vC(w){return un(w)&&nl(w.length)&&!!lt[Tr(w)]}function yC(w){return function(T){return w(T)}}var k1=typeof t=="object"&&t&&!t.nodeType&&t,ul=k1&&!0&&n&&!n.nodeType&&n,kC=ul&&ul.exports===k1,jc=kC&&z.process,w1=function(){try{var w=ul&&ul.require&&ul.require("util").types;return w||jc&&jc.binding&&jc.binding("util")}catch{}}(),B1=w1&&w1.isTypedArray,wC=B1?yC(B1):vC,BC=Object.prototype,EC=BC.hasOwnProperty;function xC(w,T){var M=At(w),F=!M&&il(w),U=!M&&!F&&rs(w),j=!M&&!F&&!U&&wC(w),G=M||F||U||j,J=G?m1(w.length,String):[],le=J.length;for(var pe in w)(T||EC.call(w,pe))&&!(G&&(pe=="length"||U&&(pe=="offset"||pe=="parent")||j&&(pe=="buffer"||pe=="byteLength"||pe=="byteOffset")||Ku(pe,le)))&&J.push(pe);return J}var Uc=Object.prototype;function IC(w){var T=w&&w.constructor,M=typeof T=="function"&&T.prototype||Uc;return w===M}function zc(w,T){return function(M){return w(T(M))}}var TC=zc(Object.keys,Object),DC=Object.prototype,SC=DC.hasOwnProperty;function E1(w){if(!IC(w))return TC(w);var T=[];for(var M in Object(w))SC.call(w,M)&&M!="constructor"&&T.push(M);return T}function Vc(w){return ol(w)?xC(w):E1(w)}function x1(w){var T=-1,M=w.length;return function(){return++T<M?{value:w[T],key:T}:null}}function LC(w){var T=-1;return function(){var F=w.next();return F.done?null:(T++,{value:F.value,key:T})}}function MC(w){var T=Vc(w),M=-1,F=T.length;return function U(){var j=T[++M];return j==="__proto__"?U():M<F?{value:w[j],key:j}:null}}function RC(w){if(ol(w))return x1(w);var T=Hc(w);return T?LC(T):MC(w)}function vo(w){return function(){if(w===null)throw new Error("Callback was already called.");var T=w;w=null,T.apply(this,arguments)}}function dl(w){return function(T,M,F){if(F=Dr(F||Ne),w<=0||!T)return F(null);var U=RC(T),j=!1,G=0,J=!1;function le(ae,Ae){if(G-=1,ae)j=!0,F(ae);else{if(Ae===si||j&&G<=0)return j=!0,F(null);J||pe()}}function pe(){for(J=!0;G<w&&!j;){var ae=U();if(ae===null){j=!0,G<=0&&F(null);return}G+=1,M(ae.value,ae.key,vo(le))}J=!1}pe()}}function Sr(w,T,M,F){dl(T)(w,R(M),F)}function jt(w,T){return function(M,F,U){return w(M,T,F,U)}}function ld(w,T,M){M=Dr(M||Ne);var F=0,U=0,j=w.length;j===0&&M(null);function G(J,le){J?M(J):(++U===j||le===si)&&M(null)}for(;F<j;F++)T(w[F],F,vo(G))}var OC=jt(Sr,1/0),Go=function(w,T,M){var F=ol(w)?ld:OC;F(w,R(T),M)};function Zo(w){return function(T,M,F){return w(Go,T,R(M),F)}}function cd(w,T,M,F){F=F||Ne,T=T||[];var U=[],j=0,G=R(M);w(T,function(J,le,pe){var ae=j++;G(J,function(Ae,Ze){U[ae]=Ze,pe(Ae)})},function(J){F(J,U)})}var Wc=Zo(cd),ad=H(Wc);function li(w){return function(T,M,F,U){return w(dl(M),T,R(F),U)}}var Lr=li(cd),ud=jt(Lr,1),dd=H(ud);function is(w,T){for(var M=-1,F=w==null?0:w.length;++M<F&&T(w[M],M,w)!==!1;);return w}function hd(w){return function(T,M,F){for(var U=-1,j=Object(T),G=F(T),J=G.length;J--;){var le=G[w?J:++U];if(M(j[le],le,j)===!1)break}return T}}var ss=hd();function ls(w,T){return w&&ss(w,T,Vc)}function I1(w,T,M,F){for(var U=w.length,j=M+(F?1:-1);F?j--:++j<U;)if(T(w[j],j,w))return j;return-1}function _C(w){return w!==w}function T1(w,T,M){for(var F=M-1,U=w.length;++F<U;)if(w[F]===T)return F;return-1}function hl(w,T,M){return T===T?T1(w,T,M):I1(w,_C,M)}var qc=function(w,T,M){typeof T=="function"&&(M=T,T=null),M=Dr(M||Ne);var F=Vc(w),U=F.length;if(!U)return M(null);T||(T=U);var j={},G=0,J=!1,le=Object.create(null),pe=[],ae=[],Ae={};ls(w,function(ht,rt){if(!At(ht)){Ze(rt,[ht]),ae.push(rt);return}var pt=ht.slice(0,ht.length-1),ko=pt.length;if(ko===0){Ze(rt,ht),ae.push(rt);return}Ae[rt]=ko,is(pt,function(E){if(!w[E])throw new Error("async.auto task `"+rt+"` has a non-existent dependency `"+E+"` in "+pt.join(", "));tn(E,function(){ko--,ko===0&&Ze(rt,ht)})})}),o3(),Dt();function Ze(ht,rt){pe.push(function(){yo(ht,rt)})}function Dt(){if(pe.length===0&&G===0)return M(null,j);for(;pe.length&&G<T;){var ht=pe.shift();ht()}}function tn(ht,rt){var pt=le[ht];pt||(pt=le[ht]=[]),pt.push(rt)}function Fn(ht){var rt=le[ht]||[];is(rt,function(pt){pt()}),Dt()}function yo(ht,rt){if(!J){var pt=vo(function(E,Or){if(G--,arguments.length>2&&(Or=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pe){ds[Pe]=Pn}),ds[ht]=Or,J=!0,le=Object.create(null),M(E,ds)}else j[ht]=Or,Fn(ht)});G++;var ko=R(rt[rt.length-1]);rt.length>1?ko(j,pt):ko(pt)}}function o3(){for(var ht,rt=0;ae.length;)ht=ae.pop(),rt++,is(r3(ht),function(pt){--Ae[pt]===0&&ae.push(pt)});if(rt!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function r3(ht){var rt=[];return ls(w,function(pt,ko){At(pt)&&hl(pt,ht,0)>=0&&rt.push(ko)}),rt}};function ci(w,T){for(var M=-1,F=w==null?0:w.length,U=Array(F);++M<F;)U[M]=T(w[M],M,w);return U}var FC="[object Symbol]";function PC(w){return typeof w=="symbol"||un(w)&&Tr(w)==FC}var NC=1/0,fd=fe?fe.prototype:void 0,D1=fd?fd.toString:void 0;function md(w){if(typeof w=="string")return w;if(At(w))return ci(w,md)+"";if(PC(w))return D1?D1.call(w):"";var T=w+"";return T=="0"&&1/w==-NC?"-0":T}function $C(w,T,M){var F=-1,U=w.length;T<0&&(T=-T>U?0:U+T),M=M>U?U:M,M<0&&(M+=U),U=T>M?0:M-T>>>0,T>>>=0;for(var j=Array(U);++F<U;)j[F]=w[F+T];return j}function HC(w,T,M){var F=w.length;return M=M===void 0?F:M,!T&&M>=F?w:$C(w,T,M)}function gd(w,T){for(var M=w.length;M--&&hl(T,w[M],0)>-1;);return M}function jC(w,T){for(var M=-1,F=w.length;++M<F&&hl(T,w[M],0)>-1;);return M}function UC(w){return w.split("")}var zC="\\ud800-\\udfff",VC="\\u0300-\\u036f",WC="\\ufe20-\\ufe2f",ct="\\u20d0-\\u20ff",ot=VC+WC+ct,qC="\\ufe0e\\ufe0f",GC="\\u200d",ZC=RegExp("["+GC+zC+ot+qC+"]");function QC(w){return ZC.test(w)}var S1="\\ud800-\\udfff",YC="\\u0300-\\u036f",L1="\\ufe20-\\ufe2f",JC="\\u20d0-\\u20ff",Gt=YC+L1+JC,pd="\\ufe0e\\ufe0f",ai="["+S1+"]",Gc="["+Gt+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+Gc+"|"+fl+")",Cd="[^"+S1+"]",Ad="(?:\\ud83c[\\udde6-\\uddff]){2}",bd="[\\ud800-\\udbff][\\udc00-\\udfff]",M1="\\u200d",vd=On+"?",yd="["+pd+"]?",wn="(?:"+M1+"(?:"+[Cd,Ad,bd].join("|")+")"+yd+vd+")*",KC=yd+vd+wn,_n="(?:"+[Cd+Gc+"?",Gc,Ad,bd,ai].join("|")+")",XC=RegExp(fl+"(?="+fl+")|"+_n+KC,"g");function R1(w){return w.match(XC)||[]}function Qo(w){return QC(w)?R1(w):UC(w)}function Zc(w){return w==null?"":md(w)}var kd=/^\s+|\s+$/g;function dt(w,T,M){if(w=Zc(w),w&&(M||T===void 0))return w.replace(kd,"");if(!w||!(T=md(T)))return w;var F=Qo(w),U=Qo(T),j=jC(F,U),G=gd(F,U)+1;return HC(F,j,G).join("")}var Mr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,wd=/,/,e3=/(=.+)?(\s*)$/,Bd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function t3(w){return w=w.toString().replace(Bd,""),w=w.match(Mr)[2].replace(" ",""),w=w?w.split(wd):[],w=w.map(function(T){return dt(T.replace(e3,""))}),w}function O1(w,T){var M={};ls(w,function(F,U){var j,G=_(F),J=!G&&F.length===1||G&&F.length===0;if(At(F))j=F.slice(0,-1),F=F[F.length-1],M[U]=j.concat(j.length>0?le:F);else if(J)M[U]=F;else{if(j=t3(F),F.length===0&&!G&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");G||j.pop(),M[U]=j.concat(le)}function le(pe,ae){var Ae=ci(j,function(Ze){return pe[Ze]});Ae.push(ae),R(F).apply(null,Ae)}}),qc(M,T)}function Jn(){this.head=this.tail=null,this.length=0}function Ed(w,T){w.length=1,w.head=w.tail=T}Jn.prototype.removeLink=function(w){return w.prev?w.prev.next=w.next:this.head=w.next,w.next?w.next.prev=w.prev:this.tail=w.prev,w.prev=w.next=null,this.length-=1,w},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.prototype.insertAfter=function(w,T){T.prev=w,T.next=w.next,w.next?w.next.prev=T:this.tail=T,w.next=T,this.length+=1},Jn.prototype.insertBefore=function(w,T){T.prev=w.prev,T.next=w,w.prev?w.prev.next=T:this.head=T,w.prev=T,this.length+=1},Jn.prototype.unshift=function(w){this.head?this.insertBefore(this.head,w):Ed(this,w)},Jn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):Ed(this,w)},Jn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Jn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Jn.prototype.toArray=function(){for(var w=Array(this.length),T=this.head,M=0;M<this.length;M++)w[M]=T.data,T=T.next;return w},Jn.prototype.remove=function(w){for(var T=this.head;T;){var M=T.next;w(T)&&this.removeLink(T),T=M}return this};function ml(w,T,M){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=R(w),U=0,j=[],G=!1;function J(Ae,Ze,Dt){if(Dt!=null&&typeof Dt!="function")throw new Error("task callback must be a function");if(ae.started=!0,At(Ae)||(Ae=[Ae]),Ae.length===0&&ae.idle())return C(function(){ae.drain()});for(var tn=0,Fn=Ae.length;tn<Fn;tn++){var yo={data:Ae[tn],callback:Dt||Ne};Ze?ae._tasks.unshift(yo):ae._tasks.push(yo)}G||(G=!0,C(function(){G=!1,ae.process()}))}function le(Ae){return function(Ze){U-=1;for(var Dt=0,tn=Ae.length;Dt<tn;Dt++){var Fn=Ae[Dt],yo=hl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Ze!=null&&ae.error(Ze,Fn.data)}U<=ae.concurrency-ae.buffer&&ae.unsaturated(),ae.idle()&&ae.drain(),ae.process()}}var pe=!1,ae={_tasks:new Jn,concurrency:T,payload:M,saturated:Ne,unsaturated:Ne,buffer:T/4,empty:Ne,drain:Ne,error:Ne,started:!1,paused:!1,push:function(Ae,Ze){J(Ae,!1,Ze)},kill:function(){ae.drain=Ne,ae._tasks.empty()},unshift:function(Ae,Ze){J(Ae,!0,Ze)},remove:function(Ae){ae._tasks.remove(Ae)},process:function(){if(!pe){for(pe=!0;!ae.paused&&U<ae.concurrency&&ae._tasks.length;){var Ae=[],Ze=[],Dt=ae._tasks.length;ae.payload&&(Dt=Math.min(Dt,ae.payload));for(var tn=0;tn<Dt;tn++){var Fn=ae._tasks.shift();Ae.push(Fn),j.push(Fn),Ze.push(Fn.data)}U+=1,ae._tasks.length===0&&ae.empty(),U===ae.concurrency&&ae.saturated();var yo=vo(le(Ae));F(Ze,yo)}pe=!1}},length:function(){return ae._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ae._tasks.length+U===0},pause:function(){ae.paused=!0},resume:function(){ae.paused!==!1&&(ae.paused=!1,C(ae.process))}};return ae}function ui(w,T){return ml(w,1,T)}var cs=jt(Sr,1);function Yo(w,T,M,F){F=Dr(F||Ne);var U=R(M);cs(w,function(j,G,J){U(T,j,function(le,pe){T=pe,J(le)})},function(j){F(j,T)})}function Qc(){var w=ci(arguments,R);return function(){var T=o(arguments),M=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Ne,Yo(w,T,function(U,j,G){j.apply(M,U.concat(function(J){var le=o(arguments,1);G(J,le)}))},function(U,j){F.apply(M,[U].concat(j))})}}var Yc=function(){return Qc.apply(null,o(arguments).reverse())},xd=Array.prototype.concat,gl=function(w,T,M,F){F=F||Ne;var U=R(M);Lr(w,T,function(j,G){U(j,function(J){return J?G(J):G(null,o(arguments,1))})},function(j,G){for(var J=[],le=0;le<G.length;le++)G[le]&&(J=xd.apply(J,G[le]));return F(j,J)})},_1=jt(gl,1/0),Jc=jt(gl,1),Kc=function(){var w=o(arguments),T=[null].concat(w);return function(){var M=arguments[arguments.length-1];return M.apply(this,T)}};function pl(w){return w}function di(w,T){return function(M,F,U,j){j=j||Ne;var G=!1,J;M(F,function(le,pe,ae){U(le,function(Ae,Ze){Ae?ae(Ae):w(Ze)&&!J?(G=!0,J=T(!0,le),ae(null,si)):ae()})},function(le){le?j(le):j(null,G?J:T(!1))})}}function dn(w,T){return T}var as=Zo(di(pl,dn)),Jo=li(di(pl,dn)),Cl=jt(Jo,1);function Id(w){return function(T){var M=o(arguments,1);M.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[w]&&is(U,function(j){console[w](j)}))}),R(T).apply(null,M)}}var F1=Id("dir");function P1(w,T,M){M=vo(M||Ne);var F=R(w),U=R(T);function j(J){if(J)return M(J);var le=o(arguments,1);le.push(G),U.apply(this,le)}function G(J,le){if(J)return M(J);if(!le)return M(null);F(j)}G(null,!0)}function Td(w,T,M){M=vo(M||Ne);var F=R(w),U=function(j){if(j)return M(j);var G=o(arguments,1);if(T.apply(this,G))return F(U);M.apply(null,[null].concat(G))};F(U)}function N1(w,T,M){Td(w,function(){return!T.apply(this,arguments)},M)}function $1(w,T,M){M=vo(M||Ne);var F=R(T),U=R(w);function j(J){if(J)return M(J);U(G)}function G(J,le){if(J)return M(J);if(!le)return M(null);F(j)}U(G)}function hi(w){return function(T,M,F){return w(T,F)}}function Xc(w,T,M){Go(w,hi(R(T)),M)}function Al(w,T,M,F){dl(T)(w,hi(R(M)),F)}var fi=jt(Al,1);function ea(w){return _(w)?w:i(function(T,M){var F=!0;T.push(function(){var U=arguments;F?C(function(){M.apply(null,U)}):M.apply(null,U)}),w.apply(this,T),F=!1})}function Kn(w){return!w}var mi=Zo(di(Kn,Kn)),bl=li(di(Kn,Kn)),ta=jt(bl,1);function H1(w){return function(T){return T==null?void 0:T[w]}}function us(w,T,M,F){var U=new Array(T.length);w(T,function(j,G,J){M(j,function(le,pe){U[G]=!!pe,J(le)})},function(j){if(j)return F(j);for(var G=[],J=0;J<T.length;J++)U[J]&&G.push(T[J]);F(null,G)})}function Xn(w,T,M,F){var U=[];w(T,function(j,G,J){M(j,function(le,pe){le?J(le):(pe&&U.push({index:G,value:j}),J())})},function(j){j?F(j):F(null,ci(U.sort(function(G,J){return G.index-J.index}),H1("value")))})}function na(w,T,M,F){var U=ol(T)?us:Xn;U(w,T,R(M),F||Ne)}var oa=Zo(na),vl=li(na),ra=jt(vl,1);function j1(w,T){var M=vo(T||Ne),F=R(ea(w));function U(j){if(j)return M(j);F(U)}U()}var ia=function(w,T,M,F){F=F||Ne;var U=R(M);Lr(w,T,function(j,G){U(j,function(J,le){return J?G(J):G(null,{key:le,val:j})})},function(j,G){for(var J={},le=Object.prototype.hasOwnProperty,pe=0;pe<G.length;pe++)if(G[pe]){var ae=G[pe].key,Ae=G[pe].val;le.call(J,ae)?J[ae].push(Ae):J[ae]=[Ae]}return F(j,J)})},gi=jt(ia,1/0),N=jt(ia,1),q=Id("log");function V(w,T,M,F){F=Dr(F||Ne);var U={},j=R(M);Sr(w,T,function(G,J,le){j(G,J,function(pe,ae){if(pe)return le(pe);U[J]=ae,le()})},function(G){F(G,U)})}var he=jt(V,1/0),Ee=jt(V,1);function Ve(w,T){return T in w}function Bt(w,T){var M=Object.create(null),F=Object.create(null);T=T||pl;var U=R(w),j=i(function(J,le){var pe=T.apply(null,J);Ve(M,pe)?C(function(){le.apply(null,M[pe])}):Ve(F,pe)?F[pe].push(le):(F[pe]=[le],U.apply(null,J.concat(function(){var ae=o(arguments);M[pe]=ae;var Ae=F[pe];delete F[pe];for(var Ze=0,Dt=Ae.length;Ze<Dt;Ze++)Ae[Ze].apply(null,ae)})))});return j.memo=M,j.unmemoized=w,j}var qe;a?qe=process.nextTick:l?qe=setImmediate:qe=d;var sa=h(qe);function Dd(w,T,M){M=M||Ne;var F=ol(T)?[]:{};w(T,function(U,j,G){R(U)(function(J,le){arguments.length>2&&(le=o(arguments,1)),F[j]=le,G(J)})},function(U){M(U,F)})}function Bn(w,T){Dd(Go,w,T)}function yl(w,T,M){Dd(dl(T),w,M)}var Sd=function(w,T){var M=R(w);return ml(function(F,U){M(F[0],U)},T,1)},pi=function(w,T){var M=Sd(w,T);return M.push=function(F,U,j){if(j==null&&(j=Ne),typeof j!="function")throw new Error("task callback must be a function");if(M.started=!0,At(F)||(F=[F]),F.length===0)return C(function(){M.drain()});U=U||0;for(var G=M._tasks.head;G&&U>=G.priority;)G=G.next;for(var J=0,le=F.length;J<le;J++){var pe={data:F[J],priority:U,callback:j};G?M._tasks.insertBefore(G,pe):M._tasks.push(pe)}C(M.process)},delete M.unshift,M};function kl(w,T){if(T=Dr(T||Ne),!At(w))return T(new TypeError("First argument to race must be an array of functions"));if(!w.length)return T();for(var M=0,F=w.length;M<F;M++)R(w[M])(T)}function Ci(w,T,M,F){var U=o(w).reverse();Yo(U,T,M,F)}function We(w){var T=R(w);return i(function(F,U){return F.push(function(G,J){if(G)U(null,{error:G});else{var le;arguments.length<=2?le=J:le=o(arguments,1),U(null,{value:le})}}),T.apply(this,F)})}function U1(w){var T;return At(w)?T=ci(w,We):(T={},ls(w,function(M,F){T[F]=We.call(this,M)})),T}function Ld(w,T,M,F){na(w,T,function(U,j){M(U,function(G,J){j(G,!J)})},F)}var wl=Zo(Ld),Md=li(Ld),z1=jt(Md,1);function V1(w){return function(){return w}}function Ai(w,T,M){var F=5,U=0,j={times:F,intervalFunc:V1(U)};function G(ae,Ae){if(typeof Ae=="object")ae.times=+Ae.times||F,ae.intervalFunc=typeof Ae.interval=="function"?Ae.interval:V1(+Ae.interval||U),ae.errorFilter=Ae.errorFilter;else if(typeof Ae=="number"||typeof Ae=="string")ae.times=+Ae||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof w=="function"?(M=T||Ne,T=w):(G(j,w),M=M||Ne),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=R(T),le=1;function pe(){J(function(ae){ae&&le++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ae))?setTimeout(pe,j.intervalFunc(le)):M.apply(null,arguments)})}pe()}var Ko=function(w,T){T||(T=w,w=null);var M=R(T);return i(function(F,U){function j(G){M.apply(null,F.concat(G))}w?Ai(w,j,U):Ai(j,U)})};function Bl(w,T){Dd(cs,w,T)}var El=Zo(di(Boolean,pl)),Rr=li(di(Boolean,pl)),xl=jt(Rr,1);function Rd(w,T,M){var F=R(T);Wc(w,function(j,G){F(j,function(J,le){if(J)return G(J);G(null,{value:j,criteria:le})})},function(j,G){if(j)return M(j);M(null,ci(G.sort(U),H1("value")))});function U(j,G){var J=j.criteria,le=G.criteria;return J<le?-1:J>le?1:0}}function Il(w,T,M){var F=R(w);return i(function(U,j){var G=!1,J;function le(){var pe=w.name||"anonymous",ae=new Error('Callback function "'+pe+'" timed out.');ae.code="ETIMEDOUT",M&&(ae.info=M),G=!0,j(ae)}U.push(function(){G||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(le,T),F.apply(null,U)})}var W1=Math.ceil,Tl=Math.max;function bi(w,T,M,F){for(var U=-1,j=Tl(W1((T-w)/(M||1)),0),G=Array(j);j--;)G[F?j:++U]=w,w+=M;return G}function vi(w,T,M,F){var U=R(M);Lr(bi(0,w,1),T,U,F)}var q1=jt(vi,1/0),G1=jt(vi,1);function Z1(w,T,M,F){arguments.length<=3&&(F=M,M=T,T=At(w)?[]:{}),F=Dr(F||Ne);var U=R(M);Go(w,function(j,G,J){U(T,j,G,J)},function(j){F(j,T)})}function Dl(w,T){var M=null,F;T=T||Ne,fi(w,function(U,j){R(U)(function(G,J){arguments.length>2?F=o(arguments,1):F=J,M=G,j(!G)})},function(){T(M,F)})}function Sl(w){return function(){return(w.unmemoized||w).apply(null,arguments)}}function Ll(w,T,M){M=vo(M||Ne);var F=R(T);if(!w())return M(null);var U=function(j){if(j)return M(j);if(w())return F(U);var G=o(arguments,1);M.apply(null,[null].concat(G))};F(U)}function Q1(w,T,M){Ll(function(){return!w.apply(this,arguments)},T,M)}var Od=function(w,T){if(T=Dr(T||Ne),!At(w))return T(new Error("First argument to waterfall must be an array of functions"));if(!w.length)return T();var M=0;function F(j){var G=R(w[M++]);j.push(vo(U)),G.apply(null,j)}function U(j){if(j||M===w.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},n3={apply:r,applyEach:ad,applyEachSeries:dd,asyncify:v,auto:qc,autoInject:O1,cargo:ui,compose:Yc,concat:_1,concatLimit:gl,concatSeries:Jc,constant:Kc,detect:as,detectLimit:Jo,detectSeries:Cl,dir:F1,doDuring:P1,doUntil:N1,doWhilst:Td,during:$1,each:Xc,eachLimit:Al,eachOf:Go,eachOfLimit:Sr,eachOfSeries:cs,eachSeries:fi,ensureAsync:ea,every:mi,everyLimit:bl,everySeries:ta,filter:oa,filterLimit:vl,filterSeries:ra,forever:j1,groupBy:gi,groupByLimit:ia,groupBySeries:N,log:q,map:Wc,mapLimit:Lr,mapSeries:ud,mapValues:he,mapValuesLimit:V,mapValuesSeries:Ee,memoize:Bt,nextTick:sa,parallel:Bn,parallelLimit:yl,priorityQueue:pi,queue:Sd,race:kl,reduce:Yo,reduceRight:Ci,reflect:We,reflectAll:U1,reject:wl,rejectLimit:Md,rejectSeries:z1,retry:Ai,retryable:Ko,seq:Qc,series:Bl,setImmediate:C,some:El,someLimit:Rr,someSeries:xl,sortBy:Rd,timeout:Il,times:q1,timesLimit:vi,timesSeries:G1,transform:Z1,tryEach:Dl,unmemoize:Sl,until:Q1,waterfall:Od,whilst:Ll,all:mi,allLimit:bl,allSeries:ta,any:El,anyLimit:Rr,anySeries:xl,find:as,findLimit:Jo,findSeries:Cl,forEach:Xc,forEachSeries:fi,forEachLimit:Al,forEachOf:Go,forEachOfSeries:cs,forEachOfLimit:Sr,inject:Yo,foldl:Yo,foldr:Ci,select:oa,selectLimit:vl,selectSeries:ra,wrapSync:v};t.default=n3,t.apply=r,t.applyEach=ad,t.applyEachSeries=dd,t.asyncify=v,t.auto=qc,t.autoInject=O1,t.cargo=ui,t.compose=Yc,t.concat=_1,t.concatLimit=gl,t.concatSeries=Jc,t.constant=Kc,t.detect=as,t.detectLimit=Jo,t.detectSeries=Cl,t.dir=F1,t.doDuring=P1,t.doUntil=N1,t.doWhilst=Td,t.during=$1,t.each=Xc,t.eachLimit=Al,t.eachOf=Go,t.eachOfLimit=Sr,t.eachOfSeries=cs,t.eachSeries=fi,t.ensureAsync=ea,t.every=mi,t.everyLimit=bl,t.everySeries=ta,t.filter=oa,t.filterLimit=vl,t.filterSeries=ra,t.forever=j1,t.groupBy=gi,t.groupByLimit=ia,t.groupBySeries=N,t.log=q,t.map=Wc,t.mapLimit=Lr,t.mapSeries=ud,t.mapValues=he,t.mapValuesLimit=V,t.mapValuesSeries=Ee,t.memoize=Bt,t.nextTick=sa,t.parallel=Bn,t.parallelLimit=yl,t.priorityQueue=pi,t.queue=Sd,t.race=kl,t.reduce=Yo,t.reduceRight=Ci,t.reflect=We,t.reflectAll=U1,t.reject=wl,t.rejectLimit=Md,t.rejectSeries=z1,t.retry=Ai,t.retryable=Ko,t.seq=Qc,t.series=Bl,t.setImmediate=C,t.some=El,t.someLimit=Rr,t.someSeries=xl,t.sortBy=Rd,t.timeout=Il,t.times=q1,t.timesLimit=vi,t.timesSeries=G1,t.transform=Z1,t.tryEach=Dl,t.unmemoize=Sl,t.until=Q1,t.waterfall=Od,t.whilst=Ll,t.all=mi,t.allLimit=bl,t.allSeries=ta,t.any=El,t.anyLimit=Rr,t.anySeries=xl,t.find=as,t.findLimit=Jo,t.findSeries=Cl,t.forEach=Xc,t.forEachSeries=fi,t.forEachLimit=Al,t.forEachOf=Go,t.forEachOfSeries=cs,t.forEachOfLimit=Sr,t.inject=Yo,t.foldl=Yo,t.foldr=Ci,t.select=oa,t.selectLimit=vl,t.selectSeries=ra,t.wrapSync=v,Object.defineProperty(t,"__esModule",{value:!0})})})(up,up.exports);var Tb={exports:{}},dp=Tb.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 a=parseInt(i,e);return a!==1/0&&a>=Math.pow(2,n)?dp(n,e):i};dp.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=dp(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 Db=Ui,CS=xb,AS=Ib,tf=No,hp=up.exports,bS=Tb.exports,Sb=Hs.ACTIONS,Lb=Rt;function Rt(n,e){if(Db.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}Db.mixin(Rt),Rt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Rt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Rt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||bS();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},Rt.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);hp.parallel([function(i){hp.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();hp.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)})})},Rt.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?Sb.presenceSubscribe:Sb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},Rt.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Rt.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Rt.prototype._receiveUpdate=function(n,e){var t=tf.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=tf.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},Rt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Rt.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()}},Rt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Rt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Rt.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)})},Rt.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},Rt.prototype._callbackOrEmit=function(n,e){if(e)return tf.nextTick(e,n);n&&this.emit("error",n)},Rt.prototype._createLocalPresence=function(n){return new CS(this,n)},Rt.prototype._createRemotePresence=function(n){return new AS(this,n)},Rt.prototype._callEachOrEmit=function(n,e){var t=tf.callEach(n,e);!t&&e&&this.emit("error",e)};var Ka=xb,Mb=Yh,vS=No,Rb=Mb.CODES,yS=Ho;function Ho(n,e){Ka.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()}Ho.prototype=Object.create(Ka.prototype),Ho.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:Rb.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,Ka.prototype.submit.call(this,n,e)},Ho.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),Ka.prototype.destroy.call(this,n)},Ho.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={})})}},Ho.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)},Ho.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)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.prototype._message=function(){var n=Ka.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Ho.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!vS.supportsPresence(o))throw new Mb(Rb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var Ob={};(function(n){var e=Qa,t=Yh,o=No,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 a=l.create.type;if(typeof a!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=e.map[a];if(d==null||typeof d!="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,a){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=e.map[d.type];if(!h)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(C){return C}}else if(a.del)l.data=void 0,l.type=null,l.v++;else if("op"in a){var p=i(l,a.op);if(p)return p;l.v++}else l.v++};function i(l,a){if(!l.type)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=e.map[l.type];if(!d)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new t(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new t(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){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{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var C=n.apply(l,p);if(C)return C}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=e.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(C){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:C.message||C}}l.v++};function s(l,a){if(l.type===e.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var C=d[p];typeof C.lm=="string"&&(C.lm=+C.lm);for(var v=C.p,B=h,D=0;D<v.length;D++){var x=v[D];Object.prototype.toString.call(B)=="[object Array]"?v[D]=+x:B.constructor===Object&&(v[D]=x.toString()),B=B[x]}p<d.length-1&&(h=e.defaultType.apply(h,[C]))}}}}})(Ob);var Xa=Ib,kS=Ob,wS=ho;function ho(n,e){Xa.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()}ho.prototype=Object.create(Xa.prototype),ho.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ho.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),Xa.prototype.destroy.call(this,n)},ho.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)},ho.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))}})}},ho.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Xa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Xa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ho.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)}},ho.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++):kS.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ho.prototype._startCachingOps=function(){this._opCache=[]},ho.prototype._stopCachingOps=function(){this._opCache=null},ho.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var _b=Lb,BS=yS,ES=wS;function nc(n,e,t){var o=nc.channel(e,t);_b.call(this,n,o),this.collection=e,this.id=t}var xS=nc;nc.prototype=Object.create(_b.prototype),nc.channel=function(n,e){return n+"."+e},nc.prototype._createLocalPresence=function(n){return new BS(this,n)},nc.prototype._createRemotePresence=function(n){return new ES(this,n)};var IS=TS;function TS(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var DS=IS,Fb=Ui,Pb=eu;function eu(n,e,t,o,r){if(Fb.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}Fb.mixin(eu),eu.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},eu.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},eu.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new DS(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var Nb=Pb,SS=No,LS=Hs.ACTIONS,MS=fp;function fp(n,e,t,o,r,i){if(Nb.call(this,n,e,t,o,i),!SS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}fp.prototype=Object.create(Nb.prototype),fp.prototype._message=function(){return{a:LS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var $b=Pb,RS=No,OS=Hs.ACTIONS,_S=mp;function mp(n,e,t,o,r,i){if($b.call(this,n,e,t,o,i),!RS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}mp.prototype=Object.create($b.prototype),mp.prototype._message=function(){return{a:OS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var FS=cS,PS=fS,NS=Lb,Hb=xS,$S=MS,HS=_S,jb=Ui,oc=Yh,nt=Hs.ACTIONS,Ub=Qa,jo=No,tu=Cb,nu=oc.CODES;function zb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var jS=Be;function Be(n){jb.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=zb(n),this.bindToSocket(n)}jb.mixin(Be),Be.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=zb(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{tu.warn("Failed to parse message",o);return}t.debug&&tu.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){jo.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)}},Be.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=Vb(n.error,n),delete n.error),n.a){case nt.initLegacy:return this._handleLegacyInit(n);case nt.handshake:return this._handleHandshake(e,n);case nt.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case nt.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case nt.queryUnsubscribe:return;case nt.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 nt.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case nt.bulkSubscribe:case nt.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case nt.snapshotFetch:case nt.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case nt.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case nt.subscribe:case nt.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case nt.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case nt.presence:return this._handlePresence(e,n);case nt.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case nt.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case nt.presenceRequest:return this._handlePresenceRequest(e,n);case nt.pingPong:return this._handlePingPong(e);default:tu.warn("Ignoring unrecognized message",n)}};function Vb(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}Be.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](Vb(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 tu.error("Invalid bulk message",e)},Be.prototype._reset=function(){this.agent=null},Be.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 oc(nu.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 a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,e),this.emit("state",n,e)}},Be.prototype.startBulk=function(){this.bulk||(this.bulk={})},Be.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},Be.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var a=t[l];a==null?o.push(l):(r[l]=a,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 d=r[s];this.send({a:n,c:e,d:s,v:d})}else i&&this.send({a:"b"+n,c:e,b:r})}},Be.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)}},Be.prototype.sendFetch=function(n){return this._sendActions(nt.fetch,n,n.version)},Be.prototype.sendSubscribe=function(n){return this._sendActions(nt.subscribe,n,n.version)},Be.prototype.sendUnsubscribe=function(n){return this._sendActions(nt.unsubscribe,n)},Be.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:nt.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)},Be.prototype.send=function(n){this.debug&&tu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Be.prototype.ping=function(){if(!this.canSend)throw new oc(nu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:nt.pingPong};this.send(n)},Be.prototype.close=function(){this.socket.close()},Be.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},Be.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new FS(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},Be.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Be.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},Be.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new PS(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},Be.prototype._destroyQuery=function(n){delete this.queries[n.id]},Be.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(nt.queryFetch,n,e,t,o)},Be.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(nt.querySubscribe,n,e,t,o)},Be.prototype.hasPending=function(){return!!(this._firstDoc(nf)||this._firstQuery(nf)||this._firstSnapshotRequest())};function nf(n){return n.hasPending()}Be.prototype.hasWritePending=function(){return!!this._firstDoc(US)};function US(n){return n.hasWritePending()}Be.prototype.whenNothingPending=function(n){var e=this._firstDoc(nf);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(nf);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},Be.prototype._nothingPendingRetry=function(n){var e=this;return function(){jo.nextTick(function(){e.whenNothingPending(n)})}},Be.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}}},Be.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},Be.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Be.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new $S(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},Be.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new HS(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},Be.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},Be.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Be.prototype._initializeHandshake=function(){this.send({a:nt.handshake,id:this.id})},Be.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},Be.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Be.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new oc(nu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Ub.map[n.type]!==Ub.defaultType)return this.emit("error",new oc(nu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new oc(nu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Be.prototype.getPresence=function(n){var e=this,t=jo.digOrCreate(this._presences,n,function(){return new NS(e,n)});return t._wantsDestroy=!1,t},Be.prototype.getDocPresence=function(n,e){var t=Hb.channel(n,e),o=this,r=jo.digOrCreate(this._presences,t,function(){return new Hb(o,n,e)});return r._wantsDestroy=!1,r},Be.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},Be.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},Be.prototype._handlePresenceSubscribe=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},Be.prototype._handlePresenceUnsubscribe=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},Be.prototype._handlePresence=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},Be.prototype._handlePresenceRequest=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var Wb=jS,zS=Qa;const of={err:1001,msg:"user auth error",name:"AuthError"},VS={err:1002,msg:"you don't have required permission",name:"PermissionError"},gp={err:1003,msg:"Too many user connected",name:"MaxUserError"},ou={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},WS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},qS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},ru="x-live-editor-token",rf="x-live-editor-base-url",Cn=S("auth-connection");function GS(n){try{n()}catch(e){Cn.error(e)}}class ZS{constructor(e,t){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new Q3.EventEmitter);m(this,"token",null);m(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 Mi(this.getBaseURL())}async auth(e){g(Cn,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[ru]:e.token,[rf]: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:{[rf]:Mi(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new jB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Wb.prototype),g(Cn,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}}},Wb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Cn.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){Cn.error(e),setTimeout(()=>this.handleAuthError(),0)}}else Cn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error(of.msg);e.code=of.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(ou.msg);e.code=ou.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===of.err)Cn.warn("auth error"),this.handleAuthError();else if(o===gp.err)Cn.warn(gp.msg),this.emitMaxUsersError();else if(o===ou.err){Cn.warn(ou.msg);try{this.emitRequestReloadError()}catch(r){Cn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Cn.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return g(Cn,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(g(Cn,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){g(Cn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){g(Cn,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(),GS(()=>{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()}}S("utils/file");function QS(){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}QS();async function YS(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new UB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>t&&(a=t);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Mi(i)}const mr=S("sharedb-doc/client");class JS{constructor(e,t,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(mr,!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),mr.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;zS.register(Wd.type),this.connection=new ZS(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return g(mr,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 a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[ru]: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=v=>{mr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await YS(t),d=await this.getFileUrlByHash(e,a,t.name,t.size,o);if(d)return r(-1),d;let h=e;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${t.size}`),p.append("file-hash",a),p.append("file",t,t.name);const C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return mr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;g(mr,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[ru]:this.connection.token},t,o);return g(mr,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 a=t||{};a.url=e,a.headers||(a.headers={}),g(mr,o,"no token"),a.headers={...a.headers,[ru]:o,[rf]:this.connection.getBase64BaseURL()};try{return await $B.default(e,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(mr,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions?withExtra=true`,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=HB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(mr,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,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/${Mi(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 KS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const pp=S("block-ids");class XS{constructor(){m(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);g(pp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();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);g(pp,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=K(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class eL{constructor(){m(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new XS,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 g(pp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class qb{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 Cp=S("op-parse-handler");class tL{constructor(e,t){m(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 eL,i=e.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Cp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;t.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,a=`${l.containerId}-${l.blockIndex}`;if(t.has(a)){Cp.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new qb,o.set(d,h)),h.delete(l.key)}else g(Cp,!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,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new qb,o.set(a,d)),d.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:a,blockIndex:d}=r.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Ot=S("op-parser");class Gb{}class Ap{constructor(e){m(this,"key");this.key=e}}function nL(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 a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Ot,s.id,"block id is required"),g(Ot,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return t.onInsertBlock(n,r,s),!0}function bp(n,e,t,o){if(t==="upsert"&&nL(n,e,o))return;g(Ot,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 a=r[1];if(g(Ot,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),g(Ot,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Ot,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Ot,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Ot,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Ot,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&t==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&t==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&t==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else t==="remove"&&d.r&&s.push(new Ap(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;t==="remove"&&a.r&&s.push(new Gb),t==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Ot,typeof l=="string","data is not string"),g(Ot,l!=="text","data !== 'text'"),g(Ot,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];t==="remove"&&d.r&&s.push(new Ap(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Gb?o.onDeleteBlock(n,i):l instanceof Ap?o.onDeleteBlockData(n,i,l.key):g(Ot,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function oL(n,e,t){Ot.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function rL(n,e,t){const o=n[1],r=n[2];g(Ot,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Ot,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Ot.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):Ot.error(`unknown comment op, ${JSON.stringify(n)}`)}function vp(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{vp(s,e,t)});return}const r=o;if(g(Ot,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){oL(n);return}if(r==="comments"){rL(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{bp(i,s,e,t)}):n.slice(1).forEach(s=>{bp(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 g(Ot,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),bp(i,n.slice(1),e,t)}function Zb(n,e,t){const o=new tL(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=me.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{vp(a,i,o)}):vp(s,i,o)}o.end()}const iL=S("sharedb-comments");function yp(n){const e=n.blocks;g(iL,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)}),me.default(t)}function Qb(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function kp(n,e){const t=zD(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},a=me.default(l);return delete a.children,a}const st=S("sharedb-doc/doc-container"),Yb="ot-json1";Wd.type.registerSubtype(VD.type),Wd.type.name=Yb,Wd.type.invert=null;class iu extends pa{constructor(t,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new jD);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});m(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()});m(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});m(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,a])=>{if(!fa.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){st.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(st.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),st.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(st.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));m(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,Yb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async t=>{if(t.length===0)return Promise.resolve();const o=t.map(({containerId:r,blocks:i})=>[ji(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async t=>{const o=[ji(t),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(t,o,r)=>{const i=[ji(t),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(t,o)=>{const r=[ji(t),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ji(t),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(t,o,r)=>{const i=[ji(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(t,o,r)=>{if(this.destroyed){st.warn("handleOp: destroyed");return}try{Zb(t,this,!!o)}catch(i){throw st.error(i),i}});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--,g(st,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new JS(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new iu(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||KS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw st.error(o),st.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(K()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return Za(this.data())}getContainerBlocks(t){const o=this.data();g(st,o,"no doc data");const r=o[ji(t)];return g(st,r,`no container data: ${t}`),me.default(r)}getBlockData(t,o){const r=this.data();g(st,r,"no doc data");const i=r[ji(t)];g(st,i,`no container data: ${t}`);const s=i[o];return g(st,s,`no block data: ${o}`),me.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);g(st,i.text,"no block text");const s=me.default(i.text);this.submitUpdateRichText(t,o,r);const l=ln.apply(s,r);return g(st,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=me.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainers(t){this.submitInsertChildContainers(t)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Qb(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return yp(o)}localCreateComment(t,o){const r=kp(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=kp(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){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,tc(t),o,r)})}onInsertBlock(t,o,r,i){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,tc(t),o,r,i)})}onUpdateBlockData(t,o,r,i){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,tc(t),o,r,i)})}onUpdateBlockText(t,o,r,i){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,tc(t),o,r,i)})}onDeleteContainer(t,o){g(st,this.callbacks.length>0,"no callbacks"),g(st,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,tc(t),o)})}onCreateContainer(t,o,r){g(st,this.callbacks.length>0,"no callbacks"),g(st,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,tc(t),o,r)})}onDeleteComment(t,o){g(st,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){g(st,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){g(st,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 Za(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return Za(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:Za(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:Za(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){Zb(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Jb{constructor(e){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Mt.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));m(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 Kb=S("remote-cursor-decorator");class wp{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];g(Kb,typeof s=="string","invalid path containerId"),g(Kb,typeof l=="number","invalid path blockIndex");const a=e.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,C)=>{C>d&&(C=d);const v=p.map(D=>({id:K(),type:"remote-cursor",name:D.user.displayName,time:D.time,rainbowIndex:D.user.rainbowIndex})),B=i.get(C);B?B.push(...v):i.set(C,v)}),{insertions:i}}}class Xb extends vt.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Ge(ir(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=te(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 sL(n,e){n.addCustom("child-block-tracker",()=>new Xb(n)).addListener("change",e)}function lL(n,e){n.addCustom("child-block-tracker",()=>new Xb(n)).removeListener("change",e)}const wne="",cL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},aL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},uL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};L.mergeLang({"zh-CN":cL,"en-US":aL,"ja-JP":uL});const Bne="";S("button");function fo(n,e,t,o,r){const i=k("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&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}const Ene="",ev=`<?xml version="1.0" ?>
|
|
27
|
+
`)}const rT=S("get-text-position");function Zl(n,e){const t=e!=null?e:n.selection.range.start;t instanceof Ut||g(rT,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=be(r),s=oe(r),l=ce(s),{offset:a}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Ql=S("insert-text");function Mg(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(g(Ql,r,"no block data"),g(Ql,r.text,"no block text"),rn(r.text)===0)return g(Ql,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Vt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function iT(n,e,t){const o=oe(e),r=ce(o),i=be(e);return Mg(n,r,i,t)}function O6(n,e,t,o,r){const i=oe(e),s=ce(i),l=be(e),a=iT(n,e,t),d=vh(t,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),pn(n,e)}function _6(n,e,t,o){const r=oe(e),i=ce(r),s=be(e),l=vh(t," ",o);return n.doc.localUpdateBlockText(i,s,l),pn(n,e)}function sT(n,e){let t=0;if(e===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Ql,typeof r.insert=="string","invalid text op, no insert");const i=t+yh(r);if(i===e)return!1;if(i>e)return!0;t=i}return!1}function Rg(n,e,t,o,r){const i=n.doc.getBlockData(t,o);g(Ql,i,"no block data"),g(Ql,i.text,"no block text");const s=Mg(n,t,o,r);s&&Object.keys(s).includes("link")&&(sT(i.text,r)||delete s.link);const l=vh(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),pn(n,n.getBlockById(i.id))}function Og(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=Zl(n);Rg(n,e,t,o,r)}const Mh=S("update-composition-text");function F6(n){const e=n.selection.range.start;e instanceof Ut||g(Mh,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);g(Mh,ne(n,o),"not a text kind block");const r=oe(o),i=ce(r),s=be(o),l=n.doc.getBlockData(i,s);g(Mh,l,"no block data in doc"),g(Mh,l.text,"no text data in text block");const a=Le(o);ph(n,Ri(o),t,a,l.text)}function P6(n){Px(n)}function Yl(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const Ha=S("delete-block-text");function _g(n,e,t,o,r){if(!n.isBlockWritable(e))return Ha.error("block is not writable"),0;g(Ha,ne(n,e),"block is not a text kind block");const i=oe(e),s=ce(i),l=be(e),a=n.doc.getBlockData(s,l);g(Ha,a,"no block data in doc"),g(Ha,a.text,"no text data in text block");let d=t;sn(e,t)||(d=_i(e,d));let h=t+o;g(Ha,h<=ue(n,e),`invalid offset and count: ${t}, ${o}`),sn(e,h)||(h=Os(e,h));const p=h-d,C=G4(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const Fg=S("break-text-block");function N6(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function Jl(n,e,t,o){g(Fg,ne(n,e),`block is not a text kind block: ${De(e)}`),g(Fg,t>=0&&t<=ue(n,e),`invalid offset: ${t}`);const r=oe(e),i=ce(r),s=be(e),l=o!=null&&o.copyBlockAttributes?N6(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===ue(n,e))){const v=t===0?s:s+1,B={...ur(""),...l,...o==null?void 0:o.newBlockData},D=kt(n,e.id,0),x=Yl(n,i,v,B,D);return{block:e,newBlock:x}}g(Fg,sn(e,t),"not a valid offset");const a=pn(n,e),{right:d}=Tn(a,t),h=rn(d);h>0&&_g(n,e,t,h);const p={...ur(d),...l,...o==null?void 0:o.newBlockData},C=Yl(n,i,s+1,p,kt(n,p.id,0));return{block:e,newBlock:C}}const lT=S("prepare-insert-new-block");function cT(n,e,t){if(e&&t!==void 0&&t!==null){const d=n.getContainerById(e),h=mt(d);return g(lT,t>=0&&t<=h.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=ce(oe(r)),t=be(r),!ne(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===ue(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const a=Jl(n,r,s).newBlock;return{containerId:e,blockIndex:be(a)}}const aT=S("auto-insert-block");function $6(n,e,t,o,r,i){const s=cT(n,t,o);g(aT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},a={anchor:l,focus:l};return Yl(n,s.containerId,s.blockIndex,e,r!=null?r:a,i)}const uT=S("delete-block");function Rh(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Rh(n,i,t)})}))}function Oh(n,e,t){const o=oe(e),r=ce(o),i=be(e),s=n.doc.getBlockData(r,i);return g(uT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,zt(n,{anchor:t.start,focus:t.end})),s}function Pg(n,e,t){return n.undoManager.runInGroup(()=>{const o=oe(e);To(o)===1&&n.insertTextBlock("",ce(o),0);let r=t?Oi(n,t):null;if(!r){const l=n.selection.range;S6(e,l)?r=L6(n,e):r=l}const i=Oh(n,e,r),s=[];return Rh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function dT(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{Rh(n,r,t)}),n.doc.localDeleteChildContainers(t)}function H6(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Rh(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Ng=S("merge-text-block");function j6(n,e,t){g(Ng,ne(n,e),"only text block can be merged"),g(Ng,ne(n,t),"only text block can be merged");const o=Pi(n,e),r=Pi(n,t),i=o.text,s=r.text;g(Ng,i&&s,"block data has no text");const l=oe(e),a=ce(l),d=be(e),h=ue(n,e),p=Rg(n,s,a,d,h),C=kt(n,e,rn(i));return Pg(n,t,C),p}const dr=S("clear-selected-contents");function _h(n,e){g(dr,ne(n,e.block),"not a text kind block");const{start:t,end:o}=e;g(dr,t.isSimple(),"not a simple block position"),g(dr,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;g(dr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function U6(n,e,t){const o=ce(e),r=mt(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 hT(n,e){const{block:t,start:o,end:r}=e;if(ne(n,t)){_h(n,e);return}if(It(t)||o.isSimple()){g(dr,r.isSimple(),"invalid range");const s=oe(t),l=be(t),a=n.insertTextBlock("",ce(s),l);n.selection.selectBlock(a,0),n.deleteBlock(t);return}g(dr,Me(n,t),"invalid block kind"),g(dr,!o.isSimple()&&!r.isSimple(),"invalid range"),Vl(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{U6(n,s,{focus:l===0})})}function fT(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(g(dr,t.length>0,"no selected block"),t.length===1){hT(n,t[0]);return}const o=t[0],r=o.block,i=oe(r);g(dr,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if(ne(n,r)){_h(n,o);const h=kt(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),ne(n,l)){_h(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(ne(n,l)){_h(n,s),t.slice(0,t.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(t.length===To(i)){U6(n,i,{focus:!0});return}const a=at(r),d=Qe(l);g(dr,a||d,"no prev or next block"),t.forEach(h=>n.deleteBlock(h.block))}function $g(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),fT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const mT=S("core");function z6(n,e,t){const o=oe(e),r=ce(o),i=be(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),pn(n,e)}function V6(n,e,t){if(!n.isBlockWritable(e)){mT.error("block is not writable");return}const o=n.getBlockText(e),r=ln.diff(o,t);z6(n,e,r)}function Fh(n,e,t){const o=pn(n,e),r=typeof t=="string"?Fi(t):t,i=ln.diff(o,r);return z6(n,e,i)}const ja=S("update-block-data");function Ph(n,e,t,o){const r=oe(e),i=ce(r),s=be(e),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(t));return d.forEach(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;ja.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(t).forEach(([C,v])=>{g(ja,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(ja.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(fa.default(B,v)||C==="text"&&ln.diff(B,v).length===0||(d.has(C)?(ja.debug(`replace key: ${C}`),a.delete.push(C)):ja.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Pi(n,e)}function W6(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Hg(n,e,t){if(!Me(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=zn(n,e).getChildContainers(n,e)[0],i=yt(r);Hg(n,i,t)}function Ps(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 Ua=S("clone-block");function Ni(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(h,p)=>(g(Ua,t!==p,"invalid child block"),Ni(n,h,t,o)));let i={};const s=new Map,l=me.default(t);l.children&&(l.children=l.children.map(h=>{const p=K(),C=e.blocks[h];g(Ua,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Ni(n,e,_,o)),B=Ps(v),{root:D,...x}=B.blocks;return i={...i,...x},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[C,v]=p;{const B=`${C}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return Ua.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${C}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return Ua.debug(`replace key: ${h} -> ${x}`),x}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const C=d(h);C!==h&&delete l.key,l[C]=p}),l.id=K(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function jg(n,e,t,o){const r=e.blocks[t];g(Ua,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Ni(n,e,l,o));return Ps(i)}function Ug(n,e,t){const o=e.blocks.root.map(r=>Ni(n.editorBlocks,e,r,t));return me.default(Ps(o))}const q6=S("insert-doc");function G6(n,e,t,o,r){if(Me(n,e)){q6.warn("failed to insert doc into a complex block");return}const i=Ug(n,o,r),s=oe(e),l=be(e),a=ce(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,z,Q;const d=[];Object.entries(i.blocks).forEach(([ee,fe])=>{ee!=="root"&&d.push({containerId:ee,blocks:fe})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(It(e)){n.deleteBlock(e);let ee;h.reverse().forEach(fe=>{const ve=n.insertBlock(a,l,fe,void 0,{noFocus:!0});ee||(ee=ve)}),ee&&n.selection.selectBlock(ee,ue(n,ee));return}if(g(q6,ne(n,e),"not a text block"),ut(n,e)){const ee=a==="root"&&n.getBlockByIndex(a,0)===e,fe=be(e);let ve;h.forEach((ze,He)=>{const Ke=n.insertBlock(a,fe+He,ze,void 0,{noFocus:!0});He===h.length-1&&(ve=Ke)}),ve&&n.selection.selectBlock(ve,ue(n,ve)),ee&&n.deleteBlock(e);return}if(h.length===1){const ee=h[0];if(xa(n,ee.type)){n.insertTextToBlock(e,t,(H=ee.text)!=null?H:[]);return}n.breakTextBlock(e,t),n.insertBlock(a,l+1,ee);return}const p=t===ue(n,e),C=t===0,v=h[0],B=h[h.length-1];let D;!p&&!C?D=n.breakTextBlock(e,t,{forceInsertAfter:!0}):D=e;const x=C?l:l+1;p?(D=n.insertBlock(a,l+1,B),n.selection.selectBlock(D,ue(n,D))):(n.selection.selectBlock(D,0),xa(n,B.type)?n.insertTextToBlock(D,0,(z=B.text)!=null?z:[]):n.insertBlock(a,x,B));const _=n.selection.range;let R=x;xa(n,v.type)?C?(n.insertBlock(a,x,v),R+=1):n.insertTextToBlock(e,t,(Q=v.text)!=null?Q:[]):(n.insertBlock(a,x,v),R+=1),h.slice(1,h.length-1).reverse().forEach(ee=>{n.insertBlock(a,R,ee)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function zg(n,e,t,o,r){const i=Ug(n,o,r),s=ce(e),l=[];return n.undoManager.runInGroup(()=>{const a=[];Object.entries(i.blocks).forEach(([h,p])=>{h!=="root"&&a.push({containerId:h,blocks:p})}),n.doc.localInsertChildContainers(a),i.blocks.root.reverse().forEach(h=>{const p=n.insertBlock(s,t,h,void 0,{noFocus:!0,noScroll:!0});l.push(p)})}),l}function Z6(n,e,t){const o=To(e);zg(n,e,o,t);for(let r=0;r<o;r++){const i=yt(e);n.deleteBlock(i)}}const za=S("add-text-attribute");function gT(n,e,t,o){const{start:r,end:i}=t;g(za,r.blockId===i.blockId&&r.blockId===ie(e),"invalid range"),g(za,o,"invalid attribute name");const s=n.getBlockText(e),l=Gl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function Q6(n,e,t,o,r){const{start:i,end:s}=t;g(za,i.blockId===s.blockId&&i.blockId===ie(e),"invalid range"),g(za,o,"invalid attribute name");const l=n.getBlockText(e),a=Oa(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function Kl(n,e,t,o,r){const{start:i,end:s}=t;g(za,i.blockId===s.blockId&&i.blockId===ie(e),"invalid range");const l=n.getBlockText(e),a=n6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,a),a}function Y6(n,e,t,o){const r=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!ne(n,s))return;if(ut(n,s)){o(n,ie(s),e,t);return}const d=zt(n,{anchor:l,focus:a});e==="color"||e==="backgroundColor"?Kl(n,s,d,e,t):(Kl(n,s,d,"color",null),Kl(n,s,d,"backgroundColor",null))})})}function J6(n,e,t){const o=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!ne(n,i))return;if(ut(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,ie(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,ie(i),"backgroundColor",null);return}const a=zt(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Kl(n,i,a,"color",null),(e==="clearBackground"||e==="clearAll")&&Kl(n,i,a,"backgroundColor",null)})})}function K6(n,e,t){const o=e.getSelectedBlocks().filter(l=>ne(n,l.block));if(o.length===0)return[null,null];const r=l=>{if(ue(n,l.block)===0)return t(n,ie(l.block));const a=l.start,d=l.end,h=n.getBlockText(l.block);return i6(a.offset,d.offset-a.offset,h)};let[i,s]=r(o[0]);return i===null&&s===null?[i,s]:(o.forEach(l=>{const[a,d]=r(l);a===null||i===null?i=null:i=a===i?i:null,d===null||s===null?s=null:s=d===s?s:null}),[i,s])}const Wn=S("adjust-selection-pos");function X6(n){const e=[];for(;n;){const t=oe(n);if(e.unshift(t),Ge(t))return e;const o=te(t);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function eA(n,e){for(;e;){const t=oe(e);if(t===n)return e;const o=te(t);g(Wn,o,"could not find parent block for a child container"),e=o}g(Wn,!1,"no parent block in specified container")}function pT(n,e){const t=X6(n),o=X6(e);g(Wn,t.length>0&&o.length>0,"block has not parent container"),g(Wn,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=eA(r,n),s=eA(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function tA(n,e){let t=te(e);for(g(Wn,t,"element is not in a block");t;){const o=oe(t);g(Wn,Mo(o),"not a child container");const r=te(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;t=r}g(Wn,!1,"failed to find parent container in complex block")}function Nh(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof Ut&&t instanceof Ut?{anchor:e,focus:t}:e instanceof Ro&&t instanceof Ro?mh(n,o,e,t):null;const i=oe(o),s=oe(r);if(i===s)return e instanceof Ro&&(e=se(o,0,"home")),t instanceof Ro&&(t=se(r,ue(n,r),"end")),g(Wn,e instanceof Ut,"not valid position type"),g(Wn,t instanceof Ut,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof Ut&&t instanceof Ro){const B=n.getContainerById(t.childContainerId);if(B===i)return{anchor:t,focus:t};const D=te(i);if(D&&D===te(B)){const x=ft(D,ce(i)),_=ft(D,ce(B));return mh(n,D,x,_)}}return null}const l=Yd(o,r)>0,{newBlock1:a,newBlock2:d}=pT(o,r);if(a===d){const B=a,D=tA(B,o),x=tA(B,r);return e=ft(a,ce(D)),t=ft(a,ce(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),mh(n,B,e,t)}let h=l?ue(n,a):0;a===o&&e instanceof Ut&&(h=e.offset);let C=l?0:ue(n,d);return d===r&&t instanceof Ut&&(C=t.offset),e=se(a,h,l?"end":"home"),t=se(d,C,l?"home":"end"),{anchor:e,focus:t}}const CT=S("move-complex-block-position");function AT(n,e,t){const o=n.getBlockById(e.blockId);g(CT,Me(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?ft(o,ce(s)):null}const Va=S("move-simple-block-position");function nA(n,e){const t=gn(n,e,{visibleOnly:!0});g(Va,t.length>0,"complex block has not any child container");const o=t[0];return yt(o)}function oA(n,e){const t=gn(n,e,{visibleOnly:!0});g(Va,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Qt(o)}function rA(n,e,t){const o=t?nA(n,e):oA(n,e);return Me(n,o)?rA(n,o,t):o}function bT(n,e){const t=n.getBlockById(e.blockId);return Me(n,t)&&e.offset===0?nA(n,t):Ts(t)}function vT(n,e){const t=n.getBlockById(e.blockId);return Me(n,t)&&e.offset===1?oA(n,t):Is(t)}function Vg(n){return n==="ArrowLeft"||n==="ArrowUp"}function Wg(n,e,t){const o=oe(e);if(Ge(o))return null;const r=te(o);g(Va,r,"child container has not parent block"),g(Va,Me(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,t);return i?Vg(t)?Qt(i):yt(i):Wg(n,r,t)}function yT(n,e,t){const o=oe(e);if(Ge(o))return null;const r=te(o);if(g(Va,r,"child container has not parent block"),Vg(t)){const l=at(r);if(l)return l}else{const l=Qe(r);if(l)return l}const i=Wg(n,r,t);if(i)return i;let s=r;for(;!Ge(oe(s));)s=te(oe(s));return Vg(t)?at(s):Qe(s)}function kT(n,e,t){return!Me(n,e)||zn(n,e).enableKeyboardSelect?e:rA(n,e,t==="ArrowDown"||t==="ArrowRight")}function wT(n,e,t){const o=n.getBlockById(e.blockId),i=Ye(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?bT(n,e):vT(n,e);if(s||(s=Wg(n,o,t),s||(s=yT(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Ge(oe(o)))return null;const l=n.insertTextBlock("",ce(n.rootContainer),To(n.rootContainer));return se(l,0,"home")}return null}if(s=kT(n,s,t),ne(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return Qx(n,s,o,e,l);if(t==="ArrowUp")return Zx(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?se(s,ue(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?se(s,0,"home"):null}function BT(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if(ne(n,r))return o;const i=Qe(r);if(i)return se(i,0,"home");if(!Ge(oe(r))||n.readonly)return o;const s=n.insertTextBlock("",ce(n.rootContainer),To(n.rootContainer));return se(s,0,"home")}function ET(n,e,t){const o=n.selection.range;let r;if(o instanceof Yt)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=BT(n,e,o):r=wT(n,o.getFocusedPos(),e);else if(r=AT(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=Qt(s);r=se(l,0,"home")}else{const l=yt(s);r=se(l,ue(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:Nh(n,o.anchor,r):null}function $i(n,e,t){const o=ET(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 iA(n){return $i(n,"ArrowLeft","move"),!0}function sA(n){return $i(n,"ArrowRight","move"),!0}function lA(n){return $i(n,"ArrowUp","move"),!0}function cA(n){if($i(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=oe(e);if(Ge(t)||Qt(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",ce(o),To(o)),!0}function aA(n){return $i(n,"ArrowDown","select"),!0}function uA(n){return $i(n,"ArrowLeft","select"),!0}function dA(n){return $i(n,"ArrowRight","select"),!0}function hA(n){return $i(n,"ArrowUp","select"),!0}const fA=S("word-offset");function qg(n,e){const t=n.selection.range.focus;g(fA,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(ut(n,o))return se(o,0,"home");if(t.offset===0||!ne(n,o)){const s=at(o);if(!s)return null;const l=se(s,ue(n,s),"end");if(e==="select"&&ne(n,s)){const a=Bg(n,s,l.offset);return se(s,a,"normal")}return l}const r=Bg(n,o,t.offset);return se(o,r,"normal")}function Gg(n,e){const t=n.selection.range.focus;g(fA,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(ut(n,o))return se(o,0,"end");if(t.offset===ue(n,o)||!ne(n,o)){const s=Qe(o);if(!s)return null;const l=se(s,0,"home");if(e==="select"&&ne(n,s)){const a=Eg(n,s,l.offset);return se(s,a,"end")}return l}const r=Eg(n,o,t.offset);return se(o,r,"normal")}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const t=qg(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const t=Gg(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function pA(n){if(!n.selection.range.focus.isSimple())return!1;const t=qg(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function CA(n){if(!n.selection.range.focus.isSimple())return!1;const t=Gg(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Zg(n,e){if(!Me(n,e))return e;const o=zn(n,e).getChildContainers(n,e)[0],i=mt(o)[0];return Zg(n,i)}function Qg(n,e){if(!Me(n,e))return e;const t=zn(n,e).getChildContainers(n,e),o=t[t.length-1],r=mt(o),i=r[r.length-1];return Qg(n,i)}function Yg(n){const e=Qg(n,Qt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(t),!0}function AA(n){const e=Zg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(t),!0}function bA(n){const e=Zg(n,n.getFirstBlock()),t=se(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Jg(n){const e=Qg(n,Qt(n.rootContainer)),t=se(e,ue(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const vA=S("line-offset");function yA(n){const e=n.selection.range.focus;g(vA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!ne(n,t))return se(t,0,"home");let r=U4(t,e).start;const{next:i}=uh(t,r);return i&&co(i)&&Ea(i)==="br"&&(r+=1),se(t,r,"home")}function kA(n){const e=n.selection.range.focus;g(vA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===ue(n,t)||!ne(n,t))return se(t,ue(n,t),"end");const o=U4(t,e);return se(t,o.end,"end")}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const t=yA(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const t=kA(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function EA(n){if(!n.selection.range.focus.isSimple())return!1;const t=yA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function xA(n){if(!n.selection.range.focus.isSimple())return!1;const t=kA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const IA=S("find-block-position");function xT(n,e,t,o){g(IA,Me(n,e),"is not a complex block");const r=zn(n,e).getChildContainers(n,e);g(IA,r.length>0,"complex block has not any child container");const i=Lo(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,a=L4(n,e,s,l);return Kg(n,a,t,o)}function Kg(n,e,t,o){if(Me(n,e))return xT(n,e,t,o);const r=ie(e);let i=Number.MAX_SAFE_INTEGER;const s=Lo(n,t,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=se(r,0,"home");const h=ue(n,e);for(let p=0;p<=h;p++){const C=se(r,p,"normal"),v=Lo(n,e,C),B=nr(v,l,a);B<i&&(i=B,d=C)}return d}const TA=S("page-offset");function IT(n,e){const t=I6(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<YI(n))return n.getFirstBlock();const i=at(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=at(s)}return n.getFirstBlock()}function TT(n,e){const t=I6(n)*.9,o=e.getBoundingClientRect(),r=JI(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=Qe(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Qe(l)}return n.getLastBlock()}function DA(n){const e=n.selection.range.focus;g(TA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=IT(n,t);let r;return o===n.getFirstBlock()?r=se(o,0,"home"):r=Kg(n,o,t,e),r}function SA(n){const e=n.selection.range.focus;g(TA,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=TT(n,t);let r;return o===n.getLastBlock()?r=se(o,ue(n,o),"end"):r=Kg(n,o,t,e),r}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const t=DA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const t=SA(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function RA(n){if(!n.selection.range.focus.isSimple())return!1;const t=DA(n);if(!t)return!1;const o=Nh(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 OA(n){if(!n.selection.range.focus.isSimple())return!1;const t=SA(n);if(!t)return!1;const o=Nh(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 Wa=S("select-all");function _A(n,e){const t=yt(n),o=Qt(n);return e.start.offset===0&&e.start.blockId===ie(t)&&e.end.offset===ue(e.getEditor(),o)&&e.end.blockId===ie(o)}function DT(n,e){const t=e.getEditor(),o=zn(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=ie(n);return e.start.blockId===s&&e.start.childContainerId===ce(r)&&e.end.blockId===s&&e.end.childContainerId===ce(i)}function ST(n,e){g(Wa,e,"no parent block"),g(Wa,Me(n,e),"not a complex block");const t=zn(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(zt(n,{anchor:ft(e,ce(o)),focus:ft(e,ce(r))}))}function FA(n,e){const t=oe(e);Xg(n,t)}function PA(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&ne(n,e)){const r=t.start,i=t.end,s=ue(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return W(n.rootContainer,"select-all"),FA(n,yt(n.rootContainer)),!1}return g(Wa,!t.isSimple(),"invalid range type"),DT(e,t)?(FA(n,e),!1):(g(Wa,e,"no parent block"),g(Wa,Me(n,e),"not a complex block"),ST(n,e),!0)}function Xg(n,e){const t=mt(e),o=t[0],r=t[t.length-1],i=se(o,0,"home"),s=se(r,ue(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function LT(n){Jg(n),n.focus()}const ep=S("selected-block-to-doc");function NA(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{NA(n,i,t)}),t.blocks[o]=me.default(r)})}function $h(n,e){const t=Ye(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=me.default(Pi(n,e.block));if(ne(n,e.block)){const i=e.start,s=e.end;if(g(ep,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Vt(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(It(e.block))return{blocks:{root:[o]},meta:{},comments:{}};g(ep,Me(n,e.block),"not complex block"),g(ep,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return NA(n,o,r),r}function tp(n,e){const t=se(e,0,"normal"),o=se(e,ue(n,e),"end");return $h(n,{block:e,start:t,end:o})}const MT=S("block-to-doc");function RT(n,e){g(MT,e.length>0,"invalid params, no blocks");const t=e.map(o=>tp(n,o));return Ps(t)}function Hh(n){const t=n.selection.range.getSelectedBlocks().map(o=>$h(n,o));return Ps(t)}function $A(n,e){const t=n.getContainerById(e),i=mt(t).map(s=>({start:se(s,0,"home"),end:se(s,ue(n,s),"end"),block:s})).map(s=>$h(n,s));return Ps(i)}const jh=S("editor-selection");class OT{constructor(e){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(S6(t,i)){jh.debug("adjust selection because remote deleted current block");const s=L6(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=ie(t);this.caret=new GI(e);const r=se(o,0,"normal");this._range=zt(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=se(e,t,"normal");let i;o&&(i=se(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=zt(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),xe(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!tT(this.editor,r))&&re(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(),ZI(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(!Wr(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=Lo(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){eT(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=ue(this.editor,t)||g(jh,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||g(jh,!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&&xe(t,"focused")&&(re(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=Hh(this.editor);return e==="text"?Na(this.editor,t):e==="markdown"?$a(this.editor,t):R6(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{re(e,"focused"),re(e,"child-focused")})}setBlockFocused(e){if(xe(e,"focused"))return!1;W(e,"focused");let t=oe(e);for(;Mo(t);){const o=te(t);g(jh,o,"parent block not found"),W(o,"child-focused"),t=oe(o)}return!0}}function _T(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,ue(n,t))}function FT(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!ne(n,t))return;let o=qg(n,"select"),r=Gg(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=se(t,0,"home")),r.blockId!==i&&(r=se(t,ue(n,t),"end")),n.selection.setSelection(o,r)}class PT{constructor(e){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(e,t)=>{var r;this.mouseDownEvent=e;const o=O4(this.editor,e.x,e.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&t.autoScroll){const s=o.getSelectedBlocks(),l=so(s[0].block);this.autoScroll=new rh({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(e.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),t.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(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=gh(this.editor,e.x,e.y);if(!t)return;const o=Nh(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",e=>{var t;(t=this.autoScroll)==null||t.inactive(),this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){FT(this.editor)}handleTripleClick(e){_T(this.editor)}}function NT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function $T(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const HA=S("delete-text");function jA(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof Ut||g(HA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(HA,ne(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!sn(s,l-t)){const a=_i(s,l);t=l-a}}else if(e==="forward"&&l+t>ue(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function UA(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const HT=S("handle-backspace");function np(n,e){if(!ut(n,e))return;const t=oe(e);To(t)!==1&&n.deleteBlock(e)}function jT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ne(n,o))if(t.offset===0){if(UA(n,o))return;const r=at(o);if(r){if(!n.isBlockWritable(r))return;if(ne(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Me(n,r)){np(n,o);const i=Wl(n,r);i?n.selection.selectBlock(i,ue(n,i)):n.selection.selectBlock(r,0,ue(n,r))}else np(n,o),g(HT,It(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=oe(o);if(Mo(i)){const s=T4(n,i);if(s){if(!n.isBlockWritable(s))return;np(n,o),n.selection.selectBlock(s,ue(n,s))}}}}else jA(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=be(o),i=oe(o);n.insertTextBlock("",ce(i),r),n.deleteBlock(o)}}function UT(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if(ne(n,o))if(t.offset===ue(n,o)){const r=Qe(o);if(r){if(!n.isBlockWritable(r))return;ne(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ut(n,o)?n.deleteBlock(o,kt(n,r,0)):n.deleteBlock(r)}}else jA(n,"forward",1,null);else{const r=be(o),i=oe(o);n.insertTextBlock("",ce(i),r),n.deleteBlock(o)}}function zT(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Me(n,r))return!1;if(Wr(t))return!0;const s=Vl(n,r,t,o),l=gn(n,r);return s.length===l.length}function VT(n,e){if(zT(n)){const s=n.getFocusedBlock(),l=be(s),a=ce(oe(s));n.insertTextBlock("",a,l+1);return}const t=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&It(t);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),ne(n,t)){if(ut(n,t)&&UA(n,t))return;const s=n.selection.range.start,l=n.breakTextBlock(t,s.offset,{copyBlockAttributes:!0});s.offset!==0?n.selection.selectBlock(l,0):n.selection.scrollIntoView()}else{const s=n.insertTextBlock();n.selection.selectBlock(s,0)}}function WT(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!ne(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const qT=S("input-handler-actions");function GT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(VT(n),!0))}function ZT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(UT(n),!0))}function QT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(jT(n),!0))}function YT(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(WT(n),!0))}function JT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e,{toPlainText:!0})}).catch(e=>{qT.error(e)}),!0)}const Uh={ArrowDown:cA,ArrowUp:lA,ArrowLeft:iA,ArrowRight:sA,"Shift+ArrowDown":aA,"Shift+ArrowUp":hA,"Shift+ArrowLeft":uA,"Shift+ArrowRight":dA,"CtrlOrCmd+ArrowLeft":mA,"CtrlOrCmd+ArrowRight":gA,"CtrlOrCmd+Shift+ArrowLeft":pA,"CtrlOrCmd+Shift+ArrowRight":CA,"CtrlOrCmd+ArrowUp":AA,"CtrlOrCmd+ArrowDown":Yg,"CtrlOrCmd+Shift+ArrowUp":bA,"CtrlOrCmd+Shift+ArrowDown":Jg,"CtrlOrCmd+A":PA,Home:EA,End:xA,"Shift+Home":wA,"Shift+End":BA,PageUp:LA,PageDown:MA,"Shift+PageUp":RA,"Shift+PageDown":OA,"CtrlOrCmd+Z":NT,"CtrlOrCmd+Shift+Z":$T,Enter:GT,Delete:ZT,Backspace:QT,"Shift+Enter":YT,"CtrlOrCmd+Shift+V":JT};function zA(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function VA(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);if(l)i.src=l;else{let a="";s.split("|").forEach(h=>{const p=t.get(h);p&&(a+=a?`|${p}`:`${p}`)}),a&&(i.src=a)}}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=>{VA(n,l,t)})})}function WA(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):VA(e,r,t)})}async function KT(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 XT(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 eD(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(XT(n,e)){const s=Array.from(Object.keys(o));r=await KT(n,s),WA(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&&WA(n,e,i)}async function tD(n,e,t){await eD(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&It(i)){const s=oe(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,e,t);a&&n.selection.selectBlock(a,ue(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=Zl(n);n.insertDoc(s,l,e,t)}})}const nD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function oD(n){let e;for(const t of nD)if(e=n[t],e)break;return e||null}function qA(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=>{qA(n,l,t)})})}function rD(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)}):qA(e,r,t)}),Array.from(t)}function zh(n,e){return Zt.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Mi(JSON.stringify(e))}" id="ones-editor-doc">${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Mi(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Vh(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=rD(n,e),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),e.meta={...t,resources:r}}function iD(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=Hh(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Vh(n,o);const i=Lh(n,o),s=$a(n,o),l=zh(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 Wh(n,e){const t=tp(n,e);Vh(n,t);const o=Lh(n,t),r=$a(n,t),i=zh(o,t);return Pm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class sD{constructor(e){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(e,t)=>{const o=new DataTransfer;o.setData("text/plain",e);const r=await this.editor.dataConverter.fromData(this.editor,o,t);r&&this.pasteDocs(r,null)});this.editor=e}onInsertText(e,t){if(!ne(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Zl(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}=Zl(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}=Zl(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(e){iD(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;It(o)&&this.editor.deleteBlock(o)}else $g(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(){W(this.editor.rootElement,"active")}onBlur(){re(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e),this.handlers=this.handlers.sort((t,o)=>{var s,l;const r=(s=t.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}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){Og(this.editor,i)}defaultHandleKeydown(e,t){return zA(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 tD(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=oD(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 lD(n,e,t){const o=Hr(e,t);return o.remove(),o}S("copy-dom-attributes");const GA=["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 cD(n,e){for(let l=0;l<GA.length;l++){const a=GA[l];e[a]=n[a]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const a=t[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];t.getNamedItem(a.name)||s.push(a)}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 ZA(n){const e=Array.from(n.childNodes).filter(t=>!V5(t));return e.forEach(t=>{t.remove()}),e}function QA(n,e,t){var d;const o=n.getContainerById(e),r=Hr(o,t),i=Ri(r),s=n.doc.getBlockData(e,t),l=Ye(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=ZA(h);ZA(r),p.forEach(v=>{r.appendChild(v)});const C=ch(h);if(C){const v=ch(r);v&&v.remove(),r.appendChild(C)}cD(h,r)}c4(n,r,s),n.blockHooks.forEach(h=>{var p;(p=h.update)==null||p.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const aD=S("transform-selection");function YA(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;g(aD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const d=ln.transformCursor(i.offset,t,o);l=se(e,d,"normal")}let a=s;if(s.blockId===e){const d=ln.transformCursor(s.offset,t,o);a=se(e,d,"normal")}return zt(n,{anchor:l,focus:a})}const uD=S("handle-block-text-changed");function dD(n,e,t,o,r){const i=n.getContainerById(e),s=Hr(i,t),l=n.doc.getBlockData(e,t);if(g(uD,l.text,"no block text"),n4(n,s).setBlockText(n,s,l.text),!r){const a=YA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function hD(n,e){const t=me.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function JA(n,e,t,o){const r=Ye(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function fD(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{JA(n,i,o,{child:!0})}),JA(n,r,o,{child:!1})}const _o=S("editor-doc");class mD extends pa{constructor(t,o,r){super();m(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);g(_o,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;g(_o,l,`no text, ${t}, ${o}`);const a=YA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(t,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(t,o,r,i){g(_o,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(C=>C!=="comments"),p=Object.keys(r.insert).filter(C=>C!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=me.default(this.getBlockData(t,o)),a=me.default(hD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(t,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(Oi(this.editor,i)),d}localInsertBlock(t,o,r,i,s){g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(t,o,r){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=me.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(Oi(this.editor,r)),s}localDeleteChildContainers(t){return g(_o,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=me.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainers(t){g(_o,!this.editor.readonly,"editor is readonly");const o=me.default(t);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(t){_o.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)}),dD(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)}),QA(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);ex(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){fD(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);lD(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){_o.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function KA(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 qh=S("undo-action");class Xl{constructor(e,t,o){m(this,"beforeRange");m(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 g(qh,e,"no other action"),!1}combine(e){g(qh,!1,"no other")}setAfterRange(e){this.afterRange&&qh.warn("after range has already set"),this.afterRange=e}findContainerById(e,t){return e.doc.toJSON().blocks[t]!==void 0}findBlockById(e,t){return e.doc.getContainerBlocks(this.containerId).some(r=>r.id===t)}checkBlockData(e,t){if(Array.isArray(t.children)){const o=e.doc.toJSON();for(let r=0;r<t.children.length;r++){const i=t.children[r];if(!o.blocks[i])return qh.warn(`container (${i}) not found, deleted by others?`),!1}}return!0}}const ec=S("block-action");class XA extends Xl{constructor(t,o,r,i,s){super(t,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=me.default(i),this.blockIndex=r}deleteBlock(t,o){if(!this.findContainerById(t,this.containerId))return ec.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(t,this.blockData.id))return ec.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);if(!i)return!1;try{g(ec,this.blockIndex===be(i),"invalid block index"),Oh(t,i,Oi(t,o))}catch(s){ec.warn(s.message),t.selection.selectBlock(i,0)}return!0}insertBlock(t,o){if(!this.findContainerById(t,this.containerId))return ec.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(t,this.blockData))return!1;try{Yl(t,this.containerId,this.blockIndex,me.default(this.blockData),o)}catch(r){ec.warn(r.message);const i=t.doc.getContainerBlocks(this.containerId),s=Math.min(i.length-1,this.blockIndex),l=t.getBlockByIndex(this.containerId,s);t.selection.selectBlock(l,0)}return!0}}S("insert-block-action");class gD extends XA{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class pD extends XA{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class CD extends Xl{constructor(t){super(t,ce(t.rootContainer),t.selection.range.toDocRange());m(this,"actions",[])}addAction(t){KA(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 Xl&&(o.afterRange||o.setAfterRange(t))}}const Hi=S("update-block-data-action");class Gh extends Xl{constructor(t,o,r,i,s,l){super(t,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hi,this.blockId===i.id,"invalid block id"),g(Hi,this.blockId===s.id,"invalid block id"),this.beforeBlockData=me.default(i),this.afterBlockData=me.default(s),g(Hi,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){if(!t.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=t.getBlockById(this.blockId);if(!o||!this.checkBlockData(t,this.beforeBlockData))return!1;const r=t.getContainerById(this.containerId);return g(Hi,r,"no container"),Ph(t,o,Gh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){if(!t.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g(Hi,t,"no editor");const o=t.getBlockById(this.blockId);if(!o||!this.checkBlockData(t,this.beforeBlockData))return!1;const r=t.getContainerById(this.containerId);return g(Hi,r,"no container"),Ph(t,o,Gh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=me.default(t);return delete o.id,delete o.type,o}}const Ns=S("update-block-text-action");class qa extends Xl{constructor(t,o,r,i,s,l){super(t,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=me.default(i),this.afterRichTextData=me.default(s),this.type=qa.calType(i,s)}static calType(t,o){g(Ns,t,"no old data"),g(Ns,o,"no new data");const i=ln.diff(t,o),s=new Set;let l=!1;const a=h=>v5(h)?`cjk_${h}`:A5(h)?"number":Xd(h)?"space":b5(h)?"letter":"unknown";let d=!1;return i.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(t){if(!this.findContainerById(t,this.containerId))return Ns.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(t,this.blockId))return Ns.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(Fh(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!this.findContainerById(t,this.containerId))return Ns.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(t,this.blockId))return Ns.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(Fh(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof qa)||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){g(Ns,t instanceof qa,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}const eb=S("child-container-action");class tb extends Xl{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return this.findContainerById(e,this.containerId)?(e.doc.localDeleteChildContainers([this.containerId]),!0):(eb.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(e){return this.findContainerById(e,this.containerId)?(eb.warn(`container (${this.containerId}) already exists`),!1):(e.doc.localInsertChildContainers([{containerId:this.containerId,blocks:me.default(this.blocks)}]),!0)}}class AD extends tb{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class bD extends tb{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const Fo=S("undo");class vD{constructor(e){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(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):(KA(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new CD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.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 Fo.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(Oi(this.editor,e.beforeRange))}catch(t){Fo.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(Oi(this.editor,t)):Fo.warn("no after range")}catch(t){Fo.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(),ln.diff(o,r).length!==0&&this.addAction(new qa(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Gh(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,t>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new gD(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new pD(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new AD(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,e,t)))}}class yD{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 kD{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new yD)}prepareData(e){const t=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)t.setData(this.converterTypes[o],e.getData(this.converterTypes[o]));return t}async fromData(e,t,o){let r={};const i=this.prepareData(t);for(const s of this.converters){const l=await s.fromData(e,i,o);l&&(r={...r,...l})}return r}addConverter(e){this.converters.push(e)}}class wD{constructor(e){m(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 Ct extends vt.TypedEmitter{constructor(t){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(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=te(o);if((!r||!et(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?ie(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&&et(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&re(s,"hover"),t&&W(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 Ct(t))}getParentTextContentChild(t,o){if(!ne(this.editor,t))return null;const r=Le(t);return o.parentElement===r?o:Vm(o)}}const nb="style-color-",ob="style-bg-color-";class BD{renderText(e,t,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(nb)?i["data-style-color"]=l.substring(nb.length):l.startsWith(ob)?i["data-style-bg-color"]=l.substring(ob.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(e,t,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=e.selection)==null?void 0:l.range)==null?void 0:a.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"),Ct.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(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ct.get(e).hoveringBlockId()===r.id&&W(o,"hover")}}function ED(n){n.editorBlocks.registerBlockClass(Dn),n.editorBlocks.registerBlockClass(I4),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(C6),n.editorBoxes.registerBoxClass(v6),n.editorBoxes.registerBoxClass(y6),n.editorInsertions.registerInsertionClass(k6),n.editorBlockRenders.registerRender(new BD)}function xD(n,e){ED(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 Zh=S("range-commands");function rb(n,e){n.forEach(t=>{t.source=e,t.children&&rb(t.children,e)})}function ib(n,e,t){const o=ie(e);g(Zh,o===t.start.blockId,"invalid start range"),g(Zh,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];if(r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);rb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),Me(n,e)){g(Zh,!t.start.isSimple(),"invalid start pos"),g(Zh,!t.end.isSimple(),"invalid end pos");const s=t.start.childContainerId,l=ir(n,s),d=mt(l)[0];if(d){const h=ue(n,d),p=zt(n,{anchor:se(d,0,"home"),focus:se(d,h,"end")}),C=ib(n,d,p);i.push(...C)}}return i}function sb(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[],r=n.isReverse()?t[0]:t[t.length-1],i=zt(e,{anchor:r.start,focus:r.end});return ib(e,r.block,i).forEach(l=>{o.push(l)}),o}function lb(n,e,t,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const C=s[p];if(C.beforeExecuteCommand&&C.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,e,t,o,r,{}))return i[ie(e)]=a,!0;let d=!1;return Me(n,e)&&Vl(n,e,t.start,t.end).forEach(C=>{mt(C).forEach(B=>{const D=ue(n,B),x=zt(n,{anchor:se(B,0,"home"),focus:se(B,D,"end")});lb(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,e,t,o,r,i)}),d}function cb(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 a=zt(o,{anchor:l.start,focus:l.end});lb(o,l.block,a,e,t,r)}),o.focus()),r}const ID=S("command-providers");class ab{constructor(e){m(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 g(ID,t,`no command provider, id=${e}`),t}getCommands(e){return sb(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>cb(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 TD(n,e){const t=oe(e),o=ce(t),r=be(e);QA(n,o,r)}const DD=S("table-scroll");class ub{constructor(e,t,o,r,i){m(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 SD{constructor(e){m(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)){DD.warn(`event has already registered: ${t}`);return}i.push(new ub(this.editor,e,t,o,r))}else{const s=new ub(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 a=s[l];if(t)t===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.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 db=S("update-block-text");function LD(n,e){const t=n.getBoxById(e.id),o=te(t);g(db,o,"no parent block"),g(db,ne(n,o),"not a text block");const r=n.getBlockText(o),i=l6(r,"id",e.id,e);V6(n,o,i)}function MD(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 RD(n){if(n.readonly)return!1;const e=lr(n);return!!n.isBlockWritable(e.map(t=>t.block))}class OD{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 _D{constructor(){m(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(or(t,s)){const a=l(e,t);if(a!==void 0)return a}}}}const Yr=S("editor");class FD extends vt.TypedEmitter{constructor(t,o,r){var i,s,l,a,d,h,p,C;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new _D);m(this,"dataConverter",new kD);m(this,"editorBlocks",new w4(this));m(this,"editorBoxes",new b6(this));m(this,"editorInsertions",new B6(this));m(this,"editorEmbeds",new E4(this));m(this,"editorDecorators",new E6(this));m(this,"editorCommandProviders",new ab(this));m(this,"editorBlockRenders",new wD(this));m(this,"blockHooks",[]);m(this,"domEvents",new SD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new sD(this));m(this,"settingsProvider");m(this,"_readonly",!1);m(this,"getColor",t=>{const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]});Yr.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,enableComments:(a=r==null?void 0:r.enableComments)!=null?a:!0},this.settingsProvider=(d=r==null?void 0:r.settingsProvider)!=null?d:new OD(this),xD(this,r==null?void 0:r.components),this.blockHooks.push(...(p=(h=r==null?void 0:r.components)==null?void 0:h.blockHooks)!=null?p:[]),this.id=(C=r==null?void 0:r.id)!=null?C:K(),this.clientId=K(),this.undoManager=new vD(this),this.doc=new mD(this,o,this.undoManager),this.parent=t,this.rootElement=k("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=k("div",["editor-content"],this.rootElement),this.rootContainerObject=v4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new qI(this,this.inputHandlers),this.selection=new OT(this),this.selectionHandler=new PT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Zt.isMobile&&W(this.rootElement,"mobile"),Zt.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?W(this.rootElement,"readonly"):re(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:so(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 g(Yr,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(){Yr.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(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(t,o){Hg(this,t,o)}isWritable(){return RD(this)}isBlockWritable(t){return MD(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return(!o||!Array.isArray(o))&&(g(Yr,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),g(Yr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(t,o,r){return y4(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&&g(Yr,Bs(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&g(Yr,zm(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return g(Yr,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return g(Yr,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Hr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return be(o)}return be(t)}getContainerById(t){return ir(this,t)}getParentContainer(t){return oe(t)}reloadBlock(t){TD(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},a={anchor:l,focus:l};return Yl(this,t,o,r,i!=null?i:a,s)}insertEmbed(t,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Pg(this,t,o)}mergeTextBlock(t,o){return j6(this,t,o)}breakTextBlock(t,o,r){return Jl(this,t,o,r).newBlock}getTextPosition(){return Zl(this)}getBlockString(t,o){const r=this.getBlockText(t);return it(r,o)}getBlockData(t){return Pi(this,t)}getBoxData(t){return m6(this,t)}getBlockText(t){return pn(this,t)}setBlockText(t,o){V6(this,t,o)}deleteTextFromBlock(t,o,r,i){return _g(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return O6(this,t,o,r,i)}insertBoxToBlock(t,o,r){return _6(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){G6(this,t,o,r,i)}insertDocAt(t,o,r,i){return zg(this,t,o,r,i)}deleteChildContainers(t){H6(this,t)}replaceBlockText(t,o){return Fh(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...a}=i;return Ph(this,t,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return W6(this,t,o,r)}updateBoxData(t){LD(this,t)}getSelectedText(){const t=Hh(this);return Na(this,t)}clearSelectedContents(){$g(this)}insertTextBlock(t,o,r,i){const s=ur(t!=null?t:"");return $6(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){P6(this);return}o?(this.compositingText="",jl()||Og(this,t)):(this.compositingText=t,F6(this))}}function Ga(n,e,t){return new FD(n,e,t)}function PD(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=ym.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const ND=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Qh extends vt.TypedEmitter{constructor(t){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=t&&t.length>0?t:ND}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&fa.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.emit("change",Array.from(this.users.values()));const o=this.cursors.get(t);if(o){const r=new Set(new Set([o==null?void 0:o.range.anchor.blockId,o==null?void 0:o.range.focus.blockId]));this.cursors.delete(t),this.emit("remote-carets-change",[...r])}}updateUsers(t){this.users.forEach(o=>{t.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),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&&Eh(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(Eh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===t.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===t.id&&(d.offset=ln.transformCursor(d.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 Xt=S("local-doc");class op extends pa{constructor(t,o){super();m(this,"doc");m(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[ur("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return me.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);g(Xt,r,`no container data: ${t}`);const i=r[o];return g(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);g(Xt,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.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}),g(Xt,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 g(Xt,i,`no container data: ${t}`),g(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xt,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);g(Xt,r,`no container data: ${t}`),g(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xt,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}localInsertChildContainers(t){t.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,o,r,!0)})})}localDeleteChildContainers(t){Xt.debug(`delete child containers: ${t}`),t.forEach(o=>{g(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{g(Xt,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){g(Xt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){g(Xt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Qh}setDoc(t){this.doc=me.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class $D{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function rp(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new $D(o)})}const hb=S("find-block");function fb(n,e){const t=Is(e);if(!t){if(lo(e))return null;const o=Es(e);return g(hb,o,"no parent block"),fb(n,o)}return Me(n,t)?Wl(n,t,{visibleOnly:!0}):t}function mb(n,e){const t=Ts(e);if(!t){if(lo(e))return null;const o=Es(e);return g(hb,o,"no parent block"),mb(n,o)}return Me(n,t)?rg(n,t,{visibleOnly:!0}):t}const HD=S("remote-cursor");class jD{constructor(){m(this,"remoteUsers",new Qh)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):HD.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 UD(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function zD(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function Za(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=UD(me.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function ji(n){return n==="root"?"blocks":n}function tc(n){return n==="blocks"?"root":n}const VD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},compose(n,e){const t=new on.default(n),o=new on.default(e);return t.compose(o).ops},diff(n,e){const t=new on.default(n),o=new on.default(e);return t.diff(o).ops},transform(n,e,t){const o=new on.default(n);return new on.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 on.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 hr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ui={},ip=J3.default.EventEmitter;Ui.EventEmitter=ip,Ui.mixin=WD;function WD(n){for(var e in ip.prototype)n.prototype[e]=ip.prototype[e]}var gb=["info","warn","error"];function pb(){var n={};gb.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var qD=pb;pb.prototype.setMethods=function(n){n=n||{};var e=this;gb.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var GD=qD,ZD=new GD,Cb=ZD;function $s(n,e){this.code=n,this.message=e||"",Error.captureStackTrace?Error.captureStackTrace(this,$s):this.stack=new Error().stack}$s.prototype=Object.create(Error.prototype),$s.prototype.constructor=$s,$s.prototype.name="ShareDBError",$s.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 Yh=$s,Qa={},Ab=QD;function QD(n,e,t,o){var r=function(s,l,a,d){e(a,s,l,"left"),e(d,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],C=0;C<s.length;){var v=[];if(r(s[C],h,p,v),C++,v.length===1)h=v[0];else if(v.length===0){for(var B=C;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(C),v),x=0;x<D[0].length;x++)o(p,D[0][x]);for(var _=0;_<D[1].length;_++)o(a,D[1][_]);h=null;break}}h!=null&&o(a,h),s=p}return[s,a]};n.transform=function(s,l,a){if(!(a==="left"||a==="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],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var bb={exports:{}},zi=bb.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||""}},sp=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},lp=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")},Jh=function(n){for(var e=0;e<n.length;e++)lp(n[e])};zi.apply=function(n,e){var t;Jh(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=sp(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 Jr=zi._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:sp(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:sp(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};zi.compose=function(n,e){Jh(n),Jh(e);for(var t=n.slice(),o=0;o<e.length;o++)Jr(t,e[o]);return t},zi.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),Jr(e,o)}return e};var cp=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};zi.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=cp(n,e[r],o);return n};var YD=zi._tc=function(n,e,t,o){if(lp(e),lp(t),e.i!=null)Jr(n,{i:e.i,p:cp(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(Jr(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&Jr(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)Jr(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)Jr(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),a=e.d.slice(s-e.p,l-e.p),d=t.d.slice(s-t.p,l-t.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=cp(i.p,t),Jr(n,i))}return n},JD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};zi.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=JD(n[e]);return n},Ab(zi,YD,Jh,Jr);var Kh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},KD=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},Ie={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Kr={};Ie.registerSubtype=function(n){Kr[n.name]=n},Ie.create=function(n){return n===void 0?null:Po(n)},Ie.invertComponent=function(n){var e={p:n.p};return n.t&&Kr[n.t]&&(e.t=n.t,e.o=Kr[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},Ie.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(Ie.invertComponent(e[o]));return t},Ie.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!Kh(n[e].p))throw new Error("Missing path")},Ie.checkList=function(n){if(!Kh(n))throw new Error("Referenced element not a list")},Ie.checkObj=function(n){if(!KD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ya(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 Ja(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}Ie.apply=function(n,e){Ie.checkValidOp(e),e=Po(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&Ya(r);for(var i=null,s=t,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Kr[r.t])s[l]=Kr[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)Ie.checkList(s),s[l]=r.li;else if(r.li!==void 0)Ie.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)Ie.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(Ie.checkList(s),r.lm!=l){var h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}else if(r.oi!==void 0)Ie.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)Ie.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},Ie.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},Ie.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=Ie.apply(n,r),t(r,n)}return n};var XD=Ie.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};Ie.append=function(n,e){if(e=Po(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)&&(Ya(e),Ya(t)),XD(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Kr[e.t]){if(t.o=Kr[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(),Ja(e),n.push(e);Ja(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)&&(Ja(e),Ja(t)),n.push(e)},Ie.compose=function(n,e){Ie.checkValidOp(n),Ie.checkValidOp(e);for(var t=Po(n),o=0;o<e.length;o++)Ie.append(t,e[o]);return t},Ie.normalize=function(n){var e=[];n=Kh(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),Ie.append(e,o)}return e},Ie.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},Ie.canOpAffectPath=function(n,e){return Ie.commonLengthForOps({p:e},n)!=null},Ie.transformComponent=function(n,e,t,o){e=Po(e);var r=Ie.commonLengthForOps(t,e),i=Ie.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 a=Po(t);a.p=a.p.slice(s),e.ld=Ie.apply(Po(e.ld),[a])}else if(e.od!==void 0){var a=Po(t);a.p=a.p.slice(s),e.od=Ie.apply(Po(e.od),[a])}}if(r!=null){var d=s==l,a=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(Ya(e),a=Po(t),Ya(a)),a.t&&Kr[a.t]){if(e.t&&e.t===a.t){var h=Kr[e.t].transform(e.o,a.o,o);if(e.si!=null||e.sd!=null)for(var p=e.p,C=0;C<h.length;C++)e.o=[h[C]],e.p=p.slice(),Ja(e),Ie.append(n,e);else(!Kh(h)||h.length>0)&&(e.o=h,Ie.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(d){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=Po(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&d&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&d&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&d){if(t.p[r]===e.p[r])return n;var p=t.p[r],v=e.p[r],B=e.lm;(p<B||p===B&&v<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 v=e.p[r],B=e.lm,D=t.p[r],x=t.lm;if(D!==x)if(v===D)if(o==="left")e.p[r]=x,v===B&&(e.lm=x);else return n;else v>D&&e.p[r]--,v>x?e.p[r]++:v===x&&D>x&&(e.p[r]++,v===B&&e.lm++),(B>D||B===D&&B>v)&&e.lm--,B>x?e.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&e.lm++:B>v?e.lm++:B===D&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&d){var v=t.p[r],B=t.lm;p=e.p[r],p>v&&e.p[r]--,p>B&&e.p[r]++}else{var v=t.p[r],B=t.lm;p=e.p[r],p===v?e.p[r]=B:(p>v&&e.p[r]--,(p>B||p===B&&v>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&&d){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")Ie.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!d)return n;if(e.oi!==void 0)delete e.od;else return n}}}return Ie.append(n,e),n},Ab(Ie,Ie.transformComponent,Ie.checkValidOp,Ie.append);var eS=bb.exports;Ie.registerSubtype(eS);var tS=Ie,nS={type:tS};(function(n){n.defaultType=nS.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)})(Qa);var No={};(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))}})(No);var vb=Array.isArray,yb=Object.keys,oS=Object.prototype.hasOwnProperty,rS=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=vb(e),r=vb(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 a=e instanceof Date,d=t instanceof Date;if(a!=d)return!1;if(a&&d)return e.getTime()==t.getTime();var h=e instanceof RegExp,p=t instanceof RegExp;if(h!=p)return!1;if(h&&p)return e.toString()==t.toString();var C=yb(e);if(s=C.length,s!==yb(t).length)return!1;for(i=s;i--!==0;)if(!oS.call(t,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},kb=Ui,iS=Cb,qn=Yh,Xh=Qa,$o=No,sS=$o.clone,lS=rS,Sn=qn.CODES,cS=Fe;function Fe(n,e,t){kb.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}kb.mixin(Fe),Fe.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())})},Fe.prototype._setType=function(n){if(typeof n=="string"&&(n=Xh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new qn(Sn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},Fe.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Fe.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new qn(Sn.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 qn(Sn.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?Xh.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()},Fe.prototype.whenNothingPending=function(n){var e=this;$o.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},Fe.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Fe.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Fe.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Fe.prototype._emitResponseError=function(n,e){if(n&&n.code===Sn.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)},Fe.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){$o.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},Fe.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){$o.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()},Fe.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Sn.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=ef(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=ef(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},Fe.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))},Fe.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()},Fe.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);aS(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},Fe.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},Fe.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},Fe.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=uS([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},Fe.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;$o.nextTick(function(){n._handleSubscribe()})}}};function aS(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function uS(n){return n=n.filter($o.truthy),n.length?function(e){$o.callEach(n,e)}:null}Fe.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function dS(n){delete n.op,delete n.create,delete n.del}function ef(n,e){if(n.del)return dS(e);if(e.del)return new qn(Sn.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new qn(Sn.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}}}Fe.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new qn(Sn.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===Xh.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=ef(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 a=this.data;this._setType(null),this.emit("del",a,e);return}},Fe.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 qn(Sn.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>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Sn.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)}},Fe.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new qn(Sn.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;$o.nextTick(function(){r.flush()})},Fe.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)},Fe.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)}}},Fe.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!lS(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}}},Fe.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)},Fe.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=Xh.defaultType.uri),this.type){var r=new qn(Sn.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)},Fe.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new qn(Sn.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)},Fe.prototype.pause=function(){this.paused=!0},Fe.prototype.resume=function(){this.paused=!1,this.flush()},Fe.prototype.toSnapshot=function(){return{v:this.version,data:sS(this.data),type:this.type.uri}},Fe.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return iS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Fe.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=ef(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)},Fe.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=$o.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},Fe.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=$o.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)return this.emit("error",n)};var Hs={};Hs.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 wb=Ui,Bb=Hs.ACTIONS,hS=No,fS=Ln;function Ln(n,e,t,o,r,i,s){wb.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}wb.mixin(Ln),Ln.prototype.hasPending=function(){return!this.ready},Ln.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}},Ln.prototype.destroy=function(n){this.connection.canSend&&this.action===Bb.querySubscribe&&this.connection.send({a:Bb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&hS.nextTick(n)},Ln.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ln.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Ln.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Ln.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(h){if(h)return r._finishResponse(h,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 a=e[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Ln.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},Ln.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)},Ln.prototype._handleError=function(n){this.emit("error",n)},Ln.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)},Ln.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var Eb=Ui,mS=Hs.ACTIONS,gS=No,xb=fr;function fr(n,e){if(Eb.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={}}Eb.mixin(fr),fr.prototype.submit=function(n,e){this.value=n,this.send(e)},fr.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},fr.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()})},fr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},fr.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},fr.prototype._message=function(){return{a:mS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},fr.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},fr.prototype._callbackOrEmit=function(n,e){if(e)return gS.nextTick(e,n);n&&this.emit("error",n)};var pS=No,Ib=ap;function ap(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}ap.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},ap.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&pS.nextTick(n)};var up={exports:{}};(function(n,e){(function(t,o){o(e)})(hr,function(t){function o(w,T){T=T|0;for(var M=Math.max(w.length-T,0),F=Array(M),U=0;U<M;U++)F[U]=w[T+U];return F}var r=function(w){var T=o(arguments,1);return function(){var M=o(arguments);return w.apply(null,T.concat(M))}},i=function(w){return function(){var T=o(arguments),M=T.pop();w.call(this,T,M)}};function s(w){var T=typeof w;return w!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(w){setTimeout(w,0)}function h(w){return function(T){var M=o(arguments,1);w(function(){T.apply(null,M)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var C=h(p);function v(w){return i(function(T,M){var F;try{F=w.apply(this,T)}catch(U){return M(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(M,null,U)},function(U){B(M,U.message?U:new Error(U))}):M(null,F)})}function B(w,T,M){try{w(T,M)}catch(F){C(D,F)}}function D(w){throw w}var x=typeof Symbol=="function";function _(w){return x&&w[Symbol.toStringTag]==="AsyncFunction"}function R(w){return _(w)?v(w):w}function H(w){return function(T){var M=o(arguments,1),F=i(function(U,j){var G=this;return w(T,function(J,le){R(J).apply(G,U.concat(le))},j)});return M.length?F.apply(this,M):F}}var z=typeof hr=="object"&&hr&&hr.Object===Object&&hr,Q=typeof self=="object"&&self&&self.Object===Object&&self,ee=z||Q||Function("return this")(),fe=ee.Symbol,ve=Object.prototype,ze=ve.hasOwnProperty,He=ve.toString,Ke=fe?fe.toStringTag:void 0;function qt(w){var T=ze.call(w,Ke),M=w[Ke];try{w[Ke]=void 0;var F=!0}catch{}var U=He.call(w);return F&&(T?w[Ke]=M:delete w[Ke]),U}var Yn=Object.prototype,Ht=Yn.toString;function Rn(w){return Ht.call(w)}var Ir="[object Null]",kn="[object Undefined]",an=fe?fe.toStringTag:void 0;function Tr(w){return w==null?w===void 0?kn:Ir:an&&an in Object(w)?qt(w):Rn(w)}var ii="[object AsyncFunction]",Ao="[object Function]",oC="[object GeneratorFunction]",rC="[object Proxy]";function iC(w){if(!s(w))return!1;var T=Tr(w);return T==Ao||T==oC||T==ii||T==rC}var ns=9007199254740991;function nl(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=ns}function ol(w){return w!=null&&nl(w.length)&&!iC(w)}var si={};function Ne(){}function Dr(w){return function(){if(w!==null){var T=w;w=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Hc=function(w){return os&&w[os]&&w[os]()};function m1(w,T){for(var M=-1,F=Array(w);++M<w;)F[M]=T(M);return F}function un(w){return w!=null&&typeof w=="object"}var rl="[object Arguments]";function g1(w){return un(w)&&Tr(w)==rl}var bo=Object.prototype,p1=bo.hasOwnProperty,sC=bo.propertyIsEnumerable,il=g1(function(){return arguments}())?g1:function(w){return un(w)&&p1.call(w,"callee")&&!sC.call(w,"callee")},At=Array.isArray;function sl(){return!1}var ll=typeof t=="object"&&t&&!t.nodeType&&t,C1=ll&&!0&&n&&!n.nodeType&&n,cl=C1&&C1.exports===ll,A1=cl?ee.Buffer:void 0,al=A1?A1.isBuffer:void 0,rs=al||sl,Yu=9007199254740991,Ju=/^(?:0|[1-9]\d*)$/;function Ku(w,T){var M=typeof w;return T=T==null?Yu:T,!!T&&(M=="number"||M!="symbol"&&Ju.test(w))&&w>-1&&w%1==0&&w<T}var Xu="[object Arguments]",ed="[object Array]",td="[object Boolean]",nd="[object Date]",od="[object Error]",rd="[object Function]",lC="[object Map]",cC="[object Number]",aC="[object Object]",b1="[object RegExp]",v1="[object Set]",uC="[object String]",dC="[object WeakMap]",hC="[object ArrayBuffer]",fC="[object DataView]",y1="[object Float32Array]",mC="[object Float64Array]",gC="[object Int8Array]",pC="[object Int16Array]",id="[object Int32Array]",CC="[object Uint8Array]",sd="[object Uint8ClampedArray]",AC="[object Uint16Array]",bC="[object Uint32Array]",lt={};lt[y1]=lt[mC]=lt[gC]=lt[pC]=lt[id]=lt[CC]=lt[sd]=lt[AC]=lt[bC]=!0,lt[Xu]=lt[ed]=lt[hC]=lt[td]=lt[fC]=lt[nd]=lt[od]=lt[rd]=lt[lC]=lt[cC]=lt[aC]=lt[b1]=lt[v1]=lt[uC]=lt[dC]=!1;function vC(w){return un(w)&&nl(w.length)&&!!lt[Tr(w)]}function yC(w){return function(T){return w(T)}}var k1=typeof t=="object"&&t&&!t.nodeType&&t,ul=k1&&!0&&n&&!n.nodeType&&n,kC=ul&&ul.exports===k1,jc=kC&&z.process,w1=function(){try{var w=ul&&ul.require&&ul.require("util").types;return w||jc&&jc.binding&&jc.binding("util")}catch{}}(),B1=w1&&w1.isTypedArray,wC=B1?yC(B1):vC,BC=Object.prototype,EC=BC.hasOwnProperty;function xC(w,T){var M=At(w),F=!M&&il(w),U=!M&&!F&&rs(w),j=!M&&!F&&!U&&wC(w),G=M||F||U||j,J=G?m1(w.length,String):[],le=J.length;for(var pe in w)(T||EC.call(w,pe))&&!(G&&(pe=="length"||U&&(pe=="offset"||pe=="parent")||j&&(pe=="buffer"||pe=="byteLength"||pe=="byteOffset")||Ku(pe,le)))&&J.push(pe);return J}var Uc=Object.prototype;function IC(w){var T=w&&w.constructor,M=typeof T=="function"&&T.prototype||Uc;return w===M}function zc(w,T){return function(M){return w(T(M))}}var TC=zc(Object.keys,Object),DC=Object.prototype,SC=DC.hasOwnProperty;function E1(w){if(!IC(w))return TC(w);var T=[];for(var M in Object(w))SC.call(w,M)&&M!="constructor"&&T.push(M);return T}function Vc(w){return ol(w)?xC(w):E1(w)}function x1(w){var T=-1,M=w.length;return function(){return++T<M?{value:w[T],key:T}:null}}function LC(w){var T=-1;return function(){var F=w.next();return F.done?null:(T++,{value:F.value,key:T})}}function MC(w){var T=Vc(w),M=-1,F=T.length;return function U(){var j=T[++M];return j==="__proto__"?U():M<F?{value:w[j],key:j}:null}}function RC(w){if(ol(w))return x1(w);var T=Hc(w);return T?LC(T):MC(w)}function vo(w){return function(){if(w===null)throw new Error("Callback was already called.");var T=w;w=null,T.apply(this,arguments)}}function dl(w){return function(T,M,F){if(F=Dr(F||Ne),w<=0||!T)return F(null);var U=RC(T),j=!1,G=0,J=!1;function le(ae,Ae){if(G-=1,ae)j=!0,F(ae);else{if(Ae===si||j&&G<=0)return j=!0,F(null);J||pe()}}function pe(){for(J=!0;G<w&&!j;){var ae=U();if(ae===null){j=!0,G<=0&&F(null);return}G+=1,M(ae.value,ae.key,vo(le))}J=!1}pe()}}function Sr(w,T,M,F){dl(T)(w,R(M),F)}function jt(w,T){return function(M,F,U){return w(M,T,F,U)}}function ld(w,T,M){M=Dr(M||Ne);var F=0,U=0,j=w.length;j===0&&M(null);function G(J,le){J?M(J):(++U===j||le===si)&&M(null)}for(;F<j;F++)T(w[F],F,vo(G))}var OC=jt(Sr,1/0),Go=function(w,T,M){var F=ol(w)?ld:OC;F(w,R(T),M)};function Zo(w){return function(T,M,F){return w(Go,T,R(M),F)}}function cd(w,T,M,F){F=F||Ne,T=T||[];var U=[],j=0,G=R(M);w(T,function(J,le,pe){var ae=j++;G(J,function(Ae,Ze){U[ae]=Ze,pe(Ae)})},function(J){F(J,U)})}var Wc=Zo(cd),ad=H(Wc);function li(w){return function(T,M,F,U){return w(dl(M),T,R(F),U)}}var Lr=li(cd),ud=jt(Lr,1),dd=H(ud);function is(w,T){for(var M=-1,F=w==null?0:w.length;++M<F&&T(w[M],M,w)!==!1;);return w}function hd(w){return function(T,M,F){for(var U=-1,j=Object(T),G=F(T),J=G.length;J--;){var le=G[w?J:++U];if(M(j[le],le,j)===!1)break}return T}}var ss=hd();function ls(w,T){return w&&ss(w,T,Vc)}function I1(w,T,M,F){for(var U=w.length,j=M+(F?1:-1);F?j--:++j<U;)if(T(w[j],j,w))return j;return-1}function _C(w){return w!==w}function T1(w,T,M){for(var F=M-1,U=w.length;++F<U;)if(w[F]===T)return F;return-1}function hl(w,T,M){return T===T?T1(w,T,M):I1(w,_C,M)}var qc=function(w,T,M){typeof T=="function"&&(M=T,T=null),M=Dr(M||Ne);var F=Vc(w),U=F.length;if(!U)return M(null);T||(T=U);var j={},G=0,J=!1,le=Object.create(null),pe=[],ae=[],Ae={};ls(w,function(ht,rt){if(!At(ht)){Ze(rt,[ht]),ae.push(rt);return}var pt=ht.slice(0,ht.length-1),ko=pt.length;if(ko===0){Ze(rt,ht),ae.push(rt);return}Ae[rt]=ko,is(pt,function(E){if(!w[E])throw new Error("async.auto task `"+rt+"` has a non-existent dependency `"+E+"` in "+pt.join(", "));tn(E,function(){ko--,ko===0&&Ze(rt,ht)})})}),o3(),Dt();function Ze(ht,rt){pe.push(function(){yo(ht,rt)})}function Dt(){if(pe.length===0&&G===0)return M(null,j);for(;pe.length&&G<T;){var ht=pe.shift();ht()}}function tn(ht,rt){var pt=le[ht];pt||(pt=le[ht]=[]),pt.push(rt)}function Fn(ht){var rt=le[ht]||[];is(rt,function(pt){pt()}),Dt()}function yo(ht,rt){if(!J){var pt=vo(function(E,Or){if(G--,arguments.length>2&&(Or=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pe){ds[Pe]=Pn}),ds[ht]=Or,J=!0,le=Object.create(null),M(E,ds)}else j[ht]=Or,Fn(ht)});G++;var ko=R(rt[rt.length-1]);rt.length>1?ko(j,pt):ko(pt)}}function o3(){for(var ht,rt=0;ae.length;)ht=ae.pop(),rt++,is(r3(ht),function(pt){--Ae[pt]===0&&ae.push(pt)});if(rt!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function r3(ht){var rt=[];return ls(w,function(pt,ko){At(pt)&&hl(pt,ht,0)>=0&&rt.push(ko)}),rt}};function ci(w,T){for(var M=-1,F=w==null?0:w.length,U=Array(F);++M<F;)U[M]=T(w[M],M,w);return U}var FC="[object Symbol]";function PC(w){return typeof w=="symbol"||un(w)&&Tr(w)==FC}var NC=1/0,fd=fe?fe.prototype:void 0,D1=fd?fd.toString:void 0;function md(w){if(typeof w=="string")return w;if(At(w))return ci(w,md)+"";if(PC(w))return D1?D1.call(w):"";var T=w+"";return T=="0"&&1/w==-NC?"-0":T}function $C(w,T,M){var F=-1,U=w.length;T<0&&(T=-T>U?0:U+T),M=M>U?U:M,M<0&&(M+=U),U=T>M?0:M-T>>>0,T>>>=0;for(var j=Array(U);++F<U;)j[F]=w[F+T];return j}function HC(w,T,M){var F=w.length;return M=M===void 0?F:M,!T&&M>=F?w:$C(w,T,M)}function gd(w,T){for(var M=w.length;M--&&hl(T,w[M],0)>-1;);return M}function jC(w,T){for(var M=-1,F=w.length;++M<F&&hl(T,w[M],0)>-1;);return M}function UC(w){return w.split("")}var zC="\\ud800-\\udfff",VC="\\u0300-\\u036f",WC="\\ufe20-\\ufe2f",ct="\\u20d0-\\u20ff",ot=VC+WC+ct,qC="\\ufe0e\\ufe0f",GC="\\u200d",ZC=RegExp("["+GC+zC+ot+qC+"]");function QC(w){return ZC.test(w)}var S1="\\ud800-\\udfff",YC="\\u0300-\\u036f",L1="\\ufe20-\\ufe2f",JC="\\u20d0-\\u20ff",Gt=YC+L1+JC,pd="\\ufe0e\\ufe0f",ai="["+S1+"]",Gc="["+Gt+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+Gc+"|"+fl+")",Cd="[^"+S1+"]",Ad="(?:\\ud83c[\\udde6-\\uddff]){2}",bd="[\\ud800-\\udbff][\\udc00-\\udfff]",M1="\\u200d",vd=On+"?",yd="["+pd+"]?",wn="(?:"+M1+"(?:"+[Cd,Ad,bd].join("|")+")"+yd+vd+")*",KC=yd+vd+wn,_n="(?:"+[Cd+Gc+"?",Gc,Ad,bd,ai].join("|")+")",XC=RegExp(fl+"(?="+fl+")|"+_n+KC,"g");function R1(w){return w.match(XC)||[]}function Qo(w){return QC(w)?R1(w):UC(w)}function Zc(w){return w==null?"":md(w)}var kd=/^\s+|\s+$/g;function dt(w,T,M){if(w=Zc(w),w&&(M||T===void 0))return w.replace(kd,"");if(!w||!(T=md(T)))return w;var F=Qo(w),U=Qo(T),j=jC(F,U),G=gd(F,U)+1;return HC(F,j,G).join("")}var Mr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,wd=/,/,e3=/(=.+)?(\s*)$/,Bd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function t3(w){return w=w.toString().replace(Bd,""),w=w.match(Mr)[2].replace(" ",""),w=w?w.split(wd):[],w=w.map(function(T){return dt(T.replace(e3,""))}),w}function O1(w,T){var M={};ls(w,function(F,U){var j,G=_(F),J=!G&&F.length===1||G&&F.length===0;if(At(F))j=F.slice(0,-1),F=F[F.length-1],M[U]=j.concat(j.length>0?le:F);else if(J)M[U]=F;else{if(j=t3(F),F.length===0&&!G&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");G||j.pop(),M[U]=j.concat(le)}function le(pe,ae){var Ae=ci(j,function(Ze){return pe[Ze]});Ae.push(ae),R(F).apply(null,Ae)}}),qc(M,T)}function Jn(){this.head=this.tail=null,this.length=0}function Ed(w,T){w.length=1,w.head=w.tail=T}Jn.prototype.removeLink=function(w){return w.prev?w.prev.next=w.next:this.head=w.next,w.next?w.next.prev=w.prev:this.tail=w.prev,w.prev=w.next=null,this.length-=1,w},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.prototype.insertAfter=function(w,T){T.prev=w,T.next=w.next,w.next?w.next.prev=T:this.tail=T,w.next=T,this.length+=1},Jn.prototype.insertBefore=function(w,T){T.prev=w.prev,T.next=w,w.prev?w.prev.next=T:this.head=T,w.prev=T,this.length+=1},Jn.prototype.unshift=function(w){this.head?this.insertBefore(this.head,w):Ed(this,w)},Jn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):Ed(this,w)},Jn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Jn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Jn.prototype.toArray=function(){for(var w=Array(this.length),T=this.head,M=0;M<this.length;M++)w[M]=T.data,T=T.next;return w},Jn.prototype.remove=function(w){for(var T=this.head;T;){var M=T.next;w(T)&&this.removeLink(T),T=M}return this};function ml(w,T,M){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=R(w),U=0,j=[],G=!1;function J(Ae,Ze,Dt){if(Dt!=null&&typeof Dt!="function")throw new Error("task callback must be a function");if(ae.started=!0,At(Ae)||(Ae=[Ae]),Ae.length===0&&ae.idle())return C(function(){ae.drain()});for(var tn=0,Fn=Ae.length;tn<Fn;tn++){var yo={data:Ae[tn],callback:Dt||Ne};Ze?ae._tasks.unshift(yo):ae._tasks.push(yo)}G||(G=!0,C(function(){G=!1,ae.process()}))}function le(Ae){return function(Ze){U-=1;for(var Dt=0,tn=Ae.length;Dt<tn;Dt++){var Fn=Ae[Dt],yo=hl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Ze!=null&&ae.error(Ze,Fn.data)}U<=ae.concurrency-ae.buffer&&ae.unsaturated(),ae.idle()&&ae.drain(),ae.process()}}var pe=!1,ae={_tasks:new Jn,concurrency:T,payload:M,saturated:Ne,unsaturated:Ne,buffer:T/4,empty:Ne,drain:Ne,error:Ne,started:!1,paused:!1,push:function(Ae,Ze){J(Ae,!1,Ze)},kill:function(){ae.drain=Ne,ae._tasks.empty()},unshift:function(Ae,Ze){J(Ae,!0,Ze)},remove:function(Ae){ae._tasks.remove(Ae)},process:function(){if(!pe){for(pe=!0;!ae.paused&&U<ae.concurrency&&ae._tasks.length;){var Ae=[],Ze=[],Dt=ae._tasks.length;ae.payload&&(Dt=Math.min(Dt,ae.payload));for(var tn=0;tn<Dt;tn++){var Fn=ae._tasks.shift();Ae.push(Fn),j.push(Fn),Ze.push(Fn.data)}U+=1,ae._tasks.length===0&&ae.empty(),U===ae.concurrency&&ae.saturated();var yo=vo(le(Ae));F(Ze,yo)}pe=!1}},length:function(){return ae._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ae._tasks.length+U===0},pause:function(){ae.paused=!0},resume:function(){ae.paused!==!1&&(ae.paused=!1,C(ae.process))}};return ae}function ui(w,T){return ml(w,1,T)}var cs=jt(Sr,1);function Yo(w,T,M,F){F=Dr(F||Ne);var U=R(M);cs(w,function(j,G,J){U(T,j,function(le,pe){T=pe,J(le)})},function(j){F(j,T)})}function Qc(){var w=ci(arguments,R);return function(){var T=o(arguments),M=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Ne,Yo(w,T,function(U,j,G){j.apply(M,U.concat(function(J){var le=o(arguments,1);G(J,le)}))},function(U,j){F.apply(M,[U].concat(j))})}}var Yc=function(){return Qc.apply(null,o(arguments).reverse())},xd=Array.prototype.concat,gl=function(w,T,M,F){F=F||Ne;var U=R(M);Lr(w,T,function(j,G){U(j,function(J){return J?G(J):G(null,o(arguments,1))})},function(j,G){for(var J=[],le=0;le<G.length;le++)G[le]&&(J=xd.apply(J,G[le]));return F(j,J)})},_1=jt(gl,1/0),Jc=jt(gl,1),Kc=function(){var w=o(arguments),T=[null].concat(w);return function(){var M=arguments[arguments.length-1];return M.apply(this,T)}};function pl(w){return w}function di(w,T){return function(M,F,U,j){j=j||Ne;var G=!1,J;M(F,function(le,pe,ae){U(le,function(Ae,Ze){Ae?ae(Ae):w(Ze)&&!J?(G=!0,J=T(!0,le),ae(null,si)):ae()})},function(le){le?j(le):j(null,G?J:T(!1))})}}function dn(w,T){return T}var as=Zo(di(pl,dn)),Jo=li(di(pl,dn)),Cl=jt(Jo,1);function Id(w){return function(T){var M=o(arguments,1);M.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[w]&&is(U,function(j){console[w](j)}))}),R(T).apply(null,M)}}var F1=Id("dir");function P1(w,T,M){M=vo(M||Ne);var F=R(w),U=R(T);function j(J){if(J)return M(J);var le=o(arguments,1);le.push(G),U.apply(this,le)}function G(J,le){if(J)return M(J);if(!le)return M(null);F(j)}G(null,!0)}function Td(w,T,M){M=vo(M||Ne);var F=R(w),U=function(j){if(j)return M(j);var G=o(arguments,1);if(T.apply(this,G))return F(U);M.apply(null,[null].concat(G))};F(U)}function N1(w,T,M){Td(w,function(){return!T.apply(this,arguments)},M)}function $1(w,T,M){M=vo(M||Ne);var F=R(T),U=R(w);function j(J){if(J)return M(J);U(G)}function G(J,le){if(J)return M(J);if(!le)return M(null);F(j)}U(G)}function hi(w){return function(T,M,F){return w(T,F)}}function Xc(w,T,M){Go(w,hi(R(T)),M)}function Al(w,T,M,F){dl(T)(w,hi(R(M)),F)}var fi=jt(Al,1);function ea(w){return _(w)?w:i(function(T,M){var F=!0;T.push(function(){var U=arguments;F?C(function(){M.apply(null,U)}):M.apply(null,U)}),w.apply(this,T),F=!1})}function Kn(w){return!w}var mi=Zo(di(Kn,Kn)),bl=li(di(Kn,Kn)),ta=jt(bl,1);function H1(w){return function(T){return T==null?void 0:T[w]}}function us(w,T,M,F){var U=new Array(T.length);w(T,function(j,G,J){M(j,function(le,pe){U[G]=!!pe,J(le)})},function(j){if(j)return F(j);for(var G=[],J=0;J<T.length;J++)U[J]&&G.push(T[J]);F(null,G)})}function Xn(w,T,M,F){var U=[];w(T,function(j,G,J){M(j,function(le,pe){le?J(le):(pe&&U.push({index:G,value:j}),J())})},function(j){j?F(j):F(null,ci(U.sort(function(G,J){return G.index-J.index}),H1("value")))})}function na(w,T,M,F){var U=ol(T)?us:Xn;U(w,T,R(M),F||Ne)}var oa=Zo(na),vl=li(na),ra=jt(vl,1);function j1(w,T){var M=vo(T||Ne),F=R(ea(w));function U(j){if(j)return M(j);F(U)}U()}var ia=function(w,T,M,F){F=F||Ne;var U=R(M);Lr(w,T,function(j,G){U(j,function(J,le){return J?G(J):G(null,{key:le,val:j})})},function(j,G){for(var J={},le=Object.prototype.hasOwnProperty,pe=0;pe<G.length;pe++)if(G[pe]){var ae=G[pe].key,Ae=G[pe].val;le.call(J,ae)?J[ae].push(Ae):J[ae]=[Ae]}return F(j,J)})},gi=jt(ia,1/0),N=jt(ia,1),q=Id("log");function V(w,T,M,F){F=Dr(F||Ne);var U={},j=R(M);Sr(w,T,function(G,J,le){j(G,J,function(pe,ae){if(pe)return le(pe);U[J]=ae,le()})},function(G){F(G,U)})}var he=jt(V,1/0),Ee=jt(V,1);function Ve(w,T){return T in w}function Bt(w,T){var M=Object.create(null),F=Object.create(null);T=T||pl;var U=R(w),j=i(function(J,le){var pe=T.apply(null,J);Ve(M,pe)?C(function(){le.apply(null,M[pe])}):Ve(F,pe)?F[pe].push(le):(F[pe]=[le],U.apply(null,J.concat(function(){var ae=o(arguments);M[pe]=ae;var Ae=F[pe];delete F[pe];for(var Ze=0,Dt=Ae.length;Ze<Dt;Ze++)Ae[Ze].apply(null,ae)})))});return j.memo=M,j.unmemoized=w,j}var qe;a?qe=process.nextTick:l?qe=setImmediate:qe=d;var sa=h(qe);function Dd(w,T,M){M=M||Ne;var F=ol(T)?[]:{};w(T,function(U,j,G){R(U)(function(J,le){arguments.length>2&&(le=o(arguments,1)),F[j]=le,G(J)})},function(U){M(U,F)})}function Bn(w,T){Dd(Go,w,T)}function yl(w,T,M){Dd(dl(T),w,M)}var Sd=function(w,T){var M=R(w);return ml(function(F,U){M(F[0],U)},T,1)},pi=function(w,T){var M=Sd(w,T);return M.push=function(F,U,j){if(j==null&&(j=Ne),typeof j!="function")throw new Error("task callback must be a function");if(M.started=!0,At(F)||(F=[F]),F.length===0)return C(function(){M.drain()});U=U||0;for(var G=M._tasks.head;G&&U>=G.priority;)G=G.next;for(var J=0,le=F.length;J<le;J++){var pe={data:F[J],priority:U,callback:j};G?M._tasks.insertBefore(G,pe):M._tasks.push(pe)}C(M.process)},delete M.unshift,M};function kl(w,T){if(T=Dr(T||Ne),!At(w))return T(new TypeError("First argument to race must be an array of functions"));if(!w.length)return T();for(var M=0,F=w.length;M<F;M++)R(w[M])(T)}function Ci(w,T,M,F){var U=o(w).reverse();Yo(U,T,M,F)}function We(w){var T=R(w);return i(function(F,U){return F.push(function(G,J){if(G)U(null,{error:G});else{var le;arguments.length<=2?le=J:le=o(arguments,1),U(null,{value:le})}}),T.apply(this,F)})}function U1(w){var T;return At(w)?T=ci(w,We):(T={},ls(w,function(M,F){T[F]=We.call(this,M)})),T}function Ld(w,T,M,F){na(w,T,function(U,j){M(U,function(G,J){j(G,!J)})},F)}var wl=Zo(Ld),Md=li(Ld),z1=jt(Md,1);function V1(w){return function(){return w}}function Ai(w,T,M){var F=5,U=0,j={times:F,intervalFunc:V1(U)};function G(ae,Ae){if(typeof Ae=="object")ae.times=+Ae.times||F,ae.intervalFunc=typeof Ae.interval=="function"?Ae.interval:V1(+Ae.interval||U),ae.errorFilter=Ae.errorFilter;else if(typeof Ae=="number"||typeof Ae=="string")ae.times=+Ae||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof w=="function"?(M=T||Ne,T=w):(G(j,w),M=M||Ne),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=R(T),le=1;function pe(){J(function(ae){ae&&le++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ae))?setTimeout(pe,j.intervalFunc(le)):M.apply(null,arguments)})}pe()}var Ko=function(w,T){T||(T=w,w=null);var M=R(T);return i(function(F,U){function j(G){M.apply(null,F.concat(G))}w?Ai(w,j,U):Ai(j,U)})};function Bl(w,T){Dd(cs,w,T)}var El=Zo(di(Boolean,pl)),Rr=li(di(Boolean,pl)),xl=jt(Rr,1);function Rd(w,T,M){var F=R(T);Wc(w,function(j,G){F(j,function(J,le){if(J)return G(J);G(null,{value:j,criteria:le})})},function(j,G){if(j)return M(j);M(null,ci(G.sort(U),H1("value")))});function U(j,G){var J=j.criteria,le=G.criteria;return J<le?-1:J>le?1:0}}function Il(w,T,M){var F=R(w);return i(function(U,j){var G=!1,J;function le(){var pe=w.name||"anonymous",ae=new Error('Callback function "'+pe+'" timed out.');ae.code="ETIMEDOUT",M&&(ae.info=M),G=!0,j(ae)}U.push(function(){G||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(le,T),F.apply(null,U)})}var W1=Math.ceil,Tl=Math.max;function bi(w,T,M,F){for(var U=-1,j=Tl(W1((T-w)/(M||1)),0),G=Array(j);j--;)G[F?j:++U]=w,w+=M;return G}function vi(w,T,M,F){var U=R(M);Lr(bi(0,w,1),T,U,F)}var q1=jt(vi,1/0),G1=jt(vi,1);function Z1(w,T,M,F){arguments.length<=3&&(F=M,M=T,T=At(w)?[]:{}),F=Dr(F||Ne);var U=R(M);Go(w,function(j,G,J){U(T,j,G,J)},function(j){F(j,T)})}function Dl(w,T){var M=null,F;T=T||Ne,fi(w,function(U,j){R(U)(function(G,J){arguments.length>2?F=o(arguments,1):F=J,M=G,j(!G)})},function(){T(M,F)})}function Sl(w){return function(){return(w.unmemoized||w).apply(null,arguments)}}function Ll(w,T,M){M=vo(M||Ne);var F=R(T);if(!w())return M(null);var U=function(j){if(j)return M(j);if(w())return F(U);var G=o(arguments,1);M.apply(null,[null].concat(G))};F(U)}function Q1(w,T,M){Ll(function(){return!w.apply(this,arguments)},T,M)}var Od=function(w,T){if(T=Dr(T||Ne),!At(w))return T(new Error("First argument to waterfall must be an array of functions"));if(!w.length)return T();var M=0;function F(j){var G=R(w[M++]);j.push(vo(U)),G.apply(null,j)}function U(j){if(j||M===w.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},n3={apply:r,applyEach:ad,applyEachSeries:dd,asyncify:v,auto:qc,autoInject:O1,cargo:ui,compose:Yc,concat:_1,concatLimit:gl,concatSeries:Jc,constant:Kc,detect:as,detectLimit:Jo,detectSeries:Cl,dir:F1,doDuring:P1,doUntil:N1,doWhilst:Td,during:$1,each:Xc,eachLimit:Al,eachOf:Go,eachOfLimit:Sr,eachOfSeries:cs,eachSeries:fi,ensureAsync:ea,every:mi,everyLimit:bl,everySeries:ta,filter:oa,filterLimit:vl,filterSeries:ra,forever:j1,groupBy:gi,groupByLimit:ia,groupBySeries:N,log:q,map:Wc,mapLimit:Lr,mapSeries:ud,mapValues:he,mapValuesLimit:V,mapValuesSeries:Ee,memoize:Bt,nextTick:sa,parallel:Bn,parallelLimit:yl,priorityQueue:pi,queue:Sd,race:kl,reduce:Yo,reduceRight:Ci,reflect:We,reflectAll:U1,reject:wl,rejectLimit:Md,rejectSeries:z1,retry:Ai,retryable:Ko,seq:Qc,series:Bl,setImmediate:C,some:El,someLimit:Rr,someSeries:xl,sortBy:Rd,timeout:Il,times:q1,timesLimit:vi,timesSeries:G1,transform:Z1,tryEach:Dl,unmemoize:Sl,until:Q1,waterfall:Od,whilst:Ll,all:mi,allLimit:bl,allSeries:ta,any:El,anyLimit:Rr,anySeries:xl,find:as,findLimit:Jo,findSeries:Cl,forEach:Xc,forEachSeries:fi,forEachLimit:Al,forEachOf:Go,forEachOfSeries:cs,forEachOfLimit:Sr,inject:Yo,foldl:Yo,foldr:Ci,select:oa,selectLimit:vl,selectSeries:ra,wrapSync:v};t.default=n3,t.apply=r,t.applyEach=ad,t.applyEachSeries=dd,t.asyncify=v,t.auto=qc,t.autoInject=O1,t.cargo=ui,t.compose=Yc,t.concat=_1,t.concatLimit=gl,t.concatSeries=Jc,t.constant=Kc,t.detect=as,t.detectLimit=Jo,t.detectSeries=Cl,t.dir=F1,t.doDuring=P1,t.doUntil=N1,t.doWhilst=Td,t.during=$1,t.each=Xc,t.eachLimit=Al,t.eachOf=Go,t.eachOfLimit=Sr,t.eachOfSeries=cs,t.eachSeries=fi,t.ensureAsync=ea,t.every=mi,t.everyLimit=bl,t.everySeries=ta,t.filter=oa,t.filterLimit=vl,t.filterSeries=ra,t.forever=j1,t.groupBy=gi,t.groupByLimit=ia,t.groupBySeries=N,t.log=q,t.map=Wc,t.mapLimit=Lr,t.mapSeries=ud,t.mapValues=he,t.mapValuesLimit=V,t.mapValuesSeries=Ee,t.memoize=Bt,t.nextTick=sa,t.parallel=Bn,t.parallelLimit=yl,t.priorityQueue=pi,t.queue=Sd,t.race=kl,t.reduce=Yo,t.reduceRight=Ci,t.reflect=We,t.reflectAll=U1,t.reject=wl,t.rejectLimit=Md,t.rejectSeries=z1,t.retry=Ai,t.retryable=Ko,t.seq=Qc,t.series=Bl,t.setImmediate=C,t.some=El,t.someLimit=Rr,t.someSeries=xl,t.sortBy=Rd,t.timeout=Il,t.times=q1,t.timesLimit=vi,t.timesSeries=G1,t.transform=Z1,t.tryEach=Dl,t.unmemoize=Sl,t.until=Q1,t.waterfall=Od,t.whilst=Ll,t.all=mi,t.allLimit=bl,t.allSeries=ta,t.any=El,t.anyLimit=Rr,t.anySeries=xl,t.find=as,t.findLimit=Jo,t.findSeries=Cl,t.forEach=Xc,t.forEachSeries=fi,t.forEachLimit=Al,t.forEachOf=Go,t.forEachOfSeries=cs,t.forEachOfLimit=Sr,t.inject=Yo,t.foldl=Yo,t.foldr=Ci,t.select=oa,t.selectLimit=vl,t.selectSeries=ra,t.wrapSync=v,Object.defineProperty(t,"__esModule",{value:!0})})})(up,up.exports);var Tb={exports:{}},dp=Tb.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 a=parseInt(i,e);return a!==1/0&&a>=Math.pow(2,n)?dp(n,e):i};dp.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=dp(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 Db=Ui,CS=xb,AS=Ib,tf=No,hp=up.exports,bS=Tb.exports,Sb=Hs.ACTIONS,Lb=Rt;function Rt(n,e){if(Db.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}Db.mixin(Rt),Rt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Rt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Rt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||bS();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},Rt.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);hp.parallel([function(i){hp.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();hp.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)})})},Rt.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?Sb.presenceSubscribe:Sb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},Rt.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Rt.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},Rt.prototype._receiveUpdate=function(n,e){var t=tf.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=tf.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},Rt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Rt.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()}},Rt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Rt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Rt.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)})},Rt.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},Rt.prototype._callbackOrEmit=function(n,e){if(e)return tf.nextTick(e,n);n&&this.emit("error",n)},Rt.prototype._createLocalPresence=function(n){return new CS(this,n)},Rt.prototype._createRemotePresence=function(n){return new AS(this,n)},Rt.prototype._callEachOrEmit=function(n,e){var t=tf.callEach(n,e);!t&&e&&this.emit("error",e)};var Ka=xb,Mb=Yh,vS=No,Rb=Mb.CODES,yS=Ho;function Ho(n,e){Ka.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()}Ho.prototype=Object.create(Ka.prototype),Ho.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:Rb.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,Ka.prototype.submit.call(this,n,e)},Ho.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),Ka.prototype.destroy.call(this,n)},Ho.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={})})}},Ho.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)},Ho.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)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.prototype._message=function(){var n=Ka.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Ho.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!vS.supportsPresence(o))throw new Mb(Rb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var Ob={};(function(n){var e=Qa,t=Yh,o=No,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 a=l.create.type;if(typeof a!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=e.map[a];if(d==null||typeof d!="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,a){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=e.map[d.type];if(!h)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(C){return C}}else if(a.del)l.data=void 0,l.type=null,l.v++;else if("op"in a){var p=i(l,a.op);if(p)return p;l.v++}else l.v++};function i(l,a){if(!l.type)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=e.map[l.type];if(!d)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new t(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new t(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){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{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var C=n.apply(l,p);if(C)return C}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=e.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(C){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:C.message||C}}l.v++};function s(l,a){if(l.type===e.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var C=d[p];typeof C.lm=="string"&&(C.lm=+C.lm);for(var v=C.p,B=h,D=0;D<v.length;D++){var x=v[D];Object.prototype.toString.call(B)=="[object Array]"?v[D]=+x:B.constructor===Object&&(v[D]=x.toString()),B=B[x]}p<d.length-1&&(h=e.defaultType.apply(h,[C]))}}}}})(Ob);var Xa=Ib,kS=Ob,wS=ho;function ho(n,e){Xa.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()}ho.prototype=Object.create(Xa.prototype),ho.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ho.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),Xa.prototype.destroy.call(this,n)},ho.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)},ho.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))}})}},ho.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Xa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Xa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ho.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)}},ho.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++):kS.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ho.prototype._startCachingOps=function(){this._opCache=[]},ho.prototype._stopCachingOps=function(){this._opCache=null},ho.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var _b=Lb,BS=yS,ES=wS;function nc(n,e,t){var o=nc.channel(e,t);_b.call(this,n,o),this.collection=e,this.id=t}var xS=nc;nc.prototype=Object.create(_b.prototype),nc.channel=function(n,e){return n+"."+e},nc.prototype._createLocalPresence=function(n){return new BS(this,n)},nc.prototype._createRemotePresence=function(n){return new ES(this,n)};var IS=TS;function TS(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var DS=IS,Fb=Ui,Pb=eu;function eu(n,e,t,o,r){if(Fb.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}Fb.mixin(eu),eu.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},eu.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},eu.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new DS(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var Nb=Pb,SS=No,LS=Hs.ACTIONS,MS=fp;function fp(n,e,t,o,r,i){if(Nb.call(this,n,e,t,o,i),!SS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}fp.prototype=Object.create(Nb.prototype),fp.prototype._message=function(){return{a:LS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var $b=Pb,RS=No,OS=Hs.ACTIONS,_S=mp;function mp(n,e,t,o,r,i){if($b.call(this,n,e,t,o,i),!RS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}mp.prototype=Object.create($b.prototype),mp.prototype._message=function(){return{a:OS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var FS=cS,PS=fS,NS=Lb,Hb=xS,$S=MS,HS=_S,jb=Ui,oc=Yh,nt=Hs.ACTIONS,Ub=Qa,jo=No,tu=Cb,nu=oc.CODES;function zb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var jS=Be;function Be(n){jb.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=zb(n),this.bindToSocket(n)}jb.mixin(Be),Be.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=zb(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{tu.warn("Failed to parse message",o);return}t.debug&&tu.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){jo.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)}},Be.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=Vb(n.error,n),delete n.error),n.a){case nt.initLegacy:return this._handleLegacyInit(n);case nt.handshake:return this._handleHandshake(e,n);case nt.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case nt.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case nt.queryUnsubscribe:return;case nt.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 nt.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case nt.bulkSubscribe:case nt.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case nt.snapshotFetch:case nt.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case nt.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case nt.subscribe:case nt.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case nt.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case nt.presence:return this._handlePresence(e,n);case nt.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case nt.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case nt.presenceRequest:return this._handlePresenceRequest(e,n);case nt.pingPong:return this._handlePingPong(e);default:tu.warn("Ignoring unrecognized message",n)}};function Vb(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}Be.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](Vb(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 tu.error("Invalid bulk message",e)},Be.prototype._reset=function(){this.agent=null},Be.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 oc(nu.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 a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,e),this.emit("state",n,e)}},Be.prototype.startBulk=function(){this.bulk||(this.bulk={})},Be.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},Be.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var a=t[l];a==null?o.push(l):(r[l]=a,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 d=r[s];this.send({a:n,c:e,d:s,v:d})}else i&&this.send({a:"b"+n,c:e,b:r})}},Be.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)}},Be.prototype.sendFetch=function(n){return this._sendActions(nt.fetch,n,n.version)},Be.prototype.sendSubscribe=function(n){return this._sendActions(nt.subscribe,n,n.version)},Be.prototype.sendUnsubscribe=function(n){return this._sendActions(nt.unsubscribe,n)},Be.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:nt.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)},Be.prototype.send=function(n){this.debug&&tu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Be.prototype.ping=function(){if(!this.canSend)throw new oc(nu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:nt.pingPong};this.send(n)},Be.prototype.close=function(){this.socket.close()},Be.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},Be.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new FS(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},Be.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Be.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},Be.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new PS(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},Be.prototype._destroyQuery=function(n){delete this.queries[n.id]},Be.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(nt.queryFetch,n,e,t,o)},Be.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(nt.querySubscribe,n,e,t,o)},Be.prototype.hasPending=function(){return!!(this._firstDoc(nf)||this._firstQuery(nf)||this._firstSnapshotRequest())};function nf(n){return n.hasPending()}Be.prototype.hasWritePending=function(){return!!this._firstDoc(US)};function US(n){return n.hasWritePending()}Be.prototype.whenNothingPending=function(n){var e=this._firstDoc(nf);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(nf);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},Be.prototype._nothingPendingRetry=function(n){var e=this;return function(){jo.nextTick(function(){e.whenNothingPending(n)})}},Be.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}}},Be.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},Be.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Be.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new $S(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},Be.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new HS(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},Be.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},Be.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Be.prototype._initializeHandshake=function(){this.send({a:nt.handshake,id:this.id})},Be.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},Be.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Be.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new oc(nu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Ub.map[n.type]!==Ub.defaultType)return this.emit("error",new oc(nu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new oc(nu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Be.prototype.getPresence=function(n){var e=this,t=jo.digOrCreate(this._presences,n,function(){return new NS(e,n)});return t._wantsDestroy=!1,t},Be.prototype.getDocPresence=function(n,e){var t=Hb.channel(n,e),o=this,r=jo.digOrCreate(this._presences,t,function(){return new Hb(o,n,e)});return r._wantsDestroy=!1,r},Be.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},Be.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},Be.prototype._handlePresenceSubscribe=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},Be.prototype._handlePresenceUnsubscribe=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},Be.prototype._handlePresence=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},Be.prototype._handlePresenceRequest=function(n,e){var t=jo.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var Wb=jS,zS=Qa;const of={err:1001,msg:"user auth error",name:"AuthError"},VS={err:1002,msg:"you don't have required permission",name:"PermissionError"},gp={err:1003,msg:"Too many user connected",name:"MaxUserError"},ou={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},WS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},qS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},ru="x-live-editor-token",rf="x-live-editor-base-url",Cn=S("auth-connection");function GS(n){try{n()}catch(e){Cn.error(e)}}class ZS{constructor(e,t){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new Q3.EventEmitter);m(this,"token",null);m(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 Mi(this.getBaseURL())}async auth(e){g(Cn,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[ru]:e.token,[rf]: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:{[rf]:Mi(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new jB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Wb.prototype),g(Cn,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}}},Wb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Cn.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){Cn.error(e),setTimeout(()=>this.handleAuthError(),0)}}else Cn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error(of.msg);e.code=of.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(ou.msg);e.code=ou.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===of.err)Cn.warn("auth error"),this.handleAuthError();else if(o===gp.err)Cn.warn(gp.msg),this.emitMaxUsersError();else if(o===ou.err){Cn.warn(ou.msg);try{this.emitRequestReloadError()}catch(r){Cn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Cn.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return g(Cn,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(g(Cn,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){g(Cn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){g(Cn,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(),GS(()=>{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()}}S("utils/file");function QS(){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}QS();async function YS(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new UB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>t&&(a=t);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Mi(i)}const mr=S("sharedb-doc/client");class JS{constructor(e,t,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(mr,!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),mr.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;zS.register(Wd.type),this.connection=new ZS(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return g(mr,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 a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[ru]: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=v=>{mr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await YS(t),d=await this.getFileUrlByHash(e,a,t.name,t.size,o);if(d)return r(-1),d;let h=e;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${t.size}`),p.append("file-hash",a),p.append("file",t,t.name);const C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return mr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;g(mr,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[ru]:this.connection.token},t,o);return g(mr,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 a=t||{};a.url=e,a.headers||(a.headers={}),g(mr,o,"no token"),a.headers={...a.headers,[ru]:o,[rf]:this.connection.getBase64BaseURL()};try{return await $B.default(e,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(mr,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions?withExtra=true`,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=HB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(mr,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,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/${Mi(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 KS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const pp=S("block-ids");class XS{constructor(){m(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);g(pp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();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);g(pp,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=K(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class eL{constructor(){m(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new XS,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 g(pp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class qb{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 Cp=S("op-parse-handler");class tL{constructor(e,t){m(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 eL,i=e.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Cp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;t.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,a=`${l.containerId}-${l.blockIndex}`;if(t.has(a)){Cp.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new qb,o.set(d,h)),h.delete(l.key)}else g(Cp,!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,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new qb,o.set(a,d)),d.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:a,blockIndex:d}=r.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Ot=S("op-parser");class Gb{}class Ap{constructor(e){m(this,"key");this.key=e}}function nL(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 a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Ot,s.id,"block id is required"),g(Ot,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return t.onInsertBlock(n,r,s),!0}function bp(n,e,t,o){if(t==="upsert"&&nL(n,e,o))return;g(Ot,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 a=r[1];if(g(Ot,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),g(Ot,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Ot,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Ot,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Ot,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Ot,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&t==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&t==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&t==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else t==="remove"&&d.r&&s.push(new Ap(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;t==="remove"&&a.r&&s.push(new Gb),t==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Ot,typeof l=="string","data is not string"),g(Ot,l!=="text","data !== 'text'"),g(Ot,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];t==="remove"&&d.r&&s.push(new Ap(a)),t==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Gb?o.onDeleteBlock(n,i):l instanceof Ap?o.onDeleteBlockData(n,i,l.key):g(Ot,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function oL(n,e,t){Ot.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function rL(n,e,t){const o=n[1],r=n[2];g(Ot,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Ot,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Ot.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):Ot.error(`unknown comment op, ${JSON.stringify(n)}`)}function vp(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{vp(s,e,t)});return}const r=o;if(g(Ot,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){oL(n);return}if(r==="comments"){rL(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{bp(i,s,e,t)}):n.slice(1).forEach(s=>{bp(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 g(Ot,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),bp(i,n.slice(1),e,t)}function Zb(n,e,t){const o=new tL(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=me.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{vp(a,i,o)}):vp(s,i,o)}o.end()}const iL=S("sharedb-comments");function yp(n){const e=n.blocks;g(iL,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)}),me.default(t)}function Qb(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function kp(n,e){const t=zD(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},a=me.default(l);return delete a.children,a}const st=S("sharedb-doc/doc-container"),Yb="ot-json1";Wd.type.registerSubtype(VD.type),Wd.type.name=Yb,Wd.type.invert=null;class iu extends pa{constructor(t,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new jD);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});m(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()});m(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});m(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,a])=>{if(!fa.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){st.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(st.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),st.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(st.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));m(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,Yb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async t=>{if(t.length===0)return Promise.resolve();const o=t.map(({containerId:r,blocks:i})=>[ji(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async t=>{const o=[ji(t),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(t,o,r)=>{const i=[ji(t),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(t,o)=>{const r=[ji(t),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ji(t),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(t,o,r)=>{const i=[ji(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(t,o,r)=>{if(this.destroyed){st.warn("handleOp: destroyed");return}try{Zb(t,this,!!o)}catch(i){throw st.error(i),i}});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--,g(st,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new JS(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new iu(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||KS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw st.error(o),st.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(K()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return Za(this.data())}getContainerBlocks(t){const o=this.data();g(st,o,"no doc data");const r=o[ji(t)];return g(st,r,`no container data: ${t}`),me.default(r)}getBlockData(t,o){const r=this.data();g(st,r,"no doc data");const i=r[ji(t)];g(st,i,`no container data: ${t}`);const s=i[o];return g(st,s,`no block data: ${o}`),me.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);g(st,i.text,"no block text");const s=me.default(i.text);this.submitUpdateRichText(t,o,r);const l=ln.apply(s,r);return g(st,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=me.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainers(t){this.submitInsertChildContainers(t)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Qb(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return yp(o)}localCreateComment(t,o){const r=kp(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=kp(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){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,tc(t),o,r)})}onInsertBlock(t,o,r,i){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,tc(t),o,r,i)})}onUpdateBlockData(t,o,r,i){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,tc(t),o,r,i)})}onUpdateBlockText(t,o,r,i){g(st,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,tc(t),o,r,i)})}onDeleteContainer(t,o){g(st,this.callbacks.length>0,"no callbacks"),g(st,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,tc(t),o)})}onCreateContainer(t,o,r){g(st,this.callbacks.length>0,"no callbacks"),g(st,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,tc(t),o,r)})}onDeleteComment(t,o){g(st,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){g(st,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){g(st,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 Za(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return Za(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:Za(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:Za(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){Zb(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Jb{constructor(e){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Mt.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));m(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 Kb=S("remote-cursor-decorator");class wp{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];g(Kb,typeof s=="string","invalid path containerId"),g(Kb,typeof l=="number","invalid path blockIndex");const a=e.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,C)=>{C>d&&(C=d);const v=p.map(D=>({id:K(),type:"remote-cursor",name:D.user.displayName,time:D.time,rainbowIndex:D.user.rainbowIndex})),B=i.get(C);B?B.push(...v):i.set(C,v)}),{insertions:i}}}class Xb extends vt.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Ge(ir(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=te(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 sL(n,e){n.addCustom("child-block-tracker",()=>new Xb(n)).addListener("change",e)}function lL(n,e){n.addCustom("child-block-tracker",()=>new Xb(n)).removeListener("change",e)}const wne="",cL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},aL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},uL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};L.mergeLang({"zh-CN":cL,"en-US":aL,"ja-JP":uL});const Bne="";S("button");function fo(n,e,t,o,r){const i=k("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&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}const Ene="",ev=`<?xml version="1.0" ?>
|
|
28
28
|
<svg
|
|
29
29
|
fill="currentColor"
|
|
30
30
|
xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|