@ones-editor/editor 0.0.3-beta.218 → 0.0.3-beta.219
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 p6={boxType:"br",updateBoxContent:FI,convertTo:PI},C6=S("editor-boxes");class A6{constructor(t){m(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);g(C6,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return g(C6,e,`unknown box type: ${t}`),e}createBox(t,e){const o=Z5(e),r=Y5(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}forEach(t){this.boxes.forEach(t)}}function NI(n,t,e,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,e);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const b6={boxType:"image",updateBoxContent:NI},$I="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function HI(n,t,e){W(e,"editor-box-anchor"),bm($I,[],e)}const v6={boxType:"anchor",updateBoxContent:HI};function jI(n,t,e,o){k("span",[],e,o.text)}const y6={insertionType:"inputting",updateInsertionContent:jI},k6=S("editor-insertion");class w6{constructor(t){m(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);g(k6,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return g(k6,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=J5(e.type,e.id),r=X5(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class UI{constructor(t){m(this,"cursors",new Map);m(this,"timer");this.editor=t,this.timer=this.startTimer()}add(t,e){this.cursors.set(t,e)}startTimer(){return setInterval(()=>{const t=Date.now();Array.from(this.cursors).forEach(([e,o])=>{if(t-o>3e3){const r=K5(this.editor,e);r&&rt(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function zI(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new UI(d)).add(r.id,r.time),W(t,"active")),k("span",[],e,"|").setAttribute("data-cursor-name",r.name),t.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const yg={insertionType:"remote-cursor",updateInsertionContent:zI};class B6{constructor(t){m(this,"decorators",[]);this.editor=t}registerDecorator(t){this.decorators.push(t)}decorateBlock(t,e){let o=e;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,t,e);i&&(o=mt.default(i))}}),o}decorateText(t,e){let o=e;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,t,e);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=mt.default(a))}}}),{insertions:r,text:o}}}const kg=S("editor-input");class VI{constructor(t,e){m(this,"editor");m(this,"composing",!1);m(this,"callbacks");m(this,"inputElement");m(this,"handleDocumentClick",t=>{const e=this.editor.rootContainer,o=t.target;if(o&&e.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 e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Ds(t)||(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});m(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});m(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});m(this,"handleCompositionstart",t=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(t))});m(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});m(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly||!this.editor.isWritable()){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});m(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});m(this,"handleCopy",t=>{this.callbacks.onCopy(t)});m(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onCut(t),kg.debug("on cut")});m(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});m(this,"handlePasteText",(t,e)=>{this.callbacks.onPasteText(t,e)});this.editor=t,this.callbacks=e;const o=k("input",["editor-input"],t.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 t=this.inputElement;t.removeEventListener("compositionstart",this.handleCompositionstart),t.removeEventListener("compositionend",this.handleCompositionend),t.onkeydown=null,t.oninput=null,t.oncopy=null,t.onpaste=null,t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),Ze.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(t){this.callbacks.onChanged(t)}handleRemoteChanged(t){this.callbacks.onRemoteChanged(t)}addHandler(t){this.callbacks.addHandler(t)}removeHandler(t){this.callbacks.removeHandler(t)}defaultInsertText(t,e,o,r,i){g(kg,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return g(kg,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function E6(n){const t=n.rootElement,e=t.getBoundingClientRect(),o=ro(t),r=window.innerWidth,i=window.innerHeight,s=e.left<0?0:e.left,l=e.top<0?0:e.top,a=e.right>r?r:e.right,d=e.bottom>i?i:e.bottom,h=(s+a)/2,p=(l+d)/2,C=0-e.left+h,v=0-e.top+p,B=n.input.inputElement;B.style.left=`${C/o}px`,B.style.top=`${v/o}px`}const wg=S("editor-caret");class WI{constructor(t){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=k("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const t=window.getComputedStyle(this.caretElem);return t.display!=="none"&&t.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const t=this.editor.selection.range.start;if(!(t instanceof Ue))return!1;const e=this.editor.getBlockById(t.blockId);return!!nt(this.editor,e)}update(){if(i5(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",E6(this.editor);return}const{range:e}=this.editor.selection;g(wg,e.isCollapsed,"range is not collapsed");const o=e.start;g(wg,o instanceof Ue,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(wg,nt(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;t.style.left=`${a}px`,t.style.top=`${d}px`,t.style.height=`${i.height}px`;const h=this.editor.input.inputElement;h.style.left=`${a}px`,h.style.top=`${d+i.height-24}px`,Ze.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?(E6(this.editor),t.style.display="none"):t.style.display=""}}function qI(n){r4(n),n.selection.range.getSelectedBlocks().forEach(t=>i4(n,t.block,t.start,t.end))}const GI=S("editor-dom");function x6(n){return so(n.rootContainer).clientHeight}function ZI(n){return n.getFirstBlock().getBoundingClientRect().top}function QI(n){return n.getLastBlock().getBoundingClientRect().bottom}function Bg(n){const e=so(n.rootContainer).getBoundingClientRect(),o=e.x<0?0:e.x,r=e.y<0?0:e.y,i=e.right>window.innerWidth?window.innerWidth:e.right,s=e.bottom>window.innerHeight?window.innerHeight:e.bottom;return new DOMRect(o,r,i-o,s-r)}function YI(n,t){const e=Bg(n),o=n.getBlockById(t.blockId),i=Lo(n,o,t);return ys(e,i.x,i.y)&&ys(e,i.right,i.bottom)}function I6(n,t){const e=Bg(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function JI(n,t){const e=Bg(n),o=t.getBoundingClientRect();return ys(e,o.x,o.y)||ys(e,o.right,o.bottom)}function KI(n){if(!wm(n.rootContainer)){GI.warn("editorScrollIntoView: editor is not visible");return}const t=n.rootContainer.getBoundingClientRect();if(t.height<1&&t.width<1)return;const e=n.selection,o=e.range.focus;if(!o.isSimple()){const p=o,C=n.getContainerById(p.childContainerId);JI(n,C)||C.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const p=n.getBlockById(e.range.start.blockId);if(Ie(p)&&I6(n,p)||Mt(n,p)&&I6(n,p))return}const r=o,i=n.getBlockById(r.blockId);if(YI(n,r))return;const s=Lo(n,i,r),l=i.getBoundingClientRect(),a=ee(i),d=k("div",["editor-block-anchor"],a),h=ro(i);d.style.top=`${(s.top-l.top)/h}px`,Qd(d,{elementToScroll:so(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function XI(n,t){if(t.isCollapsed())return!1;const e=ye(n.rootContainer),o=Qe(n.rootContainer),{start:r,end:i}=t;return r.blockId===it(e)&&r.offset===0&&i.blockId===it(o)&&i.offset===ut(n,o)}const T6=S("range-in-block");function D6(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||te(n,o),s=r===n||te(n,r);return!!(i||s)}function S6(n,t){const e=n.doc.toJSON(),o=new Set(Object.values(e.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=ae(t);if(i){for(;i&&!o.has(it(i));)i=ae(i);g(T6,i,"no prev block while deleting a block"),r=ke(n,i,ut(n,i))}else{const s=Qt(t);g(T6,s,"no prev and next block while deleting a block"),r=ke(n,s,0)}return r}const tT=S("block-to-html");function Eg(n,t,e,o){const r=Ss(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;g(tT,t.text,"no text");const i=ie(t.text);return`<div>${a5(i)}</div>`}const L6=S("block-to-text");function eT(n,t,e){let o="";return t.forEach(r=>{if(g(L6,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,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function Ih(n,t,e,o){const r=Ss(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(g(L6,t.text,"no text"),eT(n,t.text,e))}function xg(n,t,e,o){const r=Ss(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):Ih(n,t,e,o)}function Th(n,t){return t.blocks.root.map((r,i)=>Eg(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
25
25
|
`)}function M6(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${Th(n,t)}</body></html>`}function _a(n,t){return t.blocks.root.map((r,i)=>Ih(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
26
26
|
`)}function Fa(n,t){const e=t.blocks.root.map((r,i)=>xg(n,r,t,[{containerId:"root",blockIndex:i}]));return e[e.length-1]=e[e.length-1].trimEnd(),e.join(`
|
|
27
|
-
`)}const nT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ue||g(nT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=ot(r),l=ct(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Gl=S("insert-text");function Ig(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Gl,r,"no block data"),g(Gl,r.text,"no block text"),rn(r.text)===0)return g(Gl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Ve(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function oT(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return Ig(n,r,i,e)}function R6(n,t,e,o,r){const i=ot(t),s=ct(i),l=bt(t),a=oT(n,t,e),d=Ch(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),pn(n,t)}function O6(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=Ch(e," ",o);return n.doc.localUpdateBlockText(i,s,l),pn(n,t)}function rT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Gl,typeof r.insert=="string","invalid text op, no insert");const i=e+Ah(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Tg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Gl,i,"no block data"),g(Gl,i.text,"no block text");const s=Ig(n,e,o,r);s&&Object.keys(s).includes("link")&&(rT(i.text,r)||delete s.link);const l=Ch(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),pn(n,n.getBlockById(i.id))}function Dg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ql(n);Tg(n,t,e,o,r)}const Dh=S("update-composition-text");function _6(n){const t=n.selection.range.start;t instanceof Ue||g(Dh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(Dh,nt(n,o),"not a text kind block");const r=ot(o),i=ct(r),s=bt(o),l=n.doc.getBlockData(i,s);g(Dh,l,"no block data in doc"),g(Dh,l.text,"no text data in text block");const a=Lt(o);fh(n,Ri(o),e,a,l.text)}function F6(n){_x(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Pa=S("delete-block-text");function Sg(n,t,e,o,r){if(!n.isBlockWritable(t))return Pa.error("block is not writable"),0;g(Pa,nt(n,t),"block is not a text kind block");const i=ot(t),s=ct(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Pa,a,"no block data in doc"),g(Pa,a.text,"no text data in text block");let d=e;sn(t,e)||(d=_i(t,d));let h=e+o;g(Pa,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=_s(t,h));const p=h-d,C=q4(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const Lg=S("break-text-block");function P6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Lg,nt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Lg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=ot(t),i=ct(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?P6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...ar(""),...l,...o==null?void 0:o.newBlockData},D=ke(n,t.id,0),x=Zl(n,i,v,B,D);return{block:t,newBlock:x}}g(Lg,sn(t,e),"not a valid offset");const a=pn(n,t),{right:d}=Tn(a,e),h=rn(d);h>0&&Sg(n,t,e,h);const p={...ar(d),...l,...o==null?void 0:o.newBlockData},C=Zl(n,i,s+1,p,ke(n,p.id,0));return{block:t,newBlock:C}}const iT=S("prepare-insert-new-block");function sT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=me(d);return g(iT,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=ct(ot(r)),e=bt(r),!nt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Ql(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const lT=S("auto-insert-block");function N6(n,t,e,o,r,i){const s=sT(n,e,o);g(lT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Zl(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const cT=S("delete-block");function Sh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Sh(n,i,e)})}))}function Lh(n,t,e){const o=ot(t),r=ct(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(cT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,ze(n,{anchor:e.start,focus:e.end})),s}function Mg(n,t,e){return n.undoManager.runInGroup(()=>{const o=ot(t);To(o)===1&&n.insertTextBlock("",ct(o),0);let r=e?Oi(n,e):null;if(!r){const l=n.selection.range;D6(t,l)?r=S6(n,t):r=l}const i=Lh(n,t,r),s=[];return Sh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function aT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Sh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function $6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Sh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Rg=S("merge-text-block");function H6(n,t,e){g(Rg,nt(n,t),"only text block can be merged"),g(Rg,nt(n,e),"only text block can be merged");const o=Pi(n,t),r=Pi(n,e),i=o.text,s=r.text;g(Rg,i&&s,"block data has no text");const l=ot(t),a=ct(l),d=bt(t),h=ut(n,t),p=Tg(n,s,a,d,h),C=ke(n,t,rn(i));return Mg(n,e,C),p}const ur=S("clear-selected-contents");function Mh(n,t){g(ur,nt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(ur,e.isSimple(),"not a simple block position"),g(ur,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(ur,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function j6(n,t,e){const o=ct(t),r=me(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function uT(n,t){const{block:e,start:o,end:r}=t;if(nt(n,e)){Mh(n,t);return}if(Ie(e)||o.isSimple()){g(ur,r.isSimple(),"invalid range");const s=ot(e),l=bt(e),a=n.insertTextBlock("",ct(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(ur,Mt(n,e),"invalid block kind"),g(ur,!o.isSimple()&&!r.isSimple(),"invalid range"),Ms(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{j6(n,s,{focus:l===0})})}function dT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(ur,e.length>0,"no selected block"),e.length===1){uT(n,e[0]);return}const o=e[0],r=o.block,i=ot(r);g(ur,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(nt(n,r)){Mh(n,o);const h=ke(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),nt(n,l)){Mh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(nt(n,l)){Mh(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===To(i)){j6(n,i,{focus:!0});return}const a=ae(r),d=Qt(l);g(ur,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Og(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),dT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const hT=S("core");function U6(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),pn(n,t)}function z6(n,t,e){if(!n.isBlockWritable(t)){hT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);U6(n,t,r)}function Rh(n,t,e){const o=pn(n,t),r=typeof e=="string"?Fi(e):e,i=ln.diff(o,r);return U6(n,t,i)}const Na=S("update-block-data");function Oh(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;Na.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(e).forEach(([C,v])=>{g(Na,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(Na.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(ua.default(B,v)||C==="text"&&ln.diff(B,v).length===0||(d.has(C)?(Na.debug(`replace key: ${C}`),a.delete.push(C)):Na.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Pi(n,t)}function V6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function _g(n,t,e){if(!Mt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=zn(n,t).getChildContainers(n,t)[0],i=ye(r);_g(n,i,e)}function Ns(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const $a=S("clone-block");function Ni(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g($a,e!==p,"invalid child block"),Ni(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),C=t.blocks[h];g($a,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Ni(n,t,_,o)),B=Ns(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 $a.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${C}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return $a.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(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Fg(n,t,e,o){const r=t.blocks[e];g($a,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Ni(n,t,l,o));return Ns(i)}function Pg(n,t,e){const o=t.blocks.root.map(r=>Ni(n.editorBlocks,t,r,e));return mt.default(Ns(o))}const W6=S("insert-doc");function q6(n,t,e,o,r){if(Mt(n,t)){W6.warn("failed to insert doc into a complex block");return}const i=Pg(n,o,r),s=ot(t),l=bt(t),a=ct(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,z,Z;const d=[];Object.entries(i.blocks).forEach(([tt,ft])=>{tt!=="root"&&d.push({containerId:tt,blocks:ft})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(Ie(t)){n.deleteBlock(t);let tt;h.reverse().forEach(ft=>{const vt=n.insertBlock(a,l,ft,void 0,{noFocus:!0});tt||(tt=vt)}),tt&&n.selection.selectBlock(tt,ut(n,tt));return}if(g(W6,nt(n,t),"not a text block"),ue(n,t)){const tt=a==="root"&&n.getBlockByIndex(a,0)===t,ft=bt(t);let vt;h.forEach((zt,Ht)=>{const Kt=n.insertBlock(a,ft+Ht,zt,void 0,{noFocus:!0});Ht===h.length-1&&(vt=Kt)}),vt&&n.selection.selectBlock(vt,ut(n,vt)),tt&&n.deleteBlock(t);return}if(h.length===1){const tt=h[0];if(wa(n,tt.type)){n.insertTextToBlock(t,e,(H=tt.text)!=null?H:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,tt);return}const p=e===ut(n,t),C=e===0,v=h[0],B=h[h.length-1];let D;!p&&!C?D=n.breakTextBlock(t,e,{forceInsertAfter:!0}):D=t;const x=C?l:l+1;p?(D=n.insertBlock(a,l+1,B),n.selection.selectBlock(D,ut(n,D))):(n.selection.selectBlock(D,0),wa(n,B.type)?n.insertTextToBlock(D,0,(z=B.text)!=null?z:[]):n.insertBlock(a,x,B));const _=n.selection.range;let R=x;wa(n,v.type)?C?(n.insertBlock(a,x,v),R+=1):n.insertTextToBlock(t,e,(Z=v.text)!=null?Z:[]):(n.insertBlock(a,x,v),R+=1),h.slice(1,h.length-1).reverse().forEach(tt=>{n.insertBlock(a,R,tt)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function Ng(n,t,e,o,r){const i=Pg(n,o,r),s=ct(t),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,e,h,void 0,{noFocus:!0,noScroll:!0});l.push(p)})}),l}function G6(n,t,e){const o=To(t);Ng(n,t,o,e);for(let r=0;r<o;r++){const i=ye(t);n.deleteBlock(i)}}const Ha=S("add-text-attribute");function fT(n,t,e,o){const{start:r,end:i}=e;g(Ha,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Ha,o,"invalid attribute name");const s=n.getBlockText(t),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Z6(n,t,e,o,r){const{start:i,end:s}=e;g(Ha,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Ha,o,"invalid attribute name");const l=n.getBlockText(t),a=La(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Yl(n,t,e,o,r){const{start:i,end:s}=e;g(Ha,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=e6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Q6(n,t,e,o){const r=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!nt(n,s))return;if(ue(n,s)){o(n,it(s),t,e);return}const d=ze(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Yl(n,s,d,t,e):(Yl(n,s,d,"color",null),Yl(n,s,d,"backgroundColor",null))})})}function Y6(n,t,e){const o=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!nt(n,i))return;if(ue(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=ze(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Yl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Yl(n,i,a,"backgroundColor",null)})})}function $g(n,t){const e=Oo(n,{simpleBlockOnly:!0}).filter(s=>nt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return r6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Wn=S("adjust-selection-pos");function J6(n){const t=[];for(;n;){const e=ot(n);if(t.unshift(e),Gt(e))return t;const o=et(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function K6(n,t){for(;t;){const e=ot(t);if(e===n)return t;const o=et(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function mT(n,t){const e=J6(n),o=J6(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=K6(r,n),s=K6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function X6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=ot(e);g(Wn,Mo(o),"not a child container");const r=et(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function _h(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ue&&e instanceof Ue?{anchor:t,focus:e}:t instanceof Ro&&e instanceof Ro?dh(n,o,t,e):null;const i=ot(o),s=ot(r);if(i===s)return t instanceof Ro&&(t=st(o,0,"home")),e instanceof Ro&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof Ue,"not valid position type"),g(Wn,e instanceof Ue,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ue&&e instanceof Ro){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=et(i);if(D&&D===et(B)){const x=fe(D,ct(i)),_=fe(D,ct(B));return dh(n,D,x,_)}}return null}const l=Gd(o,r)>0,{newBlock1:a,newBlock2:d}=mT(o,r);if(a===d){const B=a,D=X6(B,o),x=X6(B,r);return t=fe(a,ct(D)),e=fe(a,ct(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),dh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof Ue&&(h=t.offset);let C=l?0:ut(n,d);return d===r&&e instanceof Ue&&(C=e.offset),t=st(a,h,l?"end":"home"),e=st(d,C,l?"home":"end"),{anchor:t,focus:e}}const gT=S("move-complex-block-position");function pT(n,t,e){const o=n.getBlockById(t.blockId);g(gT,Mt(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,ct(s)):null}const ja=S("move-simple-block-position");function tA(n,t){const e=gn(n,t,{visibleOnly:!0});g(ja,e.length>0,"complex block has not any child container");const o=e[0];return ye(o)}function eA(n,t){const e=gn(n,t,{visibleOnly:!0});g(ja,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qe(o)}function nA(n,t,e){const o=e?tA(n,t):eA(n,t);return Mt(n,o)?nA(n,o,e):o}function CT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?tA(n,e):Ts(e)}function AT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?eA(n,e):Is(e)}function Hg(n){return n==="ArrowLeft"||n==="ArrowUp"}function jg(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);g(ja,r,"child container has not parent block"),g(ja,Mt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?Hg(e)?Qe(i):ye(i):jg(n,r,e)}function bT(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);if(g(ja,r,"child container has not parent block"),Hg(e)){const l=ae(r);if(l)return l}else{const l=Qt(r);if(l)return l}const i=jg(n,r,e);if(i)return i;let s=r;for(;!Gt(ot(s));)s=et(ot(s));return Hg(e)?ae(s):Qt(s)}function vT(n,t,e){return!Mt(n,t)||zn(n,t).enableKeyboardSelect?t:nA(n,t,e==="ArrowDown"||e==="ArrowRight")}function yT(n,t,e){const o=n.getBlockById(t.blockId),i=Yt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?CT(n,t):AT(n,t);if(s||(s=jg(n,o,e),s||(s=bT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Gt(ot(o)))return null;const l=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(l,0,"home")}return null}if(s=vT(n,s,e),nt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Gx(n,s,o,t,l);if(e==="ArrowUp")return qx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function kT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(nt(n,r))return o;const i=Qt(r);if(i)return st(i,0,"home");if(!Gt(ot(r))||n.readonly)return o;const s=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(s,0,"home")}function wT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=kT(n,t,o):r=yT(n,o.getFocusedPos(),t);else if(r=pT(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Qe(s);r=st(l,0,"home")}else{const l=ye(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:_h(n,o.anchor,r):null}function $i(n,t,e){const o=wT(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function oA(n){return $i(n,"ArrowLeft","move"),!0}function rA(n){return $i(n,"ArrowRight","move"),!0}function iA(n){return $i(n,"ArrowUp","move"),!0}function sA(n){if($i(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=ot(t);if(Gt(e)||Qe(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",ct(o),To(o)),!0}function lA(n){return $i(n,"ArrowDown","select"),!0}function cA(n){return $i(n,"ArrowLeft","select"),!0}function aA(n){return $i(n,"ArrowRight","select"),!0}function uA(n){return $i(n,"ArrowUp","select"),!0}const dA=S("word-offset");function Ug(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"home");if(e.offset===0||!nt(n,o)){const s=ae(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&nt(n,s)){const a=bg(n,s,l.offset);return st(s,a,"normal")}return l}const r=bg(n,o,e.offset);return st(o,r,"normal")}function zg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!nt(n,o)){const s=Qt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&nt(n,s)){const a=vg(n,s,l.offset);return st(s,a,"end")}return l}const r=vg(n,o,e.offset);return st(o,r,"normal")}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Vg(n,t){if(!Mt(n,t))return t;const o=zn(n,t).getChildContainers(n,t)[0],i=me(o)[0];return Vg(n,i)}function Wg(n,t){if(!Mt(n,t))return t;const e=zn(n,t).getChildContainers(n,t),o=e[e.length-1],r=me(o),i=r[r.length-1];return Wg(n,i)}function qg(n){const t=Wg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function pA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function CA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Gg(n){const t=Wg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const AA=S("line-offset");function bA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!nt(n,e))return st(e,0,"home");let r=j4(e,t).start;const{next:i}=lh(e,r);return i&&co(i)&&ka(i)==="br"&&(r+=1),st(e,r,"home")}function vA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!nt(n,e))return st(e,ut(n,e),"end");const o=j4(e,t);return st(e,o.end,"end")}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const EA=S("find-block-position");function BT(n,t,e,o){g(EA,Mt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(EA,r.length>0,"complex block has not any child container");const i=Lo(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=S4(n,t,s,l);return Zg(n,a,e,o)}function Zg(n,t,e,o){if(Mt(n,t))return BT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=Lo(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const C=st(r,p,"normal"),v=Lo(n,t,C),B=or(v,l,a);B<i&&(i=B,d=C)}return d}const xA=S("page-offset");function ET(n,t){const e=x6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<ZI(n))return n.getFirstBlock();const i=ae(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ae(s)}return n.getFirstBlock()}function xT(n,t){const e=x6(n)*.9,o=t.getBoundingClientRect(),r=QI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Qt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Qt(l)}return n.getLastBlock()}function IA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ET(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Zg(n,o,e,t),r}function TA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=xT(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Zg(n,o,e,t),r}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);if(!e)return!1;const o=_h(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);if(!e)return!1;const o=_h(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Ua=S("select-all");function RA(n,t){const e=ye(n),o=Qe(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function IT(n,t){const e=t.getEditor(),o=zn(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===ct(r)&&t.end.blockId===s&&t.end.childContainerId===ct(i)}function TT(n,t){g(Ua,t,"no parent block"),g(Ua,Mt(n,t),"not a complex block");const e=zn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(ze(n,{anchor:fe(t,ct(o)),focus:fe(t,ct(r))}))}function OA(n,t){const e=ot(t);Qg(n,e)}function _A(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&nt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),OA(n,ye(n.rootContainer)),!1}return g(Ua,!e.isSimple(),"invalid range type"),IT(t,e)?(OA(n,t),!1):(g(Ua,t,"no parent block"),g(Ua,Mt(n,t),"not a complex block"),TT(n,t),!0)}function Qg(n,t){const e=me(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function DT(n){Gg(n),n.focus()}const Yg=S("selected-block-to-doc");function FA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{FA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Fh(n,t){const e=Yt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Pi(n,t.block));if(nt(n,t.block)){const i=t.start,s=t.end;if(g(Yg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Ve(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Ie(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Yg,Mt(n,t.block),"not complex block"),g(Yg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return FA(n,o,r),r}function Jg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Fh(n,{block:t,start:e,end:o})}const ST=S("block-to-doc");function LT(n,t){g(ST,t.length>0,"invalid params, no blocks");const e=t.map(o=>Jg(n,o));return Ns(e)}function Ph(n){const e=n.selection.range.getSelectedBlocks().map(o=>Fh(n,o));return Ns(e)}function PA(n,t){const e=n.getContainerById(t),i=me(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Fh(n,s));return Ns(i)}const Nh=S("editor-selection");class MT{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(D6(e,i)){Nh.debug("adjust selection because remote deleted current block");const s=S6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new WI(t);const r=st(o,0,"normal");this._range=ze(t,{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 t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=st(t,e,"normal");let i;o&&(i=st(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=ze(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!XI(this.editor,r))&&rt(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),qI(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!Wr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Lo(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){KI(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Nh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Nh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.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;e&&xt(e,"focused")&&(rt(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Ph(this.editor);return t==="text"?_a(this.editor,e):t==="markdown"?Fa(this.editor,e):M6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{rt(t,"focused"),rt(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=ot(t);for(;Mo(e);){const o=et(e);g(Nh,o,"parent block not found"),W(o,"child-focused"),e=ot(o)}return!0}}function RT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function OT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!nt(n,e))return;let o=Ug(n,"select"),r=zg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class _T{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=R4(this.editor,t.x,t.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=so(s[0].block);this.autoScroll=new eh({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.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(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=hh(this.editor,t.x,t.y);if(!e)return;const o=_h(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){OT(this.editor)}handleTripleClick(t){RT(this.editor)}}function FT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function PT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const NA=S("delete-text");function $A(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ue||g(NA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(NA,nt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=_i(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function HA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const NT=S("handle-backspace");function Kg(n,t){if(!ue(n,t))return;const e=ot(t);To(e)!==1&&n.deleteBlock(t)}function $T(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===0){if(HA(n,o))return;const r=ae(o);if(r){if(!n.isBlockWritable(r))return;if(nt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Kg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Kg(n,o),g(NT,Ie(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ot(o);if(Mo(i)){const s=I4(n,i);if(s){if(!n.isBlockWritable(s))return;Kg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else $A(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function HT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===ut(n,o)){const r=Qt(o);if(r){if(!n.isBlockWritable(r))return;nt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ue(n,o)?n.deleteBlock(o,ke(n,r,0)):n.deleteBlock(r)}}else $A(n,"forward",1,null);else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function jT(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Mt(n,r))return!1;if(Wr(e))return!0;const s=Ms(n,r,e,o),l=gn(n,r);return s.length===l.length}function UT(n,t){if(jT(n)){const s=n.getFocusedBlock(),l=bt(s),a=ct(ot(s));n.insertTextBlock("",a,l+1);return}const e=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&Ie(e);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),nt(n,e)){if(ue(n,e)&&HA(n,e))return;const s=n.selection.range.start,l=n.breakTextBlock(e,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 zT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!nt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const VT=S("input-handler-actions");function WT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(UT(n),!0))}function qT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function GT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>($T(n),!0))}function ZT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function QT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{VT.error(t)}),!0)}const $h={ArrowDown:sA,ArrowUp:iA,ArrowLeft:oA,ArrowRight:rA,"Shift+ArrowDown":lA,"Shift+ArrowUp":uA,"Shift+ArrowLeft":cA,"Shift+ArrowRight":aA,"CtrlOrCmd+ArrowLeft":hA,"CtrlOrCmd+ArrowRight":fA,"CtrlOrCmd+Shift+ArrowLeft":mA,"CtrlOrCmd+Shift+ArrowRight":gA,"CtrlOrCmd+ArrowUp":pA,"CtrlOrCmd+ArrowDown":qg,"CtrlOrCmd+Shift+ArrowUp":CA,"CtrlOrCmd+Shift+ArrowDown":Gg,"CtrlOrCmd+A":_A,Home:wA,End:BA,"Shift+Home":yA,"Shift+End":kA,PageUp:DA,PageDown:SA,"Shift+PageUp":LA,"Shift+PageDown":MA,"CtrlOrCmd+Z":FT,"CtrlOrCmd+Shift+Z":PT,Enter:WT,Delete:qT,Backspace:GT,"Shift+Enter":ZT,"CtrlOrCmd+Shift+V":QT};function jA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function UA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){let l="";s.split("|").forEach(d=>{const h=e.get(d);l+=l?`|${h}`:`${h}`}),i.src=l}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{UA(n,l,e)})})}function zA(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):UA(t,r,e)})}async function YT(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function JT(n,t){var i,s;const o=t.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 KT(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(JT(n,t)){const s=Array.from(Object.keys(o));r=await YT(n,s),zA(n,t,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&&zA(n,t,i)}async function XT(n,t,e){await KT(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Ie(i)){const s=ot(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,t,e)}})}const tD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function eD(n){let t;for(const e of tD)if(t=n[e],t)break;return t||null}function VA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{VA(n,l,e)})})}function nD(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):VA(t,r,e)}),Array.from(e)}function Hh(n,t){return Ze.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Mi(JSON.stringify(t))}" 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(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function jh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=nD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function oD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Ph(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),jh(n,o);const i=Th(n,o),s=Fa(n,o),l=Hh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Uh(n,t){const e=Jg(n,t);jh(n,e);const o=Th(n,e),r=Fa(n,e),i=Hh(o,e);return Mm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class rD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ql(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ql(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(t){oD(this.editor,t,(e,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(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Ie(o)&&this.editor.deleteBlock(o)}else Og(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){rt(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){Dg(this.editor,i)}defaultHandleKeydown(t,e){return jA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await XT(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=eD(t);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,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function iD(n,t,e){const o=$r(t,e);return o.remove(),o}S("copy-dom-attributes");const WA=["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 sD(n,t){for(let l=0;l<WA.length;l++){const a=WA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[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];e.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function qA(n){const t=Array.from(n.childNodes).filter(e=>!z5(e));return t.forEach(e=>{e.remove()}),t}function GA(n,t,e){var d;const o=n.getContainerById(t),r=$r(o,e),i=Ri(r),s=n.doc.getBlockData(t,e),l=Yt(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=qA(h);qA(r),p.forEach(v=>{r.appendChild(v)});const C=ih(h);if(C){const v=ih(r);v&&v.remove(),r.appendChild(C)}sD(h,r)}l4(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 lD=S("transform-selection");function ZA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(lD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return ze(n,{anchor:l,focus:a})}const cD=S("handle-block-text-changed");function aD(n,t,e,o,r){const i=n.getContainerById(t),s=$r(i,e),l=n.doc.getBlockData(t,e);if(g(cD,l.text,"no block text"),e4(n,s).setBlockText(n,s,l.text),!r){const a=ZA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function uD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function QA(n,t,e,o){const r=Yt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function dD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{QA(n,i,o,{child:!0})}),QA(n,r,o,{child:!1})}const Fo=S("editor-doc");class hD extends fa{constructor(e,o,r){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(Fo,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(Fo,l,`no text, ${e}, ${o}`);const a=ZA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,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(Fo,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(uD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Oi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(Fo,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(Oi(this.editor,r)),s}localDeleteChildContainers(e){return g(Fo,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){g(Fo,!this.editor.readonly,"editor is readonly");const o=mt.default(e);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(e){Fo.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),aD(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),GA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);KE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){dD(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);iD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Fo.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function YA(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Xg=S("undo-action");class Jl{constructor(t,e,o){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return g(Xg,t,"no other action"),!1}combine(t){g(Xg,!1,"no other")}setAfterRange(t){this.afterRange&&Xg.warn("after range has already set"),this.afterRange=t}}const fD=S("block-action");class JA extends Jl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(fD,this.blockIndex===bt(i),"invalid block index"),Lh(e,i,Oi(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}const mD=S("insert-block-action");class gD extends JA{undo(t){return t.findBlockById(this.blockData.id)?this.deleteBlock(t,this.beforeRange):(mD.warn(`block (${this.blockData.blockId}) not found, deleted by others?`),!1)}redo(t){return this.insertBlock(t,this.afterRange)}}class pD extends JA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class CD extends Jl{constructor(e){super(e,ct(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){YA(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Jl&&(o.afterRange||o.setAfterRange(e))}}const Hi=S("update-block-data-action");class zh extends Jl{constructor(e,o,r,i,s,l){super(e,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=mt.default(i),this.afterBlockData=mt.default(s),g(Hi,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Oh(e,o,zh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g(Hi,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Oh(e,o,zh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const tp=S("update-block-text-action");class za extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=za.calType(i,s)}static calType(e,o){g(tp,e,"no old data"),g(tp,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>A5(h)?`cjk_${h}`:p5(h)?"number":Yd(h)?"space":C5(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(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Rh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Rh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof za)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.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(e){g(tp,e instanceof za,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class KA extends Jl{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0}}class AD extends KA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class bD extends KA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Po=S("undo");class vD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,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(t){this.currentGroup?this.currentGroup.addAction(t):(YA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Po,!this.currentGroup,"current group already exists"),this.currentGroup=new CD(this.editor),this.groupCounter=1):(g(Po,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Po,this.currentGroup,"current group not exists"),g(Po,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Po.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(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Po.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Oi(this.editor,t.beforeRange))}catch(e){Po.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!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 t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Oi(this.editor,e)):Po.warn("no after range")}catch(e){Po.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!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 e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new za(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new zh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Po,e>=0,"invalid block index"),g(Po,o,"no block data"),this.addAction(new gD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new pD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new AD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,t,e)))}}class yD{async fromData(t,e){const o=e.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(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class wD{constructor(t){m(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);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(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,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(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Ce extends ve.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=et(o);if((!r||!te(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?it(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&te(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&rt(s,"hover"),e&&W(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Ce(e))}getParentTextContentChild(e,o){if(!nt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:$m(o)}}const XA="style-color-",tb="style-bg-color-";class BD{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(XA)?i["data-style-color"]=l.substring(XA.length):l.startsWith(tb)?i["data-style-bg-color"]=l.substring(tb.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(t,e,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=t.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"),Ce.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,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=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ce.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function ED(n){n.editorBlocks.registerBlockClass(Dn),n.editorBlocks.registerBlockClass(x4),n.editorBoxes.registerBoxClass(g6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(b6),n.editorBoxes.registerBoxClass(v6),n.editorInsertions.registerInsertionClass(y6),n.editorBlockRenders.registerRender(new BD)}function xD(n,t){ED(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const eb=S("range-commands");function nb(n,t){n.forEach(e=>{e.source=t,e.children&&nb(e.children,t)})}function ob(n,t,e){const o=it(t);g(eb,o===e.start.blockId,"invalid start range"),g(eb,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);nb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(l=>{me(l).forEach(d=>{const h=ut(n,d),p=ze(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),C=ob(n,d,p);i.push(...C)})}),i}function rb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=ze(t,{anchor:r.start,focus:r.end});ob(t,r.block,i).forEach(l=>{o.push(l)})}),o}function ib(n,t,e,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,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(C=>{me(C).forEach(B=>{const D=ut(n,B),x=ze(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});ib(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function sb(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||(n.getSelectedBlocks().forEach(l=>{const a=ze(o,{anchor:l.start,focus:l.end});ib(o,l.block,a,t,e,r)}),o.focus()),r}const ID=S("command-providers");class lb{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return g(ID,e,`no command provider, id=${t}`),e}getCommands(t){return rb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>sb(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function TD(n,t){const e=ot(t),o=ct(e),r=bt(t);GA(n,o,r)}const DD=S("table-scroll");class cb{constructor(t,e,o,r,i){m(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class SD{constructor(t){m(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){DD.warn(`event has already registered: ${e}`);return}i.push(new cb(this.editor,t,e,o,r))}else{const s=new cb(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(e)e===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(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const ab=S("update-block-text");function LD(n,t){const e=n.getBoxById(t.id),o=et(e);g(ab,o,"no parent block"),g(ab,nt(n,o),"not a text block");const r=n.getBlockText(o),i=s6(r,"id",t.id,t);z6(n,o,i)}function MD(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function RD(n){if(n.readonly)return!1;const t=Oo(n);return!!n.isBlockWritable(t.map(e=>e.block))}class OD{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class _D{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(rr(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Yr=S("editor");class FD extends ve.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;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 k4(this));m(this,"editorBoxes",new A6(this));m(this,"editorInsertions",new w6(this));m(this,"editorEmbeds",new B4(this));m(this,"editorDecorators",new B6(this));m(this,"editorCommandProviders",new lb(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 rD(this));m(this,"settingsProvider");m(this,"_readonly",!1);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},this.settingsProvider=(a=r==null?void 0:r.settingsProvider)!=null?a:new OD(this),xD(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(d=r==null?void 0:r.components)==null?void 0:d.blockHooks)!=null?h:[]),this.id=(p=r==null?void 0:r.id)!=null?p:K(),this.clientId=K(),this.undoManager=new vD(this),this.doc=new hD(this,o,this.undoManager),this.parent=e,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=b4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new VI(this,this.inputHandlers),this.selection=new MT(this),this.selectionHandler=new _T(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ze.isMobile&&W(this.rootElement,"mobile"),Ze.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):rt(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:so(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return g(Yr,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,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(e=>e.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(e,o){_g(this,e,o)}isWritable(){return RD(this)}isBlockWritable(e){return MD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return(!o||!Array.isArray(o))&&(g(Yr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Yr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(e,o,r){return v4(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Yr,Bs(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Yr,Nm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Yr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Yr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return $r(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return Vr(this,e)}getParentContainer(e){return ot(e)}reloadBlock(e){TD(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Zl(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Mg(this,e,o)}mergeTextBlock(e,o){return H6(this,e,o)}breakTextBlock(e,o,r){return Ql(this,e,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(e,o){const r=this.getBlockText(e);return ie(r,o)}getBlockData(e){return Pi(this,e)}getBoxData(e){return f6(this,e)}getBlockText(e){return pn(this,e)}setBlockText(e,o){z6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Sg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return R6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return O6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){q6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Ng(this,e,o,r,i)}deleteChildContainers(e){$6(this,e)}replaceBlockText(e,o){return Rh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Oh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return V6(this,e,o,r)}updateBoxData(e){LD(this,e)}getSelectedText(){const e=Ph(this);return _a(this,e)}clearSelectedContents(){Og(this)}insertTextBlock(e,o,r,i){const s=ar(e!=null?e:"");return N6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){F6(this);return}o?(this.compositingText="",Ca()||Dg(this,e)):(this.compositingText=e,_6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Va(n,t,e){return new FD(n,t,e)}function PD(n){const t=(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=pm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const ND=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Vh extends ve.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:ND}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&ua.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.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(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const o=this.cursors.get(e);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(e),this.emit("remote-carets-change",[...r])}}updateUsers(e){this.users.forEach(o=>{e.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&kh(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(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(kh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xe=S("local-doc");class ep extends fa{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[ar("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainers(e){e.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xe,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(e){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,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(e,o){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Vh}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class $D{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function np(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new $D(o)})}const ub=S("find-block");function db(n,t){const e=Is(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),db(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function hb(n,t){const e=Ts(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),hb(n,o)}return Mt(n,e)?Xm(n,e,{visibleOnly:!0}):e}const HD=S("remote-cursor");class jD{constructor(){m(this,"remoteUsers",new Vh)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):HD.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function UD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function zD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function Wa(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=UD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function ji(n){return n==="root"?"blocks":n}function Kl(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,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new on.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var dr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ui={},op=Q3.default.EventEmitter;Ui.EventEmitter=op,Ui.mixin=WD;function WD(n){for(var t in op.prototype)n.prototype[t]=op.prototype[t]}var fb=["info","warn","error"];function mb(){var n={};fb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var qD=mb;mb.prototype.setMethods=function(n){n=n||{};var t=this;fb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var GD=qD,ZD=new GD,gb=ZD;function $s(n,t){this.code=n,this.message=t||"",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 Wh=$s,qa={},pb=QD;function QD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(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?t([],s[0],l[0],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var Cb={exports:{}},zi=Cb.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||""}},rp=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},ip=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")},qh=function(n){for(var t=0;t<n.length;t++)ip(n[t])};zi.apply=function(n,t){var e;qh(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=rp(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Jr=zi._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:rp(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:rp(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};zi.compose=function(n,t){qh(n),qh(t);for(var e=n.slice(),o=0;o<t.length;o++)Jr(e,t[o]);return e},zi.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),Jr(t,o)}return t};var sp=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};zi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=sp(n,t[r],o);return n};var YD=zi._tc=function(n,t,e,o){if(ip(t),ip(e),t.i!=null)Jr(n,{i:t.i,p:sp(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Jr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Jr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Jr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Jr(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=sp(i.p,e),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 t=0;t<n.length;t++)n[t]=JD(n[t]);return n},pb(zi,YD,qh,Jr);var Gh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},KD=function(n){return!!n&&n.constructor===Object},No=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Kr={};It.registerSubtype=function(n){Kr[n.name]=n},It.create=function(n){return n===void 0?null:No(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Kr[n.t]&&(t.t=n.t,t.o=Kr[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Gh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Gh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!KD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ga(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function Za(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}It.apply=function(n,t){It.checkValidOp(t),t=No(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&Ga(r);for(var i=null,s=e,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)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.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)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var XD=It.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};It.append=function(n,t){if(t=No(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ga(t),Ga(e)),XD(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Kr[t.t]){if(e.o=Kr[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),Za(t),n.push(t);Za(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Za(t),Za(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=No(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Gh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=No(t);var r=It.commonLengthForOps(e,t),i=It.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var a=No(e);a.p=a.p.slice(s),t.ld=It.apply(No(t.ld),[a])}else if(t.od!==void 0){var a=No(e);a.p=a.p.slice(s),t.od=It.apply(No(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ga(t),a=No(e),Ga(a)),a.t&&Kr[a.t]){if(t.t&&t.t===a.t){var h=Kr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,C=0;C<h.length;C++)t.o=[h[C]],t.p=p.slice(),Za(t),It.append(n,t);else(!Gh(h)||h.length>0)&&(t.o=h,It.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=No(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var v=t.p[r],B=t.lm,D=e.p[r],x=e.lm;if(D!==x)if(v===D)if(o==="left")t.p[r]=x,v===B&&(t.lm=x);else return n;else v>D&&t.p[r]--,v>x?t.p[r]++:v===x&&D>x&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>x?t.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&d){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},pb(It,It.transformComponent,It.checkValidOp,It.append);var tS=Cb.exports;It.registerSubtype(tS);var eS=It,nS={type:eS};(function(n){n.defaultType=nS.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(qa);var $o={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}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(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){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(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})($o);var Ab=Array.isArray,bb=Object.keys,oS=Object.prototype.hasOwnProperty,rS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Ab(t),r=Ab(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var C=bb(t);if(s=C.length,s!==bb(e).length)return!1;for(i=s;i--!==0;)if(!oS.call(e,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},vb=Ui,iS=gb,qn=Wh,Zh=qa,Ho=$o,sS=Ho.clone,lS=rS,Sn=qn.CODES,cS=Ft;function Ft(n,t,e){vb.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,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}vb.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=Zh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Sn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new qn(Sn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new qn(Sn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?Zh.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;Ho.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Sn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){Ho.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){Ho.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Sn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Qh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Qh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Ft.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))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);aS(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=uS([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.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;Ho.nextTick(function(){n._handleSubscribe()})}}};function aS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function uS(n){return n=n.filter(Ho.truthy),n.length?function(t){Ho.callEach(n,t)}:null}Ft.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 Qh(n,t){if(n.del)return dS(t);if(t.del)return new qn(Sn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}Ft.prototype._otApply=function(n,t){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,t),!t&&this.type===Zh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Qh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);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",t);return}if(n.del){var a=this.data;this._setType(null),this.emit("del",a,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new qn(Sn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=Ho.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"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!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 e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;Ho.nextTick(function(){r.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!lS(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},Ft.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=Zh.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:t,data:n}},s=e&&e.source;this._submit(i,s,o)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Sn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:sS(this.data),type:this.type.uri}},Ft.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()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=Qh(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=Ho.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Ho.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)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 yb=Ui,kb=Hs.ACTIONS,hS=$o,fS=Ln;function Ln(n,t,e,o,r,i,s){yb.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,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}yb.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 t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Ln.prototype.destroy=function(n){this.connection.canSend&&this.action===kb.querySubscribe&&this.connection.send({a:kb.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,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ln.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ln.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)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(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Ln.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Ln.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},Ln.prototype._handleError=function(n){this.emit("error",n)},Ln.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Ln.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var wb=Ui,mS=Hs.ACTIONS,gS=$o,Bb=hr;function hr(n,t){if(wb.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}wb.mixin(hr),hr.prototype.submit=function(n,t){this.value=n,this.send(t)},hr.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},hr.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},hr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},hr.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},hr.prototype._message=function(){return{a:mS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},hr.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},hr.prototype._callbackOrEmit=function(n,t){if(t)return gS.nextTick(t,n);n&&this.emit("error",n)};var pS=$o,Eb=lp;function lp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}lp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},lp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&pS.nextTick(n)};var cp={exports:{}};(function(n,t){(function(e,o){o(t)})(dr,function(e){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,lt){R(J).apply(G,U.concat(lt))},j)});return M.length?F.apply(this,M):F}}var z=typeof dr=="object"&&dr&&dr.Object===Object&&dr,Z=typeof self=="object"&&self&&self.Object===Object&&self,tt=z||Z||Function("return this")(),ft=tt.Symbol,vt=Object.prototype,zt=vt.hasOwnProperty,Ht=vt.toString,Kt=ft?ft.toStringTag:void 0;function qe(w){var T=zt.call(w,Kt),M=w[Kt];try{w[Kt]=void 0;var F=!0}catch{}var U=Ht.call(w);return F&&(T?w[Kt]=M:delete w[Kt]),U}var Yn=Object.prototype,He=Yn.toString;function Rn(w){return He.call(w)}var xr="[object Null]",kn="[object Undefined]",an=ft?ft.toStringTag:void 0;function Ir(w){return w==null?w===void 0?kn:xr:an&&an in Object(w)?qe(w):Rn(w)}var ii="[object AsyncFunction]",Ao="[object Function]",eC="[object GeneratorFunction]",nC="[object Proxy]";function oC(w){if(!s(w))return!1;var T=Ir(w);return T==Ao||T==eC||T==ii||T==nC}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)&&!oC(w)}var si={};function Nt(){}function Tr(w){return function(){if(w!==null){var T=w;w=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Pc=function(w){return os&&w[os]&&w[os]()};function a1(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 u1(w){return un(w)&&Ir(w)==rl}var bo=Object.prototype,d1=bo.hasOwnProperty,rC=bo.propertyIsEnumerable,il=u1(function(){return arguments}())?u1:function(w){return un(w)&&d1.call(w,"callee")&&!rC.call(w,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,h1=ll&&!0&&n&&!n.nodeType&&n,cl=h1&&h1.exports===ll,f1=cl?tt.Buffer:void 0,al=f1?f1.isBuffer:void 0,rs=al||sl,Gu=9007199254740991,Zu=/^(?:0|[1-9]\d*)$/;function Qu(w,T){var M=typeof w;return T=T==null?Gu:T,!!T&&(M=="number"||M!="symbol"&&Zu.test(w))&&w>-1&&w%1==0&&w<T}var Yu="[object Arguments]",Ju="[object Array]",Ku="[object Boolean]",Xu="[object Date]",td="[object Error]",ed="[object Function]",iC="[object Map]",sC="[object Number]",lC="[object Object]",m1="[object RegExp]",g1="[object Set]",cC="[object String]",aC="[object WeakMap]",uC="[object ArrayBuffer]",dC="[object DataView]",p1="[object Float32Array]",hC="[object Float64Array]",fC="[object Int8Array]",mC="[object Int16Array]",nd="[object Int32Array]",gC="[object Uint8Array]",od="[object Uint8ClampedArray]",pC="[object Uint16Array]",CC="[object Uint32Array]",le={};le[p1]=le[hC]=le[fC]=le[mC]=le[nd]=le[gC]=le[od]=le[pC]=le[CC]=!0,le[Yu]=le[Ju]=le[uC]=le[Ku]=le[dC]=le[Xu]=le[td]=le[ed]=le[iC]=le[sC]=le[lC]=le[m1]=le[g1]=le[cC]=le[aC]=!1;function AC(w){return un(w)&&nl(w.length)&&!!le[Ir(w)]}function bC(w){return function(T){return w(T)}}var C1=typeof e=="object"&&e&&!e.nodeType&&e,ul=C1&&!0&&n&&!n.nodeType&&n,vC=ul&&ul.exports===C1,Nc=vC&&z.process,A1=function(){try{var w=ul&&ul.require&&ul.require("util").types;return w||Nc&&Nc.binding&&Nc.binding("util")}catch{}}(),b1=A1&&A1.isTypedArray,yC=b1?bC(b1):AC,kC=Object.prototype,wC=kC.hasOwnProperty;function BC(w,T){var M=Ae(w),F=!M&&il(w),U=!M&&!F&&rs(w),j=!M&&!F&&!U&&yC(w),G=M||F||U||j,J=G?a1(w.length,String):[],lt=J.length;for(var pt in w)(T||wC.call(w,pt))&&!(G&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Qu(pt,lt)))&&J.push(pt);return J}var $c=Object.prototype;function EC(w){var T=w&&w.constructor,M=typeof T=="function"&&T.prototype||$c;return w===M}function Hc(w,T){return function(M){return w(T(M))}}var xC=Hc(Object.keys,Object),IC=Object.prototype,TC=IC.hasOwnProperty;function v1(w){if(!EC(w))return xC(w);var T=[];for(var M in Object(w))TC.call(w,M)&&M!="constructor"&&T.push(M);return T}function jc(w){return ol(w)?BC(w):v1(w)}function y1(w){var T=-1,M=w.length;return function(){return++T<M?{value:w[T],key:T}:null}}function DC(w){var T=-1;return function(){var F=w.next();return F.done?null:(T++,{value:F.value,key:T})}}function SC(w){var T=jc(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 LC(w){if(ol(w))return y1(w);var T=Pc(w);return T?DC(T):SC(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=Tr(F||Nt),w<=0||!T)return F(null);var U=LC(T),j=!1,G=0,J=!1;function lt(at,At){if(G-=1,at)j=!0,F(at);else{if(At===si||j&&G<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;G<w&&!j;){var at=U();if(at===null){j=!0,G<=0&&F(null);return}G+=1,M(at.value,at.key,vo(lt))}J=!1}pt()}}function Dr(w,T,M,F){dl(T)(w,R(M),F)}function je(w,T){return function(M,F,U){return w(M,T,F,U)}}function rd(w,T,M){M=Tr(M||Nt);var F=0,U=0,j=w.length;j===0&&M(null);function G(J,lt){J?M(J):(++U===j||lt===si)&&M(null)}for(;F<j;F++)T(w[F],F,vo(G))}var MC=je(Dr,1/0),Zo=function(w,T,M){var F=ol(w)?rd:MC;F(w,R(T),M)};function Qo(w){return function(T,M,F){return w(Zo,T,R(M),F)}}function id(w,T,M,F){F=F||Nt,T=T||[];var U=[],j=0,G=R(M);w(T,function(J,lt,pt){var at=j++;G(J,function(At,Zt){U[at]=Zt,pt(At)})},function(J){F(J,U)})}var Uc=Qo(id),sd=H(Uc);function li(w){return function(T,M,F,U){return w(dl(M),T,R(F),U)}}var Sr=li(id),ld=je(Sr,1),cd=H(ld);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 ad(w){return function(T,M,F){for(var U=-1,j=Object(T),G=F(T),J=G.length;J--;){var lt=G[w?J:++U];if(M(j[lt],lt,j)===!1)break}return T}}var ss=ad();function ls(w,T){return w&&ss(w,T,jc)}function k1(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 RC(w){return w!==w}function w1(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?w1(w,T,M):k1(w,RC,M)}var zc=function(w,T,M){typeof T=="function"&&(M=T,T=null),M=Tr(M||Nt);var F=jc(w),U=F.length;if(!U)return M(null);T||(T=U);var j={},G=0,J=!1,lt=Object.create(null),pt=[],at=[],At={};ls(w,function(he,re){if(!Ae(he)){Zt(re,[he]),at.push(re);return}var pe=he.slice(0,he.length-1),ko=pe.length;if(ko===0){Zt(re,he),at.push(re);return}At[re]=ko,is(pe,function(E){if(!w[E])throw new Error("async.auto task `"+re+"` has a non-existent dependency `"+E+"` in "+pe.join(", "));en(E,function(){ko--,ko===0&&Zt(re,he)})})}),e3(),De();function Zt(he,re){pt.push(function(){yo(he,re)})}function De(){if(pt.length===0&&G===0)return M(null,j);for(;pt.length&&G<T;){var he=pt.shift();he()}}function en(he,re){var pe=lt[he];pe||(pe=lt[he]=[]),pe.push(re)}function Fn(he){var re=lt[he]||[];is(re,function(pe){pe()}),De()}function yo(he,re){if(!J){var pe=vo(function(E,Rr){if(G--,arguments.length>2&&(Rr=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pt){ds[Pt]=Pn}),ds[he]=Rr,J=!0,lt=Object.create(null),M(E,ds)}else j[he]=Rr,Fn(he)});G++;var ko=R(re[re.length-1]);re.length>1?ko(j,pe):ko(pe)}}function e3(){for(var he,re=0;at.length;)he=at.pop(),re++,is(n3(he),function(pe){--At[pe]===0&&at.push(pe)});if(re!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function n3(he){var re=[];return ls(w,function(pe,ko){Ae(pe)&&hl(pe,he,0)>=0&&re.push(ko)}),re}};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 OC="[object Symbol]";function _C(w){return typeof w=="symbol"||un(w)&&Ir(w)==OC}var FC=1/0,ud=ft?ft.prototype:void 0,B1=ud?ud.toString:void 0;function dd(w){if(typeof w=="string")return w;if(Ae(w))return ci(w,dd)+"";if(_C(w))return B1?B1.call(w):"";var T=w+"";return T=="0"&&1/w==-FC?"-0":T}function PC(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 NC(w,T,M){var F=w.length;return M=M===void 0?F:M,!T&&M>=F?w:PC(w,T,M)}function hd(w,T){for(var M=w.length;M--&&hl(T,w[M],0)>-1;);return M}function $C(w,T){for(var M=-1,F=w.length;++M<F&&hl(T,w[M],0)>-1;);return M}function HC(w){return w.split("")}var jC="\\ud800-\\udfff",UC="\\u0300-\\u036f",zC="\\ufe20-\\ufe2f",ce="\\u20d0-\\u20ff",oe=UC+zC+ce,VC="\\ufe0e\\ufe0f",WC="\\u200d",qC=RegExp("["+WC+jC+oe+VC+"]");function GC(w){return qC.test(w)}var E1="\\ud800-\\udfff",ZC="\\u0300-\\u036f",x1="\\ufe20-\\ufe2f",QC="\\u20d0-\\u20ff",Ge=ZC+x1+QC,fd="\\ufe0e\\ufe0f",ai="["+E1+"]",Vc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+Vc+"|"+fl+")",md="[^"+E1+"]",gd="(?:\\ud83c[\\udde6-\\uddff]){2}",pd="[\\ud800-\\udbff][\\udc00-\\udfff]",I1="\\u200d",Cd=On+"?",Ad="["+fd+"]?",wn="(?:"+I1+"(?:"+[md,gd,pd].join("|")+")"+Ad+Cd+")*",YC=Ad+Cd+wn,_n="(?:"+[md+Vc+"?",Vc,gd,pd,ai].join("|")+")",JC=RegExp(fl+"(?="+fl+")|"+_n+YC,"g");function T1(w){return w.match(JC)||[]}function Yo(w){return GC(w)?T1(w):HC(w)}function Wc(w){return w==null?"":dd(w)}var bd=/^\s+|\s+$/g;function de(w,T,M){if(w=Wc(w),w&&(M||T===void 0))return w.replace(bd,"");if(!w||!(T=dd(T)))return w;var F=Yo(w),U=Yo(T),j=$C(F,U),G=hd(F,U)+1;return NC(F,j,G).join("")}var Lr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,vd=/,/,KC=/(=.+)?(\s*)$/,yd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function XC(w){return w=w.toString().replace(yd,""),w=w.match(Lr)[2].replace(" ",""),w=w?w.split(vd):[],w=w.map(function(T){return de(T.replace(KC,""))}),w}function D1(w,T){var M={};ls(w,function(F,U){var j,G=_(F),J=!G&&F.length===1||G&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],M[U]=j.concat(j.length>0?lt:F);else if(J)M[U]=F;else{if(j=XC(F),F.length===0&&!G&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");G||j.pop(),M[U]=j.concat(lt)}function lt(pt,at){var At=ci(j,function(Zt){return pt[Zt]});At.push(at),R(F).apply(null,At)}}),zc(M,T)}function Jn(){this.head=this.tail=null,this.length=0}function kd(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):kd(this,w)},Jn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):kd(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(At,Zt,De){if(De!=null&&typeof De!="function")throw new Error("task callback must be a function");if(at.started=!0,Ae(At)||(At=[At]),At.length===0&&at.idle())return C(function(){at.drain()});for(var en=0,Fn=At.length;en<Fn;en++){var yo={data:At[en],callback:De||Nt};Zt?at._tasks.unshift(yo):at._tasks.push(yo)}G||(G=!0,C(function(){G=!1,at.process()}))}function lt(At){return function(Zt){U-=1;for(var De=0,en=At.length;De<en;De++){var Fn=At[De],yo=hl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Zt!=null&&at.error(Zt,Fn.data)}U<=at.concurrency-at.buffer&&at.unsaturated(),at.idle()&&at.drain(),at.process()}}var pt=!1,at={_tasks:new Jn,concurrency:T,payload:M,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Zt){J(At,!1,Zt)},kill:function(){at.drain=Nt,at._tasks.empty()},unshift:function(At,Zt){J(At,!0,Zt)},remove:function(At){at._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!at.paused&&U<at.concurrency&&at._tasks.length;){var At=[],Zt=[],De=at._tasks.length;at.payload&&(De=Math.min(De,at.payload));for(var en=0;en<De;en++){var Fn=at._tasks.shift();At.push(Fn),j.push(Fn),Zt.push(Fn.data)}U+=1,at._tasks.length===0&&at.empty(),U===at.concurrency&&at.saturated();var yo=vo(lt(At));F(Zt,yo)}pt=!1}},length:function(){return at._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return at._tasks.length+U===0},pause:function(){at.paused=!0},resume:function(){at.paused!==!1&&(at.paused=!1,C(at.process))}};return at}function ui(w,T){return ml(w,1,T)}var cs=je(Dr,1);function Jo(w,T,M,F){F=Tr(F||Nt);var U=R(M);cs(w,function(j,G,J){U(T,j,function(lt,pt){T=pt,J(lt)})},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=Nt,Jo(w,T,function(U,j,G){j.apply(M,U.concat(function(J){var lt=o(arguments,1);G(J,lt)}))},function(U,j){F.apply(M,[U].concat(j))})}}var Gc=function(){return qc.apply(null,o(arguments).reverse())},wd=Array.prototype.concat,gl=function(w,T,M,F){F=F||Nt;var U=R(M);Sr(w,T,function(j,G){U(j,function(J){return J?G(J):G(null,o(arguments,1))})},function(j,G){for(var J=[],lt=0;lt<G.length;lt++)G[lt]&&(J=wd.apply(J,G[lt]));return F(j,J)})},S1=je(gl,1/0),Zc=je(gl,1),Qc=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||Nt;var G=!1,J;M(F,function(lt,pt,at){U(lt,function(At,Zt){At?at(At):w(Zt)&&!J?(G=!0,J=T(!0,lt),at(null,si)):at()})},function(lt){lt?j(lt):j(null,G?J:T(!1))})}}function dn(w,T){return T}var as=Qo(di(pl,dn)),Ko=li(di(pl,dn)),Cl=je(Ko,1);function Bd(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 L1=Bd("dir");function M1(w,T,M){M=vo(M||Nt);var F=R(w),U=R(T);function j(J){if(J)return M(J);var lt=o(arguments,1);lt.push(G),U.apply(this,lt)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}G(null,!0)}function Ed(w,T,M){M=vo(M||Nt);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 R1(w,T,M){Ed(w,function(){return!T.apply(this,arguments)},M)}function O1(w,T,M){M=vo(M||Nt);var F=R(T),U=R(w);function j(J){if(J)return M(J);U(G)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}U(G)}function hi(w){return function(T,M,F){return w(T,F)}}function Yc(w,T,M){Zo(w,hi(R(T)),M)}function Al(w,T,M,F){dl(T)(w,hi(R(M)),F)}var fi=je(Al,1);function Jc(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=Qo(di(Kn,Kn)),bl=li(di(Kn,Kn)),Kc=je(bl,1);function _1(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(lt,pt){U[G]=!!pt,J(lt)})},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(lt,pt){lt?J(lt):(pt&&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}),_1("value")))})}function Xc(w,T,M,F){var U=ol(T)?us:Xn;U(w,T,R(M),F||Nt)}var ta=Qo(Xc),vl=li(Xc),ea=je(vl,1);function F1(w,T){var M=vo(T||Nt),F=R(Jc(w));function U(j){if(j)return M(j);F(U)}U()}var na=function(w,T,M,F){F=F||Nt;var U=R(M);Sr(w,T,function(j,G){U(j,function(J,lt){return J?G(J):G(null,{key:lt,val:j})})},function(j,G){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<G.length;pt++)if(G[pt]){var at=G[pt].key,At=G[pt].val;lt.call(J,at)?J[at].push(At):J[at]=[At]}return F(j,J)})},gi=je(na,1/0),N=je(na,1),q=Bd("log");function V(w,T,M,F){F=Tr(F||Nt);var U={},j=R(M);Dr(w,T,function(G,J,lt){j(G,J,function(pt,at){if(pt)return lt(pt);U[J]=at,lt()})},function(G){F(G,U)})}var ht=je(V,1/0),Et=je(V,1);function Vt(w,T){return T in w}function Be(w,T){var M=Object.create(null),F=Object.create(null);T=T||pl;var U=R(w),j=i(function(J,lt){var pt=T.apply(null,J);Vt(M,pt)?C(function(){lt.apply(null,M[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var at=o(arguments);M[pt]=at;var At=F[pt];delete F[pt];for(var Zt=0,De=At.length;Zt<De;Zt++)At[Zt].apply(null,at)})))});return j.memo=M,j.unmemoized=w,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var oa=h(qt);function xd(w,T,M){M=M||Nt;var F=ol(T)?[]:{};w(T,function(U,j,G){R(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,G(J)})},function(U){M(U,F)})}function Bn(w,T){xd(Zo,w,T)}function yl(w,T,M){xd(dl(T),w,M)}var Id=function(w,T){var M=R(w);return ml(function(F,U){M(F[0],U)},T,1)},pi=function(w,T){var M=Id(w,T);return M.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(M.started=!0,Ae(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,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};G?M._tasks.insertBefore(G,pt):M._tasks.push(pt)}C(M.process)},delete M.unshift,M};function kl(w,T){if(T=Tr(T||Nt),!Ae(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();Jo(U,T,M,F)}function Wt(w){var T=R(w);return i(function(F,U){return F.push(function(G,J){if(G)U(null,{error:G});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function P1(w){var T;return Ae(w)?T=ci(w,Wt):(T={},ls(w,function(M,F){T[F]=Wt.call(this,M)})),T}function Td(w,T,M,F){Xc(w,T,function(U,j){M(U,function(G,J){j(G,!J)})},F)}var wl=Qo(Td),Dd=li(Td),N1=je(Dd,1);function $1(w){return function(){return w}}function Ai(w,T,M){var F=5,U=0,j={times:F,intervalFunc:$1(U)};function G(at,At){if(typeof At=="object")at.times=+At.times||F,at.intervalFunc=typeof At.interval=="function"?At.interval:$1(+At.interval||U),at.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")at.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof w=="function"?(M=T||Nt,T=w):(G(j,w),M=M||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=R(T),lt=1;function pt(){J(function(at){at&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(at))?setTimeout(pt,j.intervalFunc(lt)):M.apply(null,arguments)})}pt()}var Xo=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){xd(cs,w,T)}var El=Qo(di(Boolean,pl)),Mr=li(di(Boolean,pl)),xl=je(Mr,1);function Sd(w,T,M){var F=R(T);Uc(w,function(j,G){F(j,function(J,lt){if(J)return G(J);G(null,{value:j,criteria:lt})})},function(j,G){if(j)return M(j);M(null,ci(G.sort(U),_1("value")))});function U(j,G){var J=j.criteria,lt=G.criteria;return J<lt?-1:J>lt?1:0}}function Il(w,T,M){var F=R(w);return i(function(U,j){var G=!1,J;function lt(){var pt=w.name||"anonymous",at=new Error('Callback function "'+pt+'" timed out.');at.code="ETIMEDOUT",M&&(at.info=M),G=!0,j(at)}U.push(function(){G||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var H1=Math.ceil,Tl=Math.max;function bi(w,T,M,F){for(var U=-1,j=Tl(H1((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);Sr(bi(0,w,1),T,U,F)}var j1=je(vi,1/0),U1=je(vi,1);function z1(w,T,M,F){arguments.length<=3&&(F=M,M=T,T=Ae(w)?[]:{}),F=Tr(F||Nt);var U=R(M);Zo(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||Nt,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||Nt);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 V1(w,T,M){Ll(function(){return!w.apply(this,arguments)},T,M)}var Ld=function(w,T){if(T=Tr(T||Nt),!Ae(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([])},t3={apply:r,applyEach:sd,applyEachSeries:cd,asyncify:v,auto:zc,autoInject:D1,cargo:ui,compose:Gc,concat:S1,concatLimit:gl,concatSeries:Zc,constant:Qc,detect:as,detectLimit:Ko,detectSeries:Cl,dir:L1,doDuring:M1,doUntil:R1,doWhilst:Ed,during:O1,each:Yc,eachLimit:Al,eachOf:Zo,eachOfLimit:Dr,eachOfSeries:cs,eachSeries:fi,ensureAsync:Jc,every:mi,everyLimit:bl,everySeries:Kc,filter:ta,filterLimit:vl,filterSeries:ea,forever:F1,groupBy:gi,groupByLimit:na,groupBySeries:N,log:q,map:Uc,mapLimit:Sr,mapSeries:ld,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:Be,nextTick:oa,parallel:Bn,parallelLimit:yl,priorityQueue:pi,queue:Id,race:kl,reduce:Jo,reduceRight:Ci,reflect:Wt,reflectAll:P1,reject:wl,rejectLimit:Dd,rejectSeries:N1,retry:Ai,retryable:Xo,seq:qc,series:Bl,setImmediate:C,some:El,someLimit:Mr,someSeries:xl,sortBy:Sd,timeout:Il,times:j1,timesLimit:vi,timesSeries:U1,transform:z1,tryEach:Dl,unmemoize:Sl,until:V1,waterfall:Ld,whilst:Ll,all:mi,allLimit:bl,allSeries:Kc,any:El,anyLimit:Mr,anySeries:xl,find:as,findLimit:Ko,findSeries:Cl,forEach:Yc,forEachSeries:fi,forEachLimit:Al,forEachOf:Zo,forEachOfSeries:cs,forEachOfLimit:Dr,inject:Jo,foldl:Jo,foldr:Ci,select:ta,selectLimit:vl,selectSeries:ea,wrapSync:v};e.default=t3,e.apply=r,e.applyEach=sd,e.applyEachSeries=cd,e.asyncify=v,e.auto=zc,e.autoInject=D1,e.cargo=ui,e.compose=Gc,e.concat=S1,e.concatLimit=gl,e.concatSeries=Zc,e.constant=Qc,e.detect=as,e.detectLimit=Ko,e.detectSeries=Cl,e.dir=L1,e.doDuring=M1,e.doUntil=R1,e.doWhilst=Ed,e.during=O1,e.each=Yc,e.eachLimit=Al,e.eachOf=Zo,e.eachOfLimit=Dr,e.eachOfSeries=cs,e.eachSeries=fi,e.ensureAsync=Jc,e.every=mi,e.everyLimit=bl,e.everySeries=Kc,e.filter=ta,e.filterLimit=vl,e.filterSeries=ea,e.forever=F1,e.groupBy=gi,e.groupByLimit=na,e.groupBySeries=N,e.log=q,e.map=Uc,e.mapLimit=Sr,e.mapSeries=ld,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=Be,e.nextTick=oa,e.parallel=Bn,e.parallelLimit=yl,e.priorityQueue=pi,e.queue=Id,e.race=kl,e.reduce=Jo,e.reduceRight=Ci,e.reflect=Wt,e.reflectAll=P1,e.reject=wl,e.rejectLimit=Dd,e.rejectSeries=N1,e.retry=Ai,e.retryable=Xo,e.seq=qc,e.series=Bl,e.setImmediate=C,e.some=El,e.someLimit=Mr,e.someSeries=xl,e.sortBy=Sd,e.timeout=Il,e.times=j1,e.timesLimit=vi,e.timesSeries=U1,e.transform=z1,e.tryEach=Dl,e.unmemoize=Sl,e.until=V1,e.waterfall=Ld,e.whilst=Ll,e.all=mi,e.allLimit=bl,e.allSeries=Kc,e.any=El,e.anyLimit=Mr,e.anySeries=xl,e.find=as,e.findLimit=Ko,e.findSeries=Cl,e.forEach=Yc,e.forEachSeries=fi,e.forEachLimit=Al,e.forEachOf=Zo,e.forEachOfSeries=cs,e.forEachOfLimit=Dr,e.inject=Jo,e.foldl=Jo,e.foldr=Ci,e.select=ta,e.selectLimit=vl,e.selectSeries=ea,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(cp,cp.exports);var xb={exports:{}},ap=xb.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?ap(n,t):i};ap.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=ap(n,t)}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=t||16,o};var Ib=Ui,CS=Bb,AS=Eb,Yh=$o,up=cp.exports,bS=xb.exports,Tb=Hs.ACTIONS,Db=Re;function Re(n,t){if(Ib.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}Ib.mixin(Re),Re.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Re.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Re.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||bS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Re.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);up.parallel([function(i){up.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();up.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Re.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Tb.presenceSubscribe:Tb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Re.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._receiveUpdate=function(n,t){var e=Yh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Yh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Re.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Re.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Re.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Re.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Re.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Re.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Re.prototype._callbackOrEmit=function(n,t){if(t)return Yh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new CS(this,n)},Re.prototype._createRemotePresence=function(n){return new AS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=Yh.callEach(n,t);!e&&t&&this.emit("error",t)};var Qa=Bb,Sb=Wh,vS=$o,Lb=Sb.CODES,yS=jo;function jo(n,t){Qa.call(this,n,t),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()}jo.prototype=Object.create(Qa.prototype),jo.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Lb.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Qa.prototype.submit.call(this,n,t)},jo.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),Qa.prototype.destroy.call(this,n)},jo.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(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},jo.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)},jo.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},jo.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},jo.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},jo.prototype._message=function(){var n=Qa.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},jo.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!vS.supportsPresence(o))throw new Sb(Lb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Mb={};(function(n){var t=qa,e=Wh,o=$o,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(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 e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(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 e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(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 e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(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 e(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=t.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===t.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=t.defaultType.apply(h,[C]))}}}}})(Mb);var Ya=Eb,kS=Mb,wS=ho;function ho(n,t){Ya.call(this,n,t),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(Ya.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),Ya.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,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Ya.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Ya.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ho.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}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],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):kS.transformPresence(this._pending,t,e)}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,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Rb=Db,BS=yS,ES=wS;function Xl(n,t,e){var o=Xl.channel(t,e);Rb.call(this,n,o),this.collection=t,this.id=e}var xS=Xl;Xl.prototype=Object.create(Rb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new BS(this,n)},Xl.prototype._createRemotePresence=function(n){return new ES(this,n)};var IS=TS;function TS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var DS=IS,Ob=Ui,_b=Ja;function Ja(n,t,e,o,r){if(Ob.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}Ob.mixin(Ja),Ja.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ja.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ja.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new DS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Fb=_b,SS=$o,LS=Hs.ACTIONS,MS=dp;function dp(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!SS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}dp.prototype=Object.create(Fb.prototype),dp.prototype._message=function(){return{a:LS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Pb=_b,RS=$o,OS=Hs.ACTIONS,_S=hp;function hp(n,t,e,o,r,i){if(Pb.call(this,n,t,e,o,i),!RS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}hp.prototype=Object.create(Pb.prototype),hp.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=Db,Nb=xS,$S=MS,HS=_S,$b=Ui,tc=Wh,ne=Hs.ACTIONS,Hb=qa,Uo=$o,Ka=gb,Xa=tc.CODES;function jb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var jS=Bt;function Bt(n){$b.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=jb(n),this.bindToSocket(n)}$b.mixin(Bt),Bt.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 t=jb(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ka.warn("Failed to parse message",o);return}e.debug&&Ka.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){Uo.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},Bt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Ub(n.error,n),delete n.error),n.a){case ne.initLegacy:return this._handleLegacyInit(n);case ne.handshake:return this._handleHandshake(t,n);case ne.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ne.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ne.queryUnsubscribe:return;case ne.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case ne.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ne.bulkSubscribe:case ne.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ne.snapshotFetch:case ne.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ne.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ne.subscribe:case ne.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ne.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ne.presence:return this._handlePresence(t,n);case ne.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ne.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ne.presenceRequest:return this._handlePresenceRequest(t,n);case ne.pingPong:return this._handlePingPong(t);default:Ka.warn("Ignoring unrecognized message",n)}};function Ub(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Bt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](Ub(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Ka.error("Invalid bulk message",t)},Bt.prototype._reset=function(){this.agent=null},Bt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new tc(Xa.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}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,t),this.emit("state",n,t)}},Bt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Bt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},Bt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[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:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},Bt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Bt.prototype.sendFetch=function(n){return this._sendActions(ne.fetch,n,n.version)},Bt.prototype.sendSubscribe=function(n){return this._sendActions(ne.subscribe,n,n.version)},Bt.prototype.sendUnsubscribe=function(n){return this._sendActions(ne.unsubscribe,n)},Bt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ne.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},Bt.prototype.send=function(n){this.debug&&Ka.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Bt.prototype.ping=function(){if(!this.canSend)throw new tc(Xa.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ne.pingPong};this.send(n)},Bt.prototype.close=function(){this.socket.close()},Bt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Bt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new FS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},Bt.prototype._destroyDoc=function(n){!n._wantsDestroy||(Uo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Bt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Bt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new PS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},Bt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Bt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ne.queryFetch,n,t,e,o)},Bt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ne.querySubscribe,n,t,e,o)},Bt.prototype.hasPending=function(){return!!(this._firstDoc(Jh)||this._firstQuery(Jh)||this._firstSnapshotRequest())};function Jh(n){return n.hasPending()}Bt.prototype.hasWritePending=function(){return!!this._firstDoc(US)};function US(n){return n.hasWritePending()}Bt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Jh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Jh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}Uo.nextTick(n)},Bt.prototype._nothingPendingRetry=function(n){var t=this;return function(){Uo.nextTick(function(){t.whenNothingPending(n)})}},Bt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},Bt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Bt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Bt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new $S(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new HS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Bt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Bt.prototype._initializeHandshake=function(){this.send({a:ne.handshake,id:this.id})},Bt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Bt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Bt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Xa.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Hb.map[n.type]!==Hb.defaultType)return this.emit("error",new tc(Xa.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Xa.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Bt.prototype.getPresence=function(n){var t=this,e=Uo.digOrCreate(this._presences,n,function(){return new NS(t,n)});return e._wantsDestroy=!1,e},Bt.prototype.getDocPresence=function(n,t){var e=Nb.channel(n,t),o=this,r=Uo.digOrCreate(this._presences,e,function(){return new Nb(o,n,t)});return r._wantsDestroy=!1,r},Bt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},Bt.prototype._addPresence=function(n){Uo.digOrCreate(this._presences,n.channel,function(){return n})},Bt.prototype._handlePresenceSubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Bt.prototype._handlePresenceUnsubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Bt.prototype._handlePresence=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Bt.prototype._handlePresenceRequest=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var zb=jS,zS=qa;const Kh={err:1001,msg:"user auth error",name:"AuthError"},VS={err:1002,msg:"you don't have required permission",name:"PermissionError"},fp={err:1003,msg:"Too many user connected",name:"MaxUserError"},tu={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"},eu="x-live-editor-token",Xh="x-live-editor-base-url",Cn=S("auth-connection");function GS(n){try{n()}catch(t){Cn.error(t)}}class ZS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new G3.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Mi(this.getBaseURL())}async auth(t){g(Cn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[eu]:t.token,[Xh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Xh]:Mi(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new $B.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(zb.prototype),g(Cn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};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}}},zb.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 t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){Cn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else Cn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Kh.msg);t.code=Kh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(tu.msg);t.code=tu.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===Kh.err)Cn.warn("auth error"),this.handleAuthError();else if(o===fp.err)Cn.warn(fp.msg),this.emitMaxUsersError();else if(o===tu.err){Cn.warn(tu.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(e)}`),this.emitAuthError()}get(t,e){return g(Cn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(Cn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(Cn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(Cn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),GS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}S("utils/file");function QS(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}QS();async function YS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new HB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Mi(i)}const fr=S("sharedb-doc/client");class JS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(fr,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),fr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;zS.register(Ud.type),this.connection=new ZS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(fr,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,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(t){const o=`${this.apiServer()}/resources`;let r=[];t.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,{[eu]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{fr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await YS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return fr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(fr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[eu]:this.connection.token},e,o);return g(fr,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=e||{};a.url=t,a.headers||(a.headers={}),g(fr,o,"no token"),a.headers={...a.headers,[eu]:o,[Xh]:this.connection.getBase64BaseURL()};try{return await PB.default(t,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(fr,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=NB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(fr,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(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${Mi(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function KS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const mp=S("block-ids");class XS{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);g(mp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);g(mp,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class tL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new XS,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return g(mp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Vb{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const gp=S("op-parse-handler");class eL{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,o=new Map,r=new tL,i=t.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&&(gp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;e.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(e.has(a)){gp.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 Vb,o.set(d,h)),h.delete(l.key)}else g(gp,!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 Vb,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 Oe=S("op-parser");class Wb{}class pp{constructor(t){m(this,"key");this.key=t}}function nL(n,t,e){const o=t.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(Oe,s.id,"block id is required"),g(Oe,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 e.onInsertBlock(n,r,s),!0}function Cp(n,t,e,o){if(e==="upsert"&&nL(n,t,o))return;g(Oe,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.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(Oe,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Oe,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Oe,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Oe,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Oe,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Oe,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Wb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Oe,typeof l=="string","data is not string"),g(Oe,l!=="text","data !== 'text'"),g(Oe,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Wb?o.onDeleteBlock(n,i):l instanceof pp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function oL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function rL(n,t,e){const o=n[1],r=n[2];g(Oe,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Oe,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Oe.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Oe.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ap(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ap(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){oL(n);return}if(r==="comments"){rL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Cp(i,s,t,e)}):n.slice(1).forEach(s=>{Cp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Oe,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Cp(i,n.slice(1),t,e)}function qb(n,t,e){const o=new eL(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{Ap(a,i,o)}):Ap(s,i,o)}o.end()}const iL=S("sharedb-comments");function bp(n){const t=n.blocks;g(iL,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),mt.default(e)}function Gb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function vp(n,t){const e=zD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const se=S("sharedb-doc/doc-container"),Zb="ot-json1";Ud.type.registerSubtype(VD.type),Ud.type.name=Zb,Ud.type.invert=null;class nu extends fa{constructor(e,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",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);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",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!ua.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 e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){se.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(se.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),se.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(se.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Zb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const o=e.map(({containerId:r,blocks:i})=>[ji(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async e=>{const o=[ji(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[ji(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[ji(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ji(e),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(e,o,r)=>{const i=[ji(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){se.warn("handleOp: destroyed");return}try{qb(e,this,!!o)}catch(i){throw se.error(i),i}});this.client=e,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(se,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new JS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new nu(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||KS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw se.error(o),se.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}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((e,o)=>{if(this.localPresence)e();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()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return Wa(this.data())}getContainerBlocks(e){const o=this.data();g(se,o,"no doc data");const r=o[ji(e)];return g(se,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(se,r,"no doc data");const i=r[ji(e)];g(se,i,`no container data: ${e}`);const s=i[o];return g(se,s,`no block data: ${o}`),mt.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(se,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(se,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Gb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return bp(o)}localCreateComment(e,o){const r=vp(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=vp(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Kl(e),o,r)})}onInsertBlock(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Kl(e),o,r,i)})}onDeleteContainer(e,o){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Kl(e),o)})}onCreateContainer(e,o,r){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Kl(e),o,r)})}onDeleteComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(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:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return Wa(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Wa(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Wa(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Wa(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){qb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Qb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,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 Yb=S("remote-cursor-decorator");class yp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Yb,typeof s=="string","invalid path containerId"),g(Yb,typeof l=="number","invalid path blockIndex");const a=t.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 Jb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Gt(Vr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=et(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function sL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).addListener("change",t)}function lL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).removeListener("change",t)}const Ent="",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 xnt="";S("button");function fo(n,t,e,o,r){const i=k("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}const Int="",Kb=`<?xml version="1.0" ?>
|
|
27
|
+
`)}const nT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ue||g(nT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=ot(r),l=ct(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Gl=S("insert-text");function Ig(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Gl,r,"no block data"),g(Gl,r.text,"no block text"),rn(r.text)===0)return g(Gl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Ve(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function oT(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return Ig(n,r,i,e)}function R6(n,t,e,o,r){const i=ot(t),s=ct(i),l=bt(t),a=oT(n,t,e),d=Ch(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),pn(n,t)}function O6(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=Ch(e," ",o);return n.doc.localUpdateBlockText(i,s,l),pn(n,t)}function rT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Gl,typeof r.insert=="string","invalid text op, no insert");const i=e+Ah(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Tg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Gl,i,"no block data"),g(Gl,i.text,"no block text");const s=Ig(n,e,o,r);s&&Object.keys(s).includes("link")&&(rT(i.text,r)||delete s.link);const l=Ch(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),pn(n,n.getBlockById(i.id))}function Dg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ql(n);Tg(n,t,e,o,r)}const Dh=S("update-composition-text");function _6(n){const t=n.selection.range.start;t instanceof Ue||g(Dh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(Dh,nt(n,o),"not a text kind block");const r=ot(o),i=ct(r),s=bt(o),l=n.doc.getBlockData(i,s);g(Dh,l,"no block data in doc"),g(Dh,l.text,"no text data in text block");const a=Lt(o);fh(n,Ri(o),e,a,l.text)}function F6(n){_x(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Pa=S("delete-block-text");function Sg(n,t,e,o,r){if(!n.isBlockWritable(t))return Pa.error("block is not writable"),0;g(Pa,nt(n,t),"block is not a text kind block");const i=ot(t),s=ct(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Pa,a,"no block data in doc"),g(Pa,a.text,"no text data in text block");let d=e;sn(t,e)||(d=_i(t,d));let h=e+o;g(Pa,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=_s(t,h));const p=h-d,C=q4(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const Lg=S("break-text-block");function P6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Lg,nt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Lg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=ot(t),i=ct(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?P6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...ar(""),...l,...o==null?void 0:o.newBlockData},D=ke(n,t.id,0),x=Zl(n,i,v,B,D);return{block:t,newBlock:x}}g(Lg,sn(t,e),"not a valid offset");const a=pn(n,t),{right:d}=Tn(a,e),h=rn(d);h>0&&Sg(n,t,e,h);const p={...ar(d),...l,...o==null?void 0:o.newBlockData},C=Zl(n,i,s+1,p,ke(n,p.id,0));return{block:t,newBlock:C}}const iT=S("prepare-insert-new-block");function sT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=me(d);return g(iT,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=ct(ot(r)),e=bt(r),!nt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Ql(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const lT=S("auto-insert-block");function N6(n,t,e,o,r,i){const s=sT(n,e,o);g(lT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Zl(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const cT=S("delete-block");function Sh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Sh(n,i,e)})}))}function Lh(n,t,e){const o=ot(t),r=ct(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(cT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,ze(n,{anchor:e.start,focus:e.end})),s}function Mg(n,t,e){return n.undoManager.runInGroup(()=>{const o=ot(t);To(o)===1&&n.insertTextBlock("",ct(o),0);let r=e?Oi(n,e):null;if(!r){const l=n.selection.range;D6(t,l)?r=S6(n,t):r=l}const i=Lh(n,t,r),s=[];return Sh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function aT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Sh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function $6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Sh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Rg=S("merge-text-block");function H6(n,t,e){g(Rg,nt(n,t),"only text block can be merged"),g(Rg,nt(n,e),"only text block can be merged");const o=Pi(n,t),r=Pi(n,e),i=o.text,s=r.text;g(Rg,i&&s,"block data has no text");const l=ot(t),a=ct(l),d=bt(t),h=ut(n,t),p=Tg(n,s,a,d,h),C=ke(n,t,rn(i));return Mg(n,e,C),p}const ur=S("clear-selected-contents");function Mh(n,t){g(ur,nt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(ur,e.isSimple(),"not a simple block position"),g(ur,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(ur,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function j6(n,t,e){const o=ct(t),r=me(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function uT(n,t){const{block:e,start:o,end:r}=t;if(nt(n,e)){Mh(n,t);return}if(Ie(e)||o.isSimple()){g(ur,r.isSimple(),"invalid range");const s=ot(e),l=bt(e),a=n.insertTextBlock("",ct(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(ur,Mt(n,e),"invalid block kind"),g(ur,!o.isSimple()&&!r.isSimple(),"invalid range"),Ms(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{j6(n,s,{focus:l===0})})}function dT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(ur,e.length>0,"no selected block"),e.length===1){uT(n,e[0]);return}const o=e[0],r=o.block,i=ot(r);g(ur,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(nt(n,r)){Mh(n,o);const h=ke(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),nt(n,l)){Mh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(nt(n,l)){Mh(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===To(i)){j6(n,i,{focus:!0});return}const a=ae(r),d=Qt(l);g(ur,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Og(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),dT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const hT=S("core");function U6(n,t,e){const o=ot(t),r=ct(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),pn(n,t)}function z6(n,t,e){if(!n.isBlockWritable(t)){hT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);U6(n,t,r)}function Rh(n,t,e){const o=pn(n,t),r=typeof e=="string"?Fi(e):e,i=ln.diff(o,r);return U6(n,t,i)}const Na=S("update-block-data");function Oh(n,t,e,o){const r=ot(t),i=ct(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;Na.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(e).forEach(([C,v])=>{g(Na,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(Na.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(ua.default(B,v)||C==="text"&&ln.diff(B,v).length===0||(d.has(C)?(Na.debug(`replace key: ${C}`),a.delete.push(C)):Na.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Pi(n,t)}function V6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function _g(n,t,e){if(!Mt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=zn(n,t).getChildContainers(n,t)[0],i=ye(r);_g(n,i,e)}function Ns(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const $a=S("clone-block");function Ni(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g($a,e!==p,"invalid child block"),Ni(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),C=t.blocks[h];g($a,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Ni(n,t,_,o)),B=Ns(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 $a.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${C}_`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}_${D}`;return $a.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(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Fg(n,t,e,o){const r=t.blocks[e];g($a,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Ni(n,t,l,o));return Ns(i)}function Pg(n,t,e){const o=t.blocks.root.map(r=>Ni(n.editorBlocks,t,r,e));return mt.default(Ns(o))}const W6=S("insert-doc");function q6(n,t,e,o,r){if(Mt(n,t)){W6.warn("failed to insert doc into a complex block");return}const i=Pg(n,o,r),s=ot(t),l=bt(t),a=ct(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,z,Z;const d=[];Object.entries(i.blocks).forEach(([tt,ft])=>{tt!=="root"&&d.push({containerId:tt,blocks:ft})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(Ie(t)){n.deleteBlock(t);let tt;h.reverse().forEach(ft=>{const vt=n.insertBlock(a,l,ft,void 0,{noFocus:!0});tt||(tt=vt)}),tt&&n.selection.selectBlock(tt,ut(n,tt));return}if(g(W6,nt(n,t),"not a text block"),ue(n,t)){const tt=a==="root"&&n.getBlockByIndex(a,0)===t,ft=bt(t);let vt;h.forEach((zt,Ht)=>{const Kt=n.insertBlock(a,ft+Ht,zt,void 0,{noFocus:!0});Ht===h.length-1&&(vt=Kt)}),vt&&n.selection.selectBlock(vt,ut(n,vt)),tt&&n.deleteBlock(t);return}if(h.length===1){const tt=h[0];if(wa(n,tt.type)){n.insertTextToBlock(t,e,(H=tt.text)!=null?H:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,tt);return}const p=e===ut(n,t),C=e===0,v=h[0],B=h[h.length-1];let D;!p&&!C?D=n.breakTextBlock(t,e,{forceInsertAfter:!0}):D=t;const x=C?l:l+1;p?(D=n.insertBlock(a,l+1,B),n.selection.selectBlock(D,ut(n,D))):(n.selection.selectBlock(D,0),wa(n,B.type)?n.insertTextToBlock(D,0,(z=B.text)!=null?z:[]):n.insertBlock(a,x,B));const _=n.selection.range;let R=x;wa(n,v.type)?C?(n.insertBlock(a,x,v),R+=1):n.insertTextToBlock(t,e,(Z=v.text)!=null?Z:[]):(n.insertBlock(a,x,v),R+=1),h.slice(1,h.length-1).reverse().forEach(tt=>{n.insertBlock(a,R,tt)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function Ng(n,t,e,o,r){const i=Pg(n,o,r),s=ct(t),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,e,h,void 0,{noFocus:!0,noScroll:!0});l.push(p)})}),l}function G6(n,t,e){const o=To(t);Ng(n,t,o,e);for(let r=0;r<o;r++){const i=ye(t);n.deleteBlock(i)}}const Ha=S("add-text-attribute");function fT(n,t,e,o){const{start:r,end:i}=e;g(Ha,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Ha,o,"invalid attribute name");const s=n.getBlockText(t),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Z6(n,t,e,o,r){const{start:i,end:s}=e;g(Ha,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Ha,o,"invalid attribute name");const l=n.getBlockText(t),a=La(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Yl(n,t,e,o,r){const{start:i,end:s}=e;g(Ha,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=e6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Q6(n,t,e,o){const r=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!nt(n,s))return;if(ue(n,s)){o(n,it(s),t,e);return}const d=ze(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Yl(n,s,d,t,e):(Yl(n,s,d,"color",null),Yl(n,s,d,"backgroundColor",null))})})}function Y6(n,t,e){const o=Oo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!nt(n,i))return;if(ue(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=ze(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Yl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Yl(n,i,a,"backgroundColor",null)})})}function $g(n,t){const e=Oo(n,{simpleBlockOnly:!0}).filter(s=>nt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return r6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Wn=S("adjust-selection-pos");function J6(n){const t=[];for(;n;){const e=ot(n);if(t.unshift(e),Gt(e))return t;const o=et(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function K6(n,t){for(;t;){const e=ot(t);if(e===n)return t;const o=et(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function mT(n,t){const e=J6(n),o=J6(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=K6(r,n),s=K6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function X6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=ot(e);g(Wn,Mo(o),"not a child container");const r=et(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function _h(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ue&&e instanceof Ue?{anchor:t,focus:e}:t instanceof Ro&&e instanceof Ro?dh(n,o,t,e):null;const i=ot(o),s=ot(r);if(i===s)return t instanceof Ro&&(t=st(o,0,"home")),e instanceof Ro&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof Ue,"not valid position type"),g(Wn,e instanceof Ue,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ue&&e instanceof Ro){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=et(i);if(D&&D===et(B)){const x=fe(D,ct(i)),_=fe(D,ct(B));return dh(n,D,x,_)}}return null}const l=Gd(o,r)>0,{newBlock1:a,newBlock2:d}=mT(o,r);if(a===d){const B=a,D=X6(B,o),x=X6(B,r);return t=fe(a,ct(D)),e=fe(a,ct(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),dh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof Ue&&(h=t.offset);let C=l?0:ut(n,d);return d===r&&e instanceof Ue&&(C=e.offset),t=st(a,h,l?"end":"home"),e=st(d,C,l?"home":"end"),{anchor:t,focus:e}}const gT=S("move-complex-block-position");function pT(n,t,e){const o=n.getBlockById(t.blockId);g(gT,Mt(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,ct(s)):null}const ja=S("move-simple-block-position");function tA(n,t){const e=gn(n,t,{visibleOnly:!0});g(ja,e.length>0,"complex block has not any child container");const o=e[0];return ye(o)}function eA(n,t){const e=gn(n,t,{visibleOnly:!0});g(ja,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qe(o)}function nA(n,t,e){const o=e?tA(n,t):eA(n,t);return Mt(n,o)?nA(n,o,e):o}function CT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?tA(n,e):Ts(e)}function AT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?eA(n,e):Is(e)}function Hg(n){return n==="ArrowLeft"||n==="ArrowUp"}function jg(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);g(ja,r,"child container has not parent block"),g(ja,Mt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?Hg(e)?Qe(i):ye(i):jg(n,r,e)}function bT(n,t,e){const o=ot(t);if(Gt(o))return null;const r=et(o);if(g(ja,r,"child container has not parent block"),Hg(e)){const l=ae(r);if(l)return l}else{const l=Qt(r);if(l)return l}const i=jg(n,r,e);if(i)return i;let s=r;for(;!Gt(ot(s));)s=et(ot(s));return Hg(e)?ae(s):Qt(s)}function vT(n,t,e){return!Mt(n,t)||zn(n,t).enableKeyboardSelect?t:nA(n,t,e==="ArrowDown"||e==="ArrowRight")}function yT(n,t,e){const o=n.getBlockById(t.blockId),i=Yt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?CT(n,t):AT(n,t);if(s||(s=jg(n,o,e),s||(s=bT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Gt(ot(o)))return null;const l=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(l,0,"home")}return null}if(s=vT(n,s,e),nt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Gx(n,s,o,t,l);if(e==="ArrowUp")return qx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function kT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(nt(n,r))return o;const i=Qt(r);if(i)return st(i,0,"home");if(!Gt(ot(r))||n.readonly)return o;const s=n.insertTextBlock("",ct(n.rootContainer),To(n.rootContainer));return st(s,0,"home")}function wT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=kT(n,t,o):r=yT(n,o.getFocusedPos(),t);else if(r=pT(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Qe(s);r=st(l,0,"home")}else{const l=ye(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:_h(n,o.anchor,r):null}function $i(n,t,e){const o=wT(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function oA(n){return $i(n,"ArrowLeft","move"),!0}function rA(n){return $i(n,"ArrowRight","move"),!0}function iA(n){return $i(n,"ArrowUp","move"),!0}function sA(n){if($i(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=ot(t);if(Gt(e)||Qe(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",ct(o),To(o)),!0}function lA(n){return $i(n,"ArrowDown","select"),!0}function cA(n){return $i(n,"ArrowLeft","select"),!0}function aA(n){return $i(n,"ArrowRight","select"),!0}function uA(n){return $i(n,"ArrowUp","select"),!0}const dA=S("word-offset");function Ug(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"home");if(e.offset===0||!nt(n,o)){const s=ae(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&nt(n,s)){const a=bg(n,s,l.offset);return st(s,a,"normal")}return l}const r=bg(n,o,e.offset);return st(o,r,"normal")}function zg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!nt(n,o)){const s=Qt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&nt(n,s)){const a=vg(n,s,l.offset);return st(s,a,"end")}return l}const r=vg(n,o,e.offset);return st(o,r,"normal")}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Vg(n,t){if(!Mt(n,t))return t;const o=zn(n,t).getChildContainers(n,t)[0],i=me(o)[0];return Vg(n,i)}function Wg(n,t){if(!Mt(n,t))return t;const e=zn(n,t).getChildContainers(n,t),o=e[e.length-1],r=me(o),i=r[r.length-1];return Wg(n,i)}function qg(n){const t=Wg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function pA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function CA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Gg(n){const t=Wg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const AA=S("line-offset");function bA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!nt(n,e))return st(e,0,"home");let r=j4(e,t).start;const{next:i}=lh(e,r);return i&&co(i)&&ka(i)==="br"&&(r+=1),st(e,r,"home")}function vA(n){const t=n.selection.range.focus;g(AA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!nt(n,e))return st(e,ut(n,e),"end");const o=j4(e,t);return st(e,o.end,"end")}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const EA=S("find-block-position");function BT(n,t,e,o){g(EA,Mt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(EA,r.length>0,"complex block has not any child container");const i=Lo(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=S4(n,t,s,l);return Zg(n,a,e,o)}function Zg(n,t,e,o){if(Mt(n,t))return BT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=Lo(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const C=st(r,p,"normal"),v=Lo(n,t,C),B=or(v,l,a);B<i&&(i=B,d=C)}return d}const xA=S("page-offset");function ET(n,t){const e=x6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<ZI(n))return n.getFirstBlock();const i=ae(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ae(s)}return n.getFirstBlock()}function xT(n,t){const e=x6(n)*.9,o=t.getBoundingClientRect(),r=QI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Qt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Qt(l)}return n.getLastBlock()}function IA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ET(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Zg(n,o,e,t),r}function TA(n){const t=n.selection.range.focus;g(xA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=xT(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Zg(n,o,e,t),r}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);if(!e)return!1;const o=_h(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);if(!e)return!1;const o=_h(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Ua=S("select-all");function RA(n,t){const e=ye(n),o=Qe(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function IT(n,t){const e=t.getEditor(),o=zn(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===ct(r)&&t.end.blockId===s&&t.end.childContainerId===ct(i)}function TT(n,t){g(Ua,t,"no parent block"),g(Ua,Mt(n,t),"not a complex block");const e=zn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(ze(n,{anchor:fe(t,ct(o)),focus:fe(t,ct(r))}))}function OA(n,t){const e=ot(t);Qg(n,e)}function _A(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&nt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),OA(n,ye(n.rootContainer)),!1}return g(Ua,!e.isSimple(),"invalid range type"),IT(t,e)?(OA(n,t),!1):(g(Ua,t,"no parent block"),g(Ua,Mt(n,t),"not a complex block"),TT(n,t),!0)}function Qg(n,t){const e=me(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function DT(n){Gg(n),n.focus()}const Yg=S("selected-block-to-doc");function FA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{FA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Fh(n,t){const e=Yt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Pi(n,t.block));if(nt(n,t.block)){const i=t.start,s=t.end;if(g(Yg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=Ve(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Ie(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Yg,Mt(n,t.block),"not complex block"),g(Yg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return FA(n,o,r),r}function Jg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Fh(n,{block:t,start:e,end:o})}const ST=S("block-to-doc");function LT(n,t){g(ST,t.length>0,"invalid params, no blocks");const e=t.map(o=>Jg(n,o));return Ns(e)}function Ph(n){const e=n.selection.range.getSelectedBlocks().map(o=>Fh(n,o));return Ns(e)}function PA(n,t){const e=n.getContainerById(t),i=me(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Fh(n,s));return Ns(i)}const Nh=S("editor-selection");class MT{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(D6(e,i)){Nh.debug("adjust selection because remote deleted current block");const s=S6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new WI(t);const r=st(o,0,"normal");this._range=ze(t,{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 t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=st(t,e,"normal");let i;o&&(i=st(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=ze(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!XI(this.editor,r))&&rt(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),qI(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!Wr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Lo(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){KI(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Nh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Nh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.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;e&&xt(e,"focused")&&(rt(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Ph(this.editor);return t==="text"?_a(this.editor,e):t==="markdown"?Fa(this.editor,e):M6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{rt(t,"focused"),rt(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=ot(t);for(;Mo(e);){const o=et(e);g(Nh,o,"parent block not found"),W(o,"child-focused"),e=ot(o)}return!0}}function RT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function OT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!nt(n,e))return;let o=Ug(n,"select"),r=zg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class _T{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=R4(this.editor,t.x,t.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=so(s[0].block);this.autoScroll=new eh({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.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(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=hh(this.editor,t.x,t.y);if(!e)return;const o=_h(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){OT(this.editor)}handleTripleClick(t){RT(this.editor)}}function FT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function PT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const NA=S("delete-text");function $A(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ue||g(NA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(NA,nt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=_i(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function HA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const NT=S("handle-backspace");function Kg(n,t){if(!ue(n,t))return;const e=ot(t);To(e)!==1&&n.deleteBlock(t)}function $T(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===0){if(HA(n,o))return;const r=ae(o);if(r){if(!n.isBlockWritable(r))return;if(nt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Kg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Kg(n,o),g(NT,Ie(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ot(o);if(Mo(i)){const s=I4(n,i);if(s){if(!n.isBlockWritable(s))return;Kg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else $A(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function HT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(nt(n,o))if(e.offset===ut(n,o)){const r=Qt(o);if(r){if(!n.isBlockWritable(r))return;nt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ue(n,o)?n.deleteBlock(o,ke(n,r,0)):n.deleteBlock(r)}}else $A(n,"forward",1,null);else{const r=bt(o),i=ot(o);n.insertTextBlock("",ct(i),r),n.deleteBlock(o)}}function jT(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Mt(n,r))return!1;if(Wr(e))return!0;const s=Ms(n,r,e,o),l=gn(n,r);return s.length===l.length}function UT(n,t){if(jT(n)){const s=n.getFocusedBlock(),l=bt(s),a=ct(ot(s));n.insertTextBlock("",a,l+1);return}const e=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&Ie(e);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),nt(n,e)){if(ue(n,e)&&HA(n,e))return;const s=n.selection.range.start,l=n.breakTextBlock(e,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 zT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!nt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const VT=S("input-handler-actions");function WT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(UT(n),!0))}function qT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function GT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>($T(n),!0))}function ZT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function QT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{VT.error(t)}),!0)}const $h={ArrowDown:sA,ArrowUp:iA,ArrowLeft:oA,ArrowRight:rA,"Shift+ArrowDown":lA,"Shift+ArrowUp":uA,"Shift+ArrowLeft":cA,"Shift+ArrowRight":aA,"CtrlOrCmd+ArrowLeft":hA,"CtrlOrCmd+ArrowRight":fA,"CtrlOrCmd+Shift+ArrowLeft":mA,"CtrlOrCmd+Shift+ArrowRight":gA,"CtrlOrCmd+ArrowUp":pA,"CtrlOrCmd+ArrowDown":qg,"CtrlOrCmd+Shift+ArrowUp":CA,"CtrlOrCmd+Shift+ArrowDown":Gg,"CtrlOrCmd+A":_A,Home:wA,End:BA,"Shift+Home":yA,"Shift+End":kA,PageUp:DA,PageDown:SA,"Shift+PageUp":LA,"Shift+PageDown":MA,"CtrlOrCmd+Z":FT,"CtrlOrCmd+Shift+Z":PT,Enter:WT,Delete:qT,Backspace:GT,"Shift+Enter":ZT,"CtrlOrCmd+Shift+V":QT};function jA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function UA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){let l="";s.split("|").forEach(d=>{const h=e.get(d);l+=l?`|${h}`:`${h}`}),i.src=l}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{UA(n,l,e)})})}function zA(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):UA(t,r,e)})}async function YT(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function JT(n,t){var i,s;const o=t.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 KT(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(JT(n,t)){const s=Array.from(Object.keys(o));r=await YT(n,s),zA(n,t,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&&zA(n,t,i)}async function XT(n,t,e){await KT(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Ie(i)){const s=ot(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,t,e)}})}const tD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function eD(n){let t;for(const e of tD)if(t=n[e],t)break;return t||null}function VA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{VA(n,l,e)})})}function nD(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):VA(t,r,e)}),Array.from(e)}function Hh(n,t){return Ze.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Mi(JSON.stringify(t))}" 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(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function jh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=nD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function oD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Ph(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),jh(n,o);const i=Th(n,o),s=Fa(n,o),l=Hh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Uh(n,t){const e=Jg(n,t);jh(n,e);const o=Th(n,e),r=Fa(n,e),i=Hh(o,e);return Mm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class rD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ql(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ql(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(t){oD(this.editor,t,(e,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(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Ie(o)&&this.editor.deleteBlock(o)}else Og(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){rt(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){Dg(this.editor,i)}defaultHandleKeydown(t,e){return jA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await XT(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=eD(t);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,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function iD(n,t,e){const o=$r(t,e);return o.remove(),o}S("copy-dom-attributes");const WA=["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 sD(n,t){for(let l=0;l<WA.length;l++){const a=WA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[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];e.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function qA(n){const t=Array.from(n.childNodes).filter(e=>!z5(e));return t.forEach(e=>{e.remove()}),t}function GA(n,t,e){var d;const o=n.getContainerById(t),r=$r(o,e),i=Ri(r),s=n.doc.getBlockData(t,e),l=Yt(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=qA(h);qA(r),p.forEach(v=>{r.appendChild(v)});const C=ih(h);if(C){const v=ih(r);v&&v.remove(),r.appendChild(C)}sD(h,r)}l4(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 lD=S("transform-selection");function ZA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(lD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return ze(n,{anchor:l,focus:a})}const cD=S("handle-block-text-changed");function aD(n,t,e,o,r){const i=n.getContainerById(t),s=$r(i,e),l=n.doc.getBlockData(t,e);if(g(cD,l.text,"no block text"),e4(n,s).setBlockText(n,s,l.text),!r){const a=ZA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function uD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function QA(n,t,e,o){const r=Yt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function dD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{QA(n,i,o,{child:!0})}),QA(n,r,o,{child:!1})}const Fo=S("editor-doc");class hD extends fa{constructor(e,o,r){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(Fo,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(Fo,l,`no text, ${e}, ${o}`);const a=ZA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(Fo,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,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(Fo,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(uD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Oi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(Fo,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(Fo,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(Oi(this.editor,r)),s}localDeleteChildContainers(e){return g(Fo,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){g(Fo,!this.editor.readonly,"editor is readonly");const o=mt.default(e);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(e){Fo.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),aD(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),GA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);KE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){dD(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);iD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Fo.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function YA(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Xg=S("undo-action");class Jl{constructor(t,e,o){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return g(Xg,t,"no other action"),!1}combine(t){g(Xg,!1,"no other")}setAfterRange(t){this.afterRange&&Xg.warn("after range has already set"),this.afterRange=t}}const fD=S("block-action");class JA extends Jl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(fD,this.blockIndex===bt(i),"invalid block index"),Lh(e,i,Oi(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}const mD=S("insert-block-action");class gD extends JA{undo(t){return t.findBlockById(this.blockData.id)?this.deleteBlock(t,this.beforeRange):(mD.warn(`block (${this.blockData.blockId}) not found, deleted by others?`),!1)}redo(t){return this.insertBlock(t,this.afterRange)}}class pD extends JA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class CD extends Jl{constructor(e){super(e,ct(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){YA(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Jl&&(o.afterRange||o.setAfterRange(e))}}const Hi=S("update-block-data-action");class zh extends Jl{constructor(e,o,r,i,s,l){super(e,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=mt.default(i),this.afterBlockData=mt.default(s),g(Hi,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Oh(e,o,zh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Hi.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g(Hi,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hi,r,"no container"),Oh(e,o,zh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const tp=S("update-block-text-action");class za extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=za.calType(i,s)}static calType(e,o){g(tp,e,"no old data"),g(tp,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>A5(h)?`cjk_${h}`:p5(h)?"number":Yd(h)?"space":C5(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(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Rh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Rh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof za)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.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(e){g(tp,e instanceof za,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class KA extends Jl{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0}}class AD extends KA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class bD extends KA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Po=S("undo");class vD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,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(t){this.currentGroup?this.currentGroup.addAction(t):(YA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Po,!this.currentGroup,"current group already exists"),this.currentGroup=new CD(this.editor),this.groupCounter=1):(g(Po,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Po,this.currentGroup,"current group not exists"),g(Po,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Po.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(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Po.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Oi(this.editor,t.beforeRange))}catch(e){Po.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!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 t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Oi(this.editor,e)):Po.warn("no after range")}catch(e){Po.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!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 e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new za(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new zh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Po,e>=0,"invalid block index"),g(Po,o,"no block data"),this.addAction(new gD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new pD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new AD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,t,e)))}}class yD{async fromData(t,e){const o=e.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(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class wD{constructor(t){m(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);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(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,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(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Ce extends ve.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=et(o);if((!r||!te(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?it(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&te(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&rt(s,"hover"),e&&W(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Ce(e))}getParentTextContentChild(e,o){if(!nt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:$m(o)}}const XA="style-color-",tb="style-bg-color-";class BD{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(XA)?i["data-style-color"]=l.substring(XA.length):l.startsWith(tb)?i["data-style-bg-color"]=l.substring(tb.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(t,e,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=t.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"),Ce.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,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=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ce.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function ED(n){n.editorBlocks.registerBlockClass(Dn),n.editorBlocks.registerBlockClass(x4),n.editorBoxes.registerBoxClass(g6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(b6),n.editorBoxes.registerBoxClass(v6),n.editorInsertions.registerInsertionClass(y6),n.editorBlockRenders.registerRender(new BD)}function xD(n,t){ED(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const eb=S("range-commands");function nb(n,t){n.forEach(e=>{e.source=t,e.children&&nb(e.children,t)})}function ob(n,t,e){const o=it(t);g(eb,o===e.start.blockId,"invalid start range"),g(eb,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);nb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(l=>{me(l).forEach(d=>{const h=ut(n,d),p=ze(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),C=ob(n,d,p);i.push(...C)})}),i}function rb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=ze(t,{anchor:r.start,focus:r.end});ob(t,r.block,i).forEach(l=>{o.push(l)})}),o}function ib(n,t,e,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,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Mt(n,t)&&Ms(n,t,e.start,e.end).forEach(C=>{me(C).forEach(B=>{const D=ut(n,B),x=ze(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});ib(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function sb(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||(n.getSelectedBlocks().forEach(l=>{const a=ze(o,{anchor:l.start,focus:l.end});ib(o,l.block,a,t,e,r)}),o.focus()),r}const ID=S("command-providers");class lb{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return g(ID,e,`no command provider, id=${t}`),e}getCommands(t){return rb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>sb(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function TD(n,t){const e=ot(t),o=ct(e),r=bt(t);GA(n,o,r)}const DD=S("table-scroll");class cb{constructor(t,e,o,r,i){m(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class SD{constructor(t){m(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){DD.warn(`event has already registered: ${e}`);return}i.push(new cb(this.editor,t,e,o,r))}else{const s=new cb(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(e)e===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(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const ab=S("update-block-text");function LD(n,t){const e=n.getBoxById(t.id),o=et(e);g(ab,o,"no parent block"),g(ab,nt(n,o),"not a text block");const r=n.getBlockText(o),i=s6(r,"id",t.id,t);z6(n,o,i)}function MD(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function RD(n){if(n.readonly)return!1;const t=Oo(n);return!!n.isBlockWritable(t.map(e=>e.block))}class OD{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class _D{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(rr(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Yr=S("editor");class FD extends ve.TypedEmitter{constructor(e,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 k4(this));m(this,"editorBoxes",new A6(this));m(this,"editorInsertions",new w6(this));m(this,"editorEmbeds",new B4(this));m(this,"editorDecorators",new B6(this));m(this,"editorCommandProviders",new lb(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 rD(this));m(this,"settingsProvider");m(this,"_readonly",!1);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 hD(this,o,this.undoManager),this.parent=e,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=b4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new VI(this,this.inputHandlers),this.selection=new MT(this),this.selectionHandler=new _T(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ze.isMobile&&W(this.rootElement,"mobile"),Ze.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):rt(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:so(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return g(Yr,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,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(e=>e.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(e,o){_g(this,e,o)}isWritable(){return RD(this)}isBlockWritable(e){return MD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return(!o||!Array.isArray(o))&&(g(Yr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Yr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(e,o,r){return v4(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Yr,Bs(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Yr,Nm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Yr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Yr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return $r(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return Vr(this,e)}getParentContainer(e){return ot(e)}reloadBlock(e){TD(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Zl(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Mg(this,e,o)}mergeTextBlock(e,o){return H6(this,e,o)}breakTextBlock(e,o,r){return Ql(this,e,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(e,o){const r=this.getBlockText(e);return ie(r,o)}getBlockData(e){return Pi(this,e)}getBoxData(e){return f6(this,e)}getBlockText(e){return pn(this,e)}setBlockText(e,o){z6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Sg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return R6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return O6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){q6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Ng(this,e,o,r,i)}deleteChildContainers(e){$6(this,e)}replaceBlockText(e,o){return Rh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Oh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return V6(this,e,o,r)}updateBoxData(e){LD(this,e)}getSelectedText(){const e=Ph(this);return _a(this,e)}clearSelectedContents(){Og(this)}insertTextBlock(e,o,r,i){const s=ar(e!=null?e:"");return N6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){F6(this);return}o?(this.compositingText="",Ca()||Dg(this,e)):(this.compositingText=e,_6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Va(n,t,e){return new FD(n,t,e)}function PD(n){const t=(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=pm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const ND=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Vh extends ve.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:ND}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&ua.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.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(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const o=this.cursors.get(e);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(e),this.emit("remote-carets-change",[...r])}}updateUsers(e){this.users.forEach(o=>{e.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&kh(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(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(kh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xe=S("local-doc");class ep extends fa{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[ar("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainers(e){e.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xe,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(e){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,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(e,o){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Vh}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class $D{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function np(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new $D(o)})}const ub=S("find-block");function db(n,t){const e=Is(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),db(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function hb(n,t){const e=Ts(t);if(!e){if(lo(t))return null;const o=Es(t);return g(ub,o,"no parent block"),hb(n,o)}return Mt(n,e)?Xm(n,e,{visibleOnly:!0}):e}const HD=S("remote-cursor");class jD{constructor(){m(this,"remoteUsers",new Vh)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):HD.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function UD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function zD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function Wa(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=UD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function ji(n){return n==="root"?"blocks":n}function Kl(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,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new on.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var dr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ui={},op=Q3.default.EventEmitter;Ui.EventEmitter=op,Ui.mixin=WD;function WD(n){for(var t in op.prototype)n.prototype[t]=op.prototype[t]}var fb=["info","warn","error"];function mb(){var n={};fb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var qD=mb;mb.prototype.setMethods=function(n){n=n||{};var t=this;fb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var GD=qD,ZD=new GD,gb=ZD;function $s(n,t){this.code=n,this.message=t||"",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 Wh=$s,qa={},pb=QD;function QD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(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?t([],s[0],l[0],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var Cb={exports:{}},zi=Cb.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||""}},rp=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},ip=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")},qh=function(n){for(var t=0;t<n.length;t++)ip(n[t])};zi.apply=function(n,t){var e;qh(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=rp(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Jr=zi._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:rp(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:rp(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};zi.compose=function(n,t){qh(n),qh(t);for(var e=n.slice(),o=0;o<t.length;o++)Jr(e,t[o]);return e},zi.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),Jr(t,o)}return t};var sp=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};zi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=sp(n,t[r],o);return n};var YD=zi._tc=function(n,t,e,o){if(ip(t),ip(e),t.i!=null)Jr(n,{i:t.i,p:sp(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Jr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Jr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Jr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Jr(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=sp(i.p,e),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 t=0;t<n.length;t++)n[t]=JD(n[t]);return n},pb(zi,YD,qh,Jr);var Gh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},KD=function(n){return!!n&&n.constructor===Object},No=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Kr={};It.registerSubtype=function(n){Kr[n.name]=n},It.create=function(n){return n===void 0?null:No(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Kr[n.t]&&(t.t=n.t,t.o=Kr[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Gh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Gh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!KD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ga(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function Za(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}It.apply=function(n,t){It.checkValidOp(t),t=No(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&Ga(r);for(var i=null,s=e,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)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.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)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var XD=It.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};It.append=function(n,t){if(t=No(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ga(t),Ga(e)),XD(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Kr[t.t]){if(e.o=Kr[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),Za(t),n.push(t);Za(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Za(t),Za(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=No(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Gh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=No(t);var r=It.commonLengthForOps(e,t),i=It.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var a=No(e);a.p=a.p.slice(s),t.ld=It.apply(No(t.ld),[a])}else if(t.od!==void 0){var a=No(e);a.p=a.p.slice(s),t.od=It.apply(No(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ga(t),a=No(e),Ga(a)),a.t&&Kr[a.t]){if(t.t&&t.t===a.t){var h=Kr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,C=0;C<h.length;C++)t.o=[h[C]],t.p=p.slice(),Za(t),It.append(n,t);else(!Gh(h)||h.length>0)&&(t.o=h,It.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=No(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var v=t.p[r],B=t.lm,D=e.p[r],x=e.lm;if(D!==x)if(v===D)if(o==="left")t.p[r]=x,v===B&&(t.lm=x);else return n;else v>D&&t.p[r]--,v>x?t.p[r]++:v===x&&D>x&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>x?t.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&d){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},pb(It,It.transformComponent,It.checkValidOp,It.append);var tS=Cb.exports;It.registerSubtype(tS);var eS=It,nS={type:eS};(function(n){n.defaultType=nS.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(qa);var $o={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}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(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){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(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})($o);var Ab=Array.isArray,bb=Object.keys,oS=Object.prototype.hasOwnProperty,rS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Ab(t),r=Ab(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var C=bb(t);if(s=C.length,s!==bb(e).length)return!1;for(i=s;i--!==0;)if(!oS.call(e,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},vb=Ui,iS=gb,qn=Wh,Zh=qa,Ho=$o,sS=Ho.clone,lS=rS,Sn=qn.CODES,cS=Ft;function Ft(n,t,e){vb.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,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}vb.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=Zh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Sn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new qn(Sn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new qn(Sn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?Zh.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;Ho.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Sn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){Ho.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){Ho.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Sn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Qh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Qh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Ft.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))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);aS(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=uS([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.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;Ho.nextTick(function(){n._handleSubscribe()})}}};function aS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function uS(n){return n=n.filter(Ho.truthy),n.length?function(t){Ho.callEach(n,t)}:null}Ft.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 Qh(n,t){if(n.del)return dS(t);if(t.del)return new qn(Sn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Sn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}Ft.prototype._otApply=function(n,t){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,t),!t&&this.type===Zh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Qh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);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",t);return}if(n.del){var a=this.data;this._setType(null),this.emit("del",a,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new qn(Sn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=Ho.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"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!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 e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;Ho.nextTick(function(){r.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!lS(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},Ft.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=Zh.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:t,data:n}},s=e&&e.source;this._submit(i,s,o)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Sn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:sS(this.data),type:this.type.uri}},Ft.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()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=Qh(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=Ho.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Ho.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)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 yb=Ui,kb=Hs.ACTIONS,hS=$o,fS=Ln;function Ln(n,t,e,o,r,i,s){yb.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,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}yb.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 t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Ln.prototype.destroy=function(n){this.connection.canSend&&this.action===kb.querySubscribe&&this.connection.send({a:kb.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,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ln.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ln.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)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(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Ln.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Ln.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},Ln.prototype._handleError=function(n){this.emit("error",n)},Ln.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Ln.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var wb=Ui,mS=Hs.ACTIONS,gS=$o,Bb=hr;function hr(n,t){if(wb.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}wb.mixin(hr),hr.prototype.submit=function(n,t){this.value=n,this.send(t)},hr.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},hr.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},hr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},hr.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},hr.prototype._message=function(){return{a:mS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},hr.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},hr.prototype._callbackOrEmit=function(n,t){if(t)return gS.nextTick(t,n);n&&this.emit("error",n)};var pS=$o,Eb=lp;function lp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}lp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},lp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&pS.nextTick(n)};var cp={exports:{}};(function(n,t){(function(e,o){o(t)})(dr,function(e){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,lt){R(J).apply(G,U.concat(lt))},j)});return M.length?F.apply(this,M):F}}var z=typeof dr=="object"&&dr&&dr.Object===Object&&dr,Z=typeof self=="object"&&self&&self.Object===Object&&self,tt=z||Z||Function("return this")(),ft=tt.Symbol,vt=Object.prototype,zt=vt.hasOwnProperty,Ht=vt.toString,Kt=ft?ft.toStringTag:void 0;function qe(w){var T=zt.call(w,Kt),M=w[Kt];try{w[Kt]=void 0;var F=!0}catch{}var U=Ht.call(w);return F&&(T?w[Kt]=M:delete w[Kt]),U}var Yn=Object.prototype,He=Yn.toString;function Rn(w){return He.call(w)}var xr="[object Null]",kn="[object Undefined]",an=ft?ft.toStringTag:void 0;function Ir(w){return w==null?w===void 0?kn:xr:an&&an in Object(w)?qe(w):Rn(w)}var ii="[object AsyncFunction]",Ao="[object Function]",eC="[object GeneratorFunction]",nC="[object Proxy]";function oC(w){if(!s(w))return!1;var T=Ir(w);return T==Ao||T==eC||T==ii||T==nC}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)&&!oC(w)}var si={};function Nt(){}function Tr(w){return function(){if(w!==null){var T=w;w=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Pc=function(w){return os&&w[os]&&w[os]()};function a1(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 u1(w){return un(w)&&Ir(w)==rl}var bo=Object.prototype,d1=bo.hasOwnProperty,rC=bo.propertyIsEnumerable,il=u1(function(){return arguments}())?u1:function(w){return un(w)&&d1.call(w,"callee")&&!rC.call(w,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,h1=ll&&!0&&n&&!n.nodeType&&n,cl=h1&&h1.exports===ll,f1=cl?tt.Buffer:void 0,al=f1?f1.isBuffer:void 0,rs=al||sl,Gu=9007199254740991,Zu=/^(?:0|[1-9]\d*)$/;function Qu(w,T){var M=typeof w;return T=T==null?Gu:T,!!T&&(M=="number"||M!="symbol"&&Zu.test(w))&&w>-1&&w%1==0&&w<T}var Yu="[object Arguments]",Ju="[object Array]",Ku="[object Boolean]",Xu="[object Date]",td="[object Error]",ed="[object Function]",iC="[object Map]",sC="[object Number]",lC="[object Object]",m1="[object RegExp]",g1="[object Set]",cC="[object String]",aC="[object WeakMap]",uC="[object ArrayBuffer]",dC="[object DataView]",p1="[object Float32Array]",hC="[object Float64Array]",fC="[object Int8Array]",mC="[object Int16Array]",nd="[object Int32Array]",gC="[object Uint8Array]",od="[object Uint8ClampedArray]",pC="[object Uint16Array]",CC="[object Uint32Array]",le={};le[p1]=le[hC]=le[fC]=le[mC]=le[nd]=le[gC]=le[od]=le[pC]=le[CC]=!0,le[Yu]=le[Ju]=le[uC]=le[Ku]=le[dC]=le[Xu]=le[td]=le[ed]=le[iC]=le[sC]=le[lC]=le[m1]=le[g1]=le[cC]=le[aC]=!1;function AC(w){return un(w)&&nl(w.length)&&!!le[Ir(w)]}function bC(w){return function(T){return w(T)}}var C1=typeof e=="object"&&e&&!e.nodeType&&e,ul=C1&&!0&&n&&!n.nodeType&&n,vC=ul&&ul.exports===C1,Nc=vC&&z.process,A1=function(){try{var w=ul&&ul.require&&ul.require("util").types;return w||Nc&&Nc.binding&&Nc.binding("util")}catch{}}(),b1=A1&&A1.isTypedArray,yC=b1?bC(b1):AC,kC=Object.prototype,wC=kC.hasOwnProperty;function BC(w,T){var M=Ae(w),F=!M&&il(w),U=!M&&!F&&rs(w),j=!M&&!F&&!U&&yC(w),G=M||F||U||j,J=G?a1(w.length,String):[],lt=J.length;for(var pt in w)(T||wC.call(w,pt))&&!(G&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Qu(pt,lt)))&&J.push(pt);return J}var $c=Object.prototype;function EC(w){var T=w&&w.constructor,M=typeof T=="function"&&T.prototype||$c;return w===M}function Hc(w,T){return function(M){return w(T(M))}}var xC=Hc(Object.keys,Object),IC=Object.prototype,TC=IC.hasOwnProperty;function v1(w){if(!EC(w))return xC(w);var T=[];for(var M in Object(w))TC.call(w,M)&&M!="constructor"&&T.push(M);return T}function jc(w){return ol(w)?BC(w):v1(w)}function y1(w){var T=-1,M=w.length;return function(){return++T<M?{value:w[T],key:T}:null}}function DC(w){var T=-1;return function(){var F=w.next();return F.done?null:(T++,{value:F.value,key:T})}}function SC(w){var T=jc(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 LC(w){if(ol(w))return y1(w);var T=Pc(w);return T?DC(T):SC(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=Tr(F||Nt),w<=0||!T)return F(null);var U=LC(T),j=!1,G=0,J=!1;function lt(at,At){if(G-=1,at)j=!0,F(at);else{if(At===si||j&&G<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;G<w&&!j;){var at=U();if(at===null){j=!0,G<=0&&F(null);return}G+=1,M(at.value,at.key,vo(lt))}J=!1}pt()}}function Dr(w,T,M,F){dl(T)(w,R(M),F)}function je(w,T){return function(M,F,U){return w(M,T,F,U)}}function rd(w,T,M){M=Tr(M||Nt);var F=0,U=0,j=w.length;j===0&&M(null);function G(J,lt){J?M(J):(++U===j||lt===si)&&M(null)}for(;F<j;F++)T(w[F],F,vo(G))}var MC=je(Dr,1/0),Zo=function(w,T,M){var F=ol(w)?rd:MC;F(w,R(T),M)};function Qo(w){return function(T,M,F){return w(Zo,T,R(M),F)}}function id(w,T,M,F){F=F||Nt,T=T||[];var U=[],j=0,G=R(M);w(T,function(J,lt,pt){var at=j++;G(J,function(At,Zt){U[at]=Zt,pt(At)})},function(J){F(J,U)})}var Uc=Qo(id),sd=H(Uc);function li(w){return function(T,M,F,U){return w(dl(M),T,R(F),U)}}var Sr=li(id),ld=je(Sr,1),cd=H(ld);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 ad(w){return function(T,M,F){for(var U=-1,j=Object(T),G=F(T),J=G.length;J--;){var lt=G[w?J:++U];if(M(j[lt],lt,j)===!1)break}return T}}var ss=ad();function ls(w,T){return w&&ss(w,T,jc)}function k1(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 RC(w){return w!==w}function w1(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?w1(w,T,M):k1(w,RC,M)}var zc=function(w,T,M){typeof T=="function"&&(M=T,T=null),M=Tr(M||Nt);var F=jc(w),U=F.length;if(!U)return M(null);T||(T=U);var j={},G=0,J=!1,lt=Object.create(null),pt=[],at=[],At={};ls(w,function(he,re){if(!Ae(he)){Zt(re,[he]),at.push(re);return}var pe=he.slice(0,he.length-1),ko=pe.length;if(ko===0){Zt(re,he),at.push(re);return}At[re]=ko,is(pe,function(E){if(!w[E])throw new Error("async.auto task `"+re+"` has a non-existent dependency `"+E+"` in "+pe.join(", "));en(E,function(){ko--,ko===0&&Zt(re,he)})})}),e3(),De();function Zt(he,re){pt.push(function(){yo(he,re)})}function De(){if(pt.length===0&&G===0)return M(null,j);for(;pt.length&&G<T;){var he=pt.shift();he()}}function en(he,re){var pe=lt[he];pe||(pe=lt[he]=[]),pe.push(re)}function Fn(he){var re=lt[he]||[];is(re,function(pe){pe()}),De()}function yo(he,re){if(!J){var pe=vo(function(E,Rr){if(G--,arguments.length>2&&(Rr=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pt){ds[Pt]=Pn}),ds[he]=Rr,J=!0,lt=Object.create(null),M(E,ds)}else j[he]=Rr,Fn(he)});G++;var ko=R(re[re.length-1]);re.length>1?ko(j,pe):ko(pe)}}function e3(){for(var he,re=0;at.length;)he=at.pop(),re++,is(n3(he),function(pe){--At[pe]===0&&at.push(pe)});if(re!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function n3(he){var re=[];return ls(w,function(pe,ko){Ae(pe)&&hl(pe,he,0)>=0&&re.push(ko)}),re}};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 OC="[object Symbol]";function _C(w){return typeof w=="symbol"||un(w)&&Ir(w)==OC}var FC=1/0,ud=ft?ft.prototype:void 0,B1=ud?ud.toString:void 0;function dd(w){if(typeof w=="string")return w;if(Ae(w))return ci(w,dd)+"";if(_C(w))return B1?B1.call(w):"";var T=w+"";return T=="0"&&1/w==-FC?"-0":T}function PC(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 NC(w,T,M){var F=w.length;return M=M===void 0?F:M,!T&&M>=F?w:PC(w,T,M)}function hd(w,T){for(var M=w.length;M--&&hl(T,w[M],0)>-1;);return M}function $C(w,T){for(var M=-1,F=w.length;++M<F&&hl(T,w[M],0)>-1;);return M}function HC(w){return w.split("")}var jC="\\ud800-\\udfff",UC="\\u0300-\\u036f",zC="\\ufe20-\\ufe2f",ce="\\u20d0-\\u20ff",oe=UC+zC+ce,VC="\\ufe0e\\ufe0f",WC="\\u200d",qC=RegExp("["+WC+jC+oe+VC+"]");function GC(w){return qC.test(w)}var E1="\\ud800-\\udfff",ZC="\\u0300-\\u036f",x1="\\ufe20-\\ufe2f",QC="\\u20d0-\\u20ff",Ge=ZC+x1+QC,fd="\\ufe0e\\ufe0f",ai="["+E1+"]",Vc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+Vc+"|"+fl+")",md="[^"+E1+"]",gd="(?:\\ud83c[\\udde6-\\uddff]){2}",pd="[\\ud800-\\udbff][\\udc00-\\udfff]",I1="\\u200d",Cd=On+"?",Ad="["+fd+"]?",wn="(?:"+I1+"(?:"+[md,gd,pd].join("|")+")"+Ad+Cd+")*",YC=Ad+Cd+wn,_n="(?:"+[md+Vc+"?",Vc,gd,pd,ai].join("|")+")",JC=RegExp(fl+"(?="+fl+")|"+_n+YC,"g");function T1(w){return w.match(JC)||[]}function Yo(w){return GC(w)?T1(w):HC(w)}function Wc(w){return w==null?"":dd(w)}var bd=/^\s+|\s+$/g;function de(w,T,M){if(w=Wc(w),w&&(M||T===void 0))return w.replace(bd,"");if(!w||!(T=dd(T)))return w;var F=Yo(w),U=Yo(T),j=$C(F,U),G=hd(F,U)+1;return NC(F,j,G).join("")}var Lr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,vd=/,/,KC=/(=.+)?(\s*)$/,yd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function XC(w){return w=w.toString().replace(yd,""),w=w.match(Lr)[2].replace(" ",""),w=w?w.split(vd):[],w=w.map(function(T){return de(T.replace(KC,""))}),w}function D1(w,T){var M={};ls(w,function(F,U){var j,G=_(F),J=!G&&F.length===1||G&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],M[U]=j.concat(j.length>0?lt:F);else if(J)M[U]=F;else{if(j=XC(F),F.length===0&&!G&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");G||j.pop(),M[U]=j.concat(lt)}function lt(pt,at){var At=ci(j,function(Zt){return pt[Zt]});At.push(at),R(F).apply(null,At)}}),zc(M,T)}function Jn(){this.head=this.tail=null,this.length=0}function kd(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):kd(this,w)},Jn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):kd(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(At,Zt,De){if(De!=null&&typeof De!="function")throw new Error("task callback must be a function");if(at.started=!0,Ae(At)||(At=[At]),At.length===0&&at.idle())return C(function(){at.drain()});for(var en=0,Fn=At.length;en<Fn;en++){var yo={data:At[en],callback:De||Nt};Zt?at._tasks.unshift(yo):at._tasks.push(yo)}G||(G=!0,C(function(){G=!1,at.process()}))}function lt(At){return function(Zt){U-=1;for(var De=0,en=At.length;De<en;De++){var Fn=At[De],yo=hl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Zt!=null&&at.error(Zt,Fn.data)}U<=at.concurrency-at.buffer&&at.unsaturated(),at.idle()&&at.drain(),at.process()}}var pt=!1,at={_tasks:new Jn,concurrency:T,payload:M,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Zt){J(At,!1,Zt)},kill:function(){at.drain=Nt,at._tasks.empty()},unshift:function(At,Zt){J(At,!0,Zt)},remove:function(At){at._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!at.paused&&U<at.concurrency&&at._tasks.length;){var At=[],Zt=[],De=at._tasks.length;at.payload&&(De=Math.min(De,at.payload));for(var en=0;en<De;en++){var Fn=at._tasks.shift();At.push(Fn),j.push(Fn),Zt.push(Fn.data)}U+=1,at._tasks.length===0&&at.empty(),U===at.concurrency&&at.saturated();var yo=vo(lt(At));F(Zt,yo)}pt=!1}},length:function(){return at._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return at._tasks.length+U===0},pause:function(){at.paused=!0},resume:function(){at.paused!==!1&&(at.paused=!1,C(at.process))}};return at}function ui(w,T){return ml(w,1,T)}var cs=je(Dr,1);function Jo(w,T,M,F){F=Tr(F||Nt);var U=R(M);cs(w,function(j,G,J){U(T,j,function(lt,pt){T=pt,J(lt)})},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=Nt,Jo(w,T,function(U,j,G){j.apply(M,U.concat(function(J){var lt=o(arguments,1);G(J,lt)}))},function(U,j){F.apply(M,[U].concat(j))})}}var Gc=function(){return qc.apply(null,o(arguments).reverse())},wd=Array.prototype.concat,gl=function(w,T,M,F){F=F||Nt;var U=R(M);Sr(w,T,function(j,G){U(j,function(J){return J?G(J):G(null,o(arguments,1))})},function(j,G){for(var J=[],lt=0;lt<G.length;lt++)G[lt]&&(J=wd.apply(J,G[lt]));return F(j,J)})},S1=je(gl,1/0),Zc=je(gl,1),Qc=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||Nt;var G=!1,J;M(F,function(lt,pt,at){U(lt,function(At,Zt){At?at(At):w(Zt)&&!J?(G=!0,J=T(!0,lt),at(null,si)):at()})},function(lt){lt?j(lt):j(null,G?J:T(!1))})}}function dn(w,T){return T}var as=Qo(di(pl,dn)),Ko=li(di(pl,dn)),Cl=je(Ko,1);function Bd(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 L1=Bd("dir");function M1(w,T,M){M=vo(M||Nt);var F=R(w),U=R(T);function j(J){if(J)return M(J);var lt=o(arguments,1);lt.push(G),U.apply(this,lt)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}G(null,!0)}function Ed(w,T,M){M=vo(M||Nt);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 R1(w,T,M){Ed(w,function(){return!T.apply(this,arguments)},M)}function O1(w,T,M){M=vo(M||Nt);var F=R(T),U=R(w);function j(J){if(J)return M(J);U(G)}function G(J,lt){if(J)return M(J);if(!lt)return M(null);F(j)}U(G)}function hi(w){return function(T,M,F){return w(T,F)}}function Yc(w,T,M){Zo(w,hi(R(T)),M)}function Al(w,T,M,F){dl(T)(w,hi(R(M)),F)}var fi=je(Al,1);function Jc(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=Qo(di(Kn,Kn)),bl=li(di(Kn,Kn)),Kc=je(bl,1);function _1(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(lt,pt){U[G]=!!pt,J(lt)})},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(lt,pt){lt?J(lt):(pt&&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}),_1("value")))})}function Xc(w,T,M,F){var U=ol(T)?us:Xn;U(w,T,R(M),F||Nt)}var ta=Qo(Xc),vl=li(Xc),ea=je(vl,1);function F1(w,T){var M=vo(T||Nt),F=R(Jc(w));function U(j){if(j)return M(j);F(U)}U()}var na=function(w,T,M,F){F=F||Nt;var U=R(M);Sr(w,T,function(j,G){U(j,function(J,lt){return J?G(J):G(null,{key:lt,val:j})})},function(j,G){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<G.length;pt++)if(G[pt]){var at=G[pt].key,At=G[pt].val;lt.call(J,at)?J[at].push(At):J[at]=[At]}return F(j,J)})},gi=je(na,1/0),N=je(na,1),q=Bd("log");function V(w,T,M,F){F=Tr(F||Nt);var U={},j=R(M);Dr(w,T,function(G,J,lt){j(G,J,function(pt,at){if(pt)return lt(pt);U[J]=at,lt()})},function(G){F(G,U)})}var ht=je(V,1/0),Et=je(V,1);function Vt(w,T){return T in w}function Be(w,T){var M=Object.create(null),F=Object.create(null);T=T||pl;var U=R(w),j=i(function(J,lt){var pt=T.apply(null,J);Vt(M,pt)?C(function(){lt.apply(null,M[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var at=o(arguments);M[pt]=at;var At=F[pt];delete F[pt];for(var Zt=0,De=At.length;Zt<De;Zt++)At[Zt].apply(null,at)})))});return j.memo=M,j.unmemoized=w,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var oa=h(qt);function xd(w,T,M){M=M||Nt;var F=ol(T)?[]:{};w(T,function(U,j,G){R(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,G(J)})},function(U){M(U,F)})}function Bn(w,T){xd(Zo,w,T)}function yl(w,T,M){xd(dl(T),w,M)}var Id=function(w,T){var M=R(w);return ml(function(F,U){M(F[0],U)},T,1)},pi=function(w,T){var M=Id(w,T);return M.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(M.started=!0,Ae(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,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};G?M._tasks.insertBefore(G,pt):M._tasks.push(pt)}C(M.process)},delete M.unshift,M};function kl(w,T){if(T=Tr(T||Nt),!Ae(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();Jo(U,T,M,F)}function Wt(w){var T=R(w);return i(function(F,U){return F.push(function(G,J){if(G)U(null,{error:G});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function P1(w){var T;return Ae(w)?T=ci(w,Wt):(T={},ls(w,function(M,F){T[F]=Wt.call(this,M)})),T}function Td(w,T,M,F){Xc(w,T,function(U,j){M(U,function(G,J){j(G,!J)})},F)}var wl=Qo(Td),Dd=li(Td),N1=je(Dd,1);function $1(w){return function(){return w}}function Ai(w,T,M){var F=5,U=0,j={times:F,intervalFunc:$1(U)};function G(at,At){if(typeof At=="object")at.times=+At.times||F,at.intervalFunc=typeof At.interval=="function"?At.interval:$1(+At.interval||U),at.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")at.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof w=="function"?(M=T||Nt,T=w):(G(j,w),M=M||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=R(T),lt=1;function pt(){J(function(at){at&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(at))?setTimeout(pt,j.intervalFunc(lt)):M.apply(null,arguments)})}pt()}var Xo=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){xd(cs,w,T)}var El=Qo(di(Boolean,pl)),Mr=li(di(Boolean,pl)),xl=je(Mr,1);function Sd(w,T,M){var F=R(T);Uc(w,function(j,G){F(j,function(J,lt){if(J)return G(J);G(null,{value:j,criteria:lt})})},function(j,G){if(j)return M(j);M(null,ci(G.sort(U),_1("value")))});function U(j,G){var J=j.criteria,lt=G.criteria;return J<lt?-1:J>lt?1:0}}function Il(w,T,M){var F=R(w);return i(function(U,j){var G=!1,J;function lt(){var pt=w.name||"anonymous",at=new Error('Callback function "'+pt+'" timed out.');at.code="ETIMEDOUT",M&&(at.info=M),G=!0,j(at)}U.push(function(){G||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var H1=Math.ceil,Tl=Math.max;function bi(w,T,M,F){for(var U=-1,j=Tl(H1((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);Sr(bi(0,w,1),T,U,F)}var j1=je(vi,1/0),U1=je(vi,1);function z1(w,T,M,F){arguments.length<=3&&(F=M,M=T,T=Ae(w)?[]:{}),F=Tr(F||Nt);var U=R(M);Zo(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||Nt,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||Nt);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 V1(w,T,M){Ll(function(){return!w.apply(this,arguments)},T,M)}var Ld=function(w,T){if(T=Tr(T||Nt),!Ae(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([])},t3={apply:r,applyEach:sd,applyEachSeries:cd,asyncify:v,auto:zc,autoInject:D1,cargo:ui,compose:Gc,concat:S1,concatLimit:gl,concatSeries:Zc,constant:Qc,detect:as,detectLimit:Ko,detectSeries:Cl,dir:L1,doDuring:M1,doUntil:R1,doWhilst:Ed,during:O1,each:Yc,eachLimit:Al,eachOf:Zo,eachOfLimit:Dr,eachOfSeries:cs,eachSeries:fi,ensureAsync:Jc,every:mi,everyLimit:bl,everySeries:Kc,filter:ta,filterLimit:vl,filterSeries:ea,forever:F1,groupBy:gi,groupByLimit:na,groupBySeries:N,log:q,map:Uc,mapLimit:Sr,mapSeries:ld,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:Be,nextTick:oa,parallel:Bn,parallelLimit:yl,priorityQueue:pi,queue:Id,race:kl,reduce:Jo,reduceRight:Ci,reflect:Wt,reflectAll:P1,reject:wl,rejectLimit:Dd,rejectSeries:N1,retry:Ai,retryable:Xo,seq:qc,series:Bl,setImmediate:C,some:El,someLimit:Mr,someSeries:xl,sortBy:Sd,timeout:Il,times:j1,timesLimit:vi,timesSeries:U1,transform:z1,tryEach:Dl,unmemoize:Sl,until:V1,waterfall:Ld,whilst:Ll,all:mi,allLimit:bl,allSeries:Kc,any:El,anyLimit:Mr,anySeries:xl,find:as,findLimit:Ko,findSeries:Cl,forEach:Yc,forEachSeries:fi,forEachLimit:Al,forEachOf:Zo,forEachOfSeries:cs,forEachOfLimit:Dr,inject:Jo,foldl:Jo,foldr:Ci,select:ta,selectLimit:vl,selectSeries:ea,wrapSync:v};e.default=t3,e.apply=r,e.applyEach=sd,e.applyEachSeries=cd,e.asyncify=v,e.auto=zc,e.autoInject=D1,e.cargo=ui,e.compose=Gc,e.concat=S1,e.concatLimit=gl,e.concatSeries=Zc,e.constant=Qc,e.detect=as,e.detectLimit=Ko,e.detectSeries=Cl,e.dir=L1,e.doDuring=M1,e.doUntil=R1,e.doWhilst=Ed,e.during=O1,e.each=Yc,e.eachLimit=Al,e.eachOf=Zo,e.eachOfLimit=Dr,e.eachOfSeries=cs,e.eachSeries=fi,e.ensureAsync=Jc,e.every=mi,e.everyLimit=bl,e.everySeries=Kc,e.filter=ta,e.filterLimit=vl,e.filterSeries=ea,e.forever=F1,e.groupBy=gi,e.groupByLimit=na,e.groupBySeries=N,e.log=q,e.map=Uc,e.mapLimit=Sr,e.mapSeries=ld,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=Be,e.nextTick=oa,e.parallel=Bn,e.parallelLimit=yl,e.priorityQueue=pi,e.queue=Id,e.race=kl,e.reduce=Jo,e.reduceRight=Ci,e.reflect=Wt,e.reflectAll=P1,e.reject=wl,e.rejectLimit=Dd,e.rejectSeries=N1,e.retry=Ai,e.retryable=Xo,e.seq=qc,e.series=Bl,e.setImmediate=C,e.some=El,e.someLimit=Mr,e.someSeries=xl,e.sortBy=Sd,e.timeout=Il,e.times=j1,e.timesLimit=vi,e.timesSeries=U1,e.transform=z1,e.tryEach=Dl,e.unmemoize=Sl,e.until=V1,e.waterfall=Ld,e.whilst=Ll,e.all=mi,e.allLimit=bl,e.allSeries=Kc,e.any=El,e.anyLimit=Mr,e.anySeries=xl,e.find=as,e.findLimit=Ko,e.findSeries=Cl,e.forEach=Yc,e.forEachSeries=fi,e.forEachLimit=Al,e.forEachOf=Zo,e.forEachOfSeries=cs,e.forEachOfLimit=Dr,e.inject=Jo,e.foldl=Jo,e.foldr=Ci,e.select=ta,e.selectLimit=vl,e.selectSeries=ea,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(cp,cp.exports);var xb={exports:{}},ap=xb.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?ap(n,t):i};ap.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=ap(n,t)}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=t||16,o};var Ib=Ui,CS=Bb,AS=Eb,Yh=$o,up=cp.exports,bS=xb.exports,Tb=Hs.ACTIONS,Db=Re;function Re(n,t){if(Ib.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}Ib.mixin(Re),Re.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Re.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Re.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||bS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Re.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);up.parallel([function(i){up.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();up.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Re.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Tb.presenceSubscribe:Tb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Re.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._receiveUpdate=function(n,t){var e=Yh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Yh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Re.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Re.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Re.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Re.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Re.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Re.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Re.prototype._callbackOrEmit=function(n,t){if(t)return Yh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new CS(this,n)},Re.prototype._createRemotePresence=function(n){return new AS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=Yh.callEach(n,t);!e&&t&&this.emit("error",t)};var Qa=Bb,Sb=Wh,vS=$o,Lb=Sb.CODES,yS=jo;function jo(n,t){Qa.call(this,n,t),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()}jo.prototype=Object.create(Qa.prototype),jo.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Lb.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Qa.prototype.submit.call(this,n,t)},jo.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),Qa.prototype.destroy.call(this,n)},jo.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(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},jo.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)},jo.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},jo.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},jo.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},jo.prototype._message=function(){var n=Qa.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},jo.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!vS.supportsPresence(o))throw new Sb(Lb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Mb={};(function(n){var t=qa,e=Wh,o=$o,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(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 e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(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 e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(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 e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(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 e(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=t.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===t.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=t.defaultType.apply(h,[C]))}}}}})(Mb);var Ya=Eb,kS=Mb,wS=ho;function ho(n,t){Ya.call(this,n,t),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(Ya.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),Ya.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,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Ya.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Ya.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ho.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}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],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):kS.transformPresence(this._pending,t,e)}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,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Rb=Db,BS=yS,ES=wS;function Xl(n,t,e){var o=Xl.channel(t,e);Rb.call(this,n,o),this.collection=t,this.id=e}var xS=Xl;Xl.prototype=Object.create(Rb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new BS(this,n)},Xl.prototype._createRemotePresence=function(n){return new ES(this,n)};var IS=TS;function TS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var DS=IS,Ob=Ui,_b=Ja;function Ja(n,t,e,o,r){if(Ob.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}Ob.mixin(Ja),Ja.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ja.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ja.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new DS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Fb=_b,SS=$o,LS=Hs.ACTIONS,MS=dp;function dp(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!SS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}dp.prototype=Object.create(Fb.prototype),dp.prototype._message=function(){return{a:LS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Pb=_b,RS=$o,OS=Hs.ACTIONS,_S=hp;function hp(n,t,e,o,r,i){if(Pb.call(this,n,t,e,o,i),!RS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}hp.prototype=Object.create(Pb.prototype),hp.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=Db,Nb=xS,$S=MS,HS=_S,$b=Ui,tc=Wh,ne=Hs.ACTIONS,Hb=qa,Uo=$o,Ka=gb,Xa=tc.CODES;function jb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var jS=Bt;function Bt(n){$b.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=jb(n),this.bindToSocket(n)}$b.mixin(Bt),Bt.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 t=jb(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ka.warn("Failed to parse message",o);return}e.debug&&Ka.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){Uo.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},Bt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Ub(n.error,n),delete n.error),n.a){case ne.initLegacy:return this._handleLegacyInit(n);case ne.handshake:return this._handleHandshake(t,n);case ne.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ne.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ne.queryUnsubscribe:return;case ne.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case ne.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ne.bulkSubscribe:case ne.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ne.snapshotFetch:case ne.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ne.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ne.subscribe:case ne.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ne.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ne.presence:return this._handlePresence(t,n);case ne.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ne.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ne.presenceRequest:return this._handlePresenceRequest(t,n);case ne.pingPong:return this._handlePingPong(t);default:Ka.warn("Ignoring unrecognized message",n)}};function Ub(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Bt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](Ub(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Ka.error("Invalid bulk message",t)},Bt.prototype._reset=function(){this.agent=null},Bt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new tc(Xa.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}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,t),this.emit("state",n,t)}},Bt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Bt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},Bt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[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:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},Bt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Bt.prototype.sendFetch=function(n){return this._sendActions(ne.fetch,n,n.version)},Bt.prototype.sendSubscribe=function(n){return this._sendActions(ne.subscribe,n,n.version)},Bt.prototype.sendUnsubscribe=function(n){return this._sendActions(ne.unsubscribe,n)},Bt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ne.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},Bt.prototype.send=function(n){this.debug&&Ka.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Bt.prototype.ping=function(){if(!this.canSend)throw new tc(Xa.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ne.pingPong};this.send(n)},Bt.prototype.close=function(){this.socket.close()},Bt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Bt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new FS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},Bt.prototype._destroyDoc=function(n){!n._wantsDestroy||(Uo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Bt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Bt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new PS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},Bt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Bt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ne.queryFetch,n,t,e,o)},Bt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ne.querySubscribe,n,t,e,o)},Bt.prototype.hasPending=function(){return!!(this._firstDoc(Jh)||this._firstQuery(Jh)||this._firstSnapshotRequest())};function Jh(n){return n.hasPending()}Bt.prototype.hasWritePending=function(){return!!this._firstDoc(US)};function US(n){return n.hasWritePending()}Bt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Jh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Jh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}Uo.nextTick(n)},Bt.prototype._nothingPendingRetry=function(n){var t=this;return function(){Uo.nextTick(function(){t.whenNothingPending(n)})}},Bt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},Bt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Bt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Bt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new $S(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new HS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Bt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Bt.prototype._initializeHandshake=function(){this.send({a:ne.handshake,id:this.id})},Bt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Bt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Bt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Xa.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Hb.map[n.type]!==Hb.defaultType)return this.emit("error",new tc(Xa.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Xa.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Bt.prototype.getPresence=function(n){var t=this,e=Uo.digOrCreate(this._presences,n,function(){return new NS(t,n)});return e._wantsDestroy=!1,e},Bt.prototype.getDocPresence=function(n,t){var e=Nb.channel(n,t),o=this,r=Uo.digOrCreate(this._presences,e,function(){return new Nb(o,n,t)});return r._wantsDestroy=!1,r},Bt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},Bt.prototype._addPresence=function(n){Uo.digOrCreate(this._presences,n.channel,function(){return n})},Bt.prototype._handlePresenceSubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Bt.prototype._handlePresenceUnsubscribe=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Bt.prototype._handlePresence=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Bt.prototype._handlePresenceRequest=function(n,t){var e=Uo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var zb=jS,zS=qa;const Kh={err:1001,msg:"user auth error",name:"AuthError"},VS={err:1002,msg:"you don't have required permission",name:"PermissionError"},fp={err:1003,msg:"Too many user connected",name:"MaxUserError"},tu={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"},eu="x-live-editor-token",Xh="x-live-editor-base-url",Cn=S("auth-connection");function GS(n){try{n()}catch(t){Cn.error(t)}}class ZS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new G3.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Mi(this.getBaseURL())}async auth(t){g(Cn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[eu]:t.token,[Xh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Xh]:Mi(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new $B.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(zb.prototype),g(Cn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};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}}},zb.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 t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){Cn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else Cn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Kh.msg);t.code=Kh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(tu.msg);t.code=tu.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===Kh.err)Cn.warn("auth error"),this.handleAuthError();else if(o===fp.err)Cn.warn(fp.msg),this.emitMaxUsersError();else if(o===tu.err){Cn.warn(tu.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(e)}`),this.emitAuthError()}get(t,e){return g(Cn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(Cn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(Cn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(Cn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),GS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}S("utils/file");function QS(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}QS();async function YS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new HB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Mi(i)}const fr=S("sharedb-doc/client");class JS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(fr,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),fr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;zS.register(Ud.type),this.connection=new ZS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(fr,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,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(t){const o=`${this.apiServer()}/resources`;let r=[];t.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,{[eu]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{fr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await YS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return fr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(fr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[eu]:this.connection.token},e,o);return g(fr,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=e||{};a.url=t,a.headers||(a.headers={}),g(fr,o,"no token"),a.headers={...a.headers,[eu]:o,[Xh]:this.connection.getBase64BaseURL()};try{return await PB.default(t,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(fr,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=NB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(fr,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(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${Mi(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function KS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const mp=S("block-ids");class XS{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);g(mp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);g(mp,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class tL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new XS,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return g(mp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Vb{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const gp=S("op-parse-handler");class eL{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,o=new Map,r=new tL,i=t.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&&(gp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;e.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(e.has(a)){gp.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 Vb,o.set(d,h)),h.delete(l.key)}else g(gp,!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 Vb,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 Oe=S("op-parser");class Wb{}class pp{constructor(t){m(this,"key");this.key=t}}function nL(n,t,e){const o=t.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(Oe,s.id,"block id is required"),g(Oe,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 e.onInsertBlock(n,r,s),!0}function Cp(n,t,e,o){if(e==="upsert"&&nL(n,t,o))return;g(Oe,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.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(Oe,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Oe,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Oe,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Oe,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Oe,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Oe,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Wb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Oe,typeof l=="string","data is not string"),g(Oe,l!=="text","data !== 'text'"),g(Oe,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Wb?o.onDeleteBlock(n,i):l instanceof pp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function oL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function rL(n,t,e){const o=n[1],r=n[2];g(Oe,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Oe,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Oe.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Oe.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ap(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ap(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){oL(n);return}if(r==="comments"){rL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Cp(i,s,t,e)}):n.slice(1).forEach(s=>{Cp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Oe,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Cp(i,n.slice(1),t,e)}function qb(n,t,e){const o=new eL(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{Ap(a,i,o)}):Ap(s,i,o)}o.end()}const iL=S("sharedb-comments");function bp(n){const t=n.blocks;g(iL,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),mt.default(e)}function Gb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function vp(n,t){const e=zD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const se=S("sharedb-doc/doc-container"),Zb="ot-json1";Ud.type.registerSubtype(VD.type),Ud.type.name=Zb,Ud.type.invert=null;class nu extends fa{constructor(e,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",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);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",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!ua.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 e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){se.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(se.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),se.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(se.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Zb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const o=e.map(({containerId:r,blocks:i})=>[ji(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async e=>{const o=[ji(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[ji(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[ji(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ji(e),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(e,o,r)=>{const i=[ji(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){se.warn("handleOp: destroyed");return}try{qb(e,this,!!o)}catch(i){throw se.error(i),i}});this.client=e,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(se,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new JS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new nu(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||KS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw se.error(o),se.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}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((e,o)=>{if(this.localPresence)e();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()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return Wa(this.data())}getContainerBlocks(e){const o=this.data();g(se,o,"no doc data");const r=o[ji(e)];return g(se,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(se,r,"no doc data");const i=r[ji(e)];g(se,i,`no container data: ${e}`);const s=i[o];return g(se,s,`no block data: ${o}`),mt.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(se,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(se,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Gb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return bp(o)}localCreateComment(e,o){const r=vp(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=vp(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Kl(e),o,r)})}onInsertBlock(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Kl(e),o,r,i)})}onDeleteContainer(e,o){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Kl(e),o)})}onCreateContainer(e,o,r){g(se,this.callbacks.length>0,"no callbacks"),g(se,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Kl(e),o,r)})}onDeleteComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){g(se,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(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:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return Wa(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Wa(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Wa(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Wa(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){qb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Qb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,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 Yb=S("remote-cursor-decorator");class yp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Yb,typeof s=="string","invalid path containerId"),g(Yb,typeof l=="number","invalid path blockIndex");const a=t.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 Jb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Gt(Vr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=et(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function sL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).addListener("change",t)}function lL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).removeListener("change",t)}const Ent="",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 xnt="";S("button");function fo(n,t,e,o,r){const i=k("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}const Int="",Kb=`<?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">
|
|
@@ -527,7 +527,7 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
|
527
527
|
<path d="M1.00098 12.9985L10.9995 2.99998" stroke="currentColor"/>
|
|
528
528
|
<path d="M11.9113 6.16809L13.7433 3.79209C13.946 3.52009 14.0473 3.26142 14.0473 3.01609V2.90409C14.0473 2.71209 13.994 2.56009 13.8873 2.44809C13.786 2.33609 13.6473 2.28009 13.4713 2.28009C13.2953 2.28009 13.1567 2.33876 13.0553 2.45609C12.954 2.57342 12.9033 2.73609 12.9033 2.94409V3.07209H11.8873V2.88009C11.8873 2.59209 11.9513 2.33609 12.0793 2.11209C12.2127 1.88809 12.402 1.71209 12.6473 1.58409C12.8927 1.45609 13.1807 1.39209 13.5113 1.39209C13.8313 1.39209 14.1113 1.45876 14.3513 1.59209C14.5967 1.72542 14.7833 1.90409 14.9113 2.12809C15.0447 2.35209 15.1113 2.60009 15.1113 2.87209V3.00809C15.1113 3.24809 15.0687 3.46942 14.9833 3.67209C14.898 3.87476 14.7727 4.08276 14.6073 4.29609L13.2313 6.08009H15.1113V7.00009H11.9113V6.16809Z" fill="currentColor"/>
|
|
529
529
|
</svg>
|
|
530
|
-
`,Ks=S("text-commands");function l8(n){const t={id:"more",name:L.t("commands.more"),icon:Xb,childrenType:"menu",childrenPlacement:"bottom-start",manualShowChildren:!0,children:[]},e={"style-bold":[L.t("commands.bold"),io("CtrlOrCmd+B"),vz],"style-italic":[L.t("commands.italic"),io("CtrlOrCmd+I"),yz],"style-underline":[L.t("commands.underline"),io("CtrlOrCmd+U"),kz],"style-strikethrough":[L.t("commands.strikethrough"),io("CtrlOrCmd+D"),wz],"style-code":[L.t("commands.code"),void 0,Bz]},o={"style-super":[L.t("commands.superscript"),void 0,xz],"style-sub":[L.t("commands.subscript"),void 0,Ez]};if(rn(n)===0){const l=Object.entries(e).map(([a,[d,h,p]])=>({id:a,name:d,icon:p,desc:h}));return t.children=Object.entries(o).map(([a,[d,h,p]])=>({id:a,name:d,icon:p,desc:h})),l.concat(t)}const r=Az(n);function i([l,[a,d,h]]){const p=r.get(l);return p!==void 0?{id:l,name:a,value:p,states:p===!0?["checked"]:void 0,icon:h,desc:d}:{id:l,name:a,icon:h,desc:d}}const s=Object.entries(e).map(i);return t.children=Object.entries(o).map(i),s.concat(t)}function Iz(n,t){const e=it(t),o=Dt(t),r=So(n,t);return l8([]).map(i=>({blockId:e,blockType:o,blockKind:r,...i,groupIndex:500}))}function Tz(n,t,e){g(Ks,e.isSimple(),"nor a simple range");const{start:o,end:r}=e;g(Ks,o.isSimple(),"is not a simple block position"),g(Ks,r.isSimple(),"is not a simple block position"),g(Ks,nt(n,t),"invalid block type, not a text kind block");const i=it(t);g(Ks,o.blockId===i&&r.blockId===i,"invalid range");const s=n.getBlockText(t);let l=[];o.offset===r.offset?o.offset!==0&&(l=Ve(s,o.offset-1,1).middle):l=Ve(s,o.offset,r.offset-o.offset).middle;const a=Dt(t),d=So(n,t);return l8(l).map((h,p)=>({blockId:i,blockType:a,blockKind:d,...h,groupIndex:500,order:p*100}))}function Dz(n,t,e,o,r,i){if(!nt(n,t))return!1;if(!o.startsWith("style-"))return Ks.warn(`unknown command: ${o}`),!1;const s=r==null?void 0:r.value,l=typeof s;if(l!=="string"&&l!=="number"&&l!=="boolean"&&l!=="undefined")return Ks.warn(`invalid value type, accept string | number | boolean | undefined, current is ${l}`),!1;const a=bz(n,t,e,o,s);return i.result=a,!0}const Sz=S("text-command-provider");class wr{constructor(t){m(this,"id","TextCommandProvider");m(this,"emptyTextBlockAttributes",new Map);m(this,"colorItem");m(this,"updateButtonColor",()=>{const t=$g(this.editor,this.getEmptyTextBlockColor);this.colorItem.updateButtonColor(t)});m(this,"handleChangeColor",(t,e)=>{if(t==="color"||t==="backgroundColor")Q6(this.editor,t,e,this.setEmptyTextBlockColor);else{const o=["clearAll","clearColor","clearBackground"];Y6(this.editor,o[e],this.setEmptyTextBlockColor)}});m(this,"handleBeforePopupPalette",()=>{const t=$g(this.editor,this.getEmptyTextBlockColor);this.colorItem.updatePaletteColor(t)});m(this,"getEmptyTextBlockColor",(t,e)=>{const o=this.getEmptyBlockTextAttributes(t,e);return fg(o)});m(this,"setEmptyTextBlockColor",(t,e,o,r)=>{var s;const i=(s=this.emptyTextBlockAttributes.get(e))!=null?s:{};n6(i,o,r),this.emptyTextBlockAttributes.set(e,i)});this.editor=t,this.colorItem=t.addCustom("text-color-item",()=>new yM(t)),this.colorItem.addListener("onClick",this.handleChangeColor),this.colorItem.addListener("beforePopup",this.handleBeforePopupPalette)}destroy(){this.colorItem.destroy()}getAvailableCommands(t,e,o){if(!nt(t,e))return[];let r;ut(t,e)===0?r=this.getCommandsOnEmptyText(t,e).map(wr.toTextCommand):r=Tz(t,e,o).map(wr.toTextCommand),this.updateButtonColor();const s={...this.colorItem,blockId:it(e),blockKind:So(t,e),blockType:Dt(e),groupIndex:500,order:350};return r.push(s),r}executeCommand(t,e,o,r,i,s){if(!nt(t,e))return!1;let l=i.value;l===void 0&&(l=!r.value);const a=wr.fromTextCommandId(r.id);if(a.startsWith("style-")){if(a==="style-font")return this.handleChangeColor(i.type,l),!0;if(ut(t,e)===0)return this.executeCommandOnEmptyText(e,r,{value:l})}return Dz(t,e,o,a,{value:l},s)}executeCommandOnEmptyText(t,e,o){let r=this.emptyTextBlockAttributes.get(it(t));r||(r={},this.emptyTextBlockAttributes.set(it(t),r));const i=wr.fromTextCommandId(e.id),s=o.value;return s==null||s===!1?(delete r[i],!0):(r[i]=o.value,!0)}getCommandsOnEmptyText(t,e){const o=Iz(t,e);return this.setCommandsStates(o,e)}setCommandsStates(t,e){var i;const o=it(e),r=(i=this.emptyTextBlockAttributes.get(o))!=null?i:{};return t.map(s=>{const l=r[s.id],a=l?["checked"]:void 0;return s.children&&(s.children=this.setCommandsStates(s.children,e)),{...s,value:l,states:a}})}getEmptyBlockTextAttributes(t,e){var r;const o=mt.default((r=this.emptyTextBlockAttributes.get(e))!=null?r:{});if(Array.from(Object.entries(o)).forEach(([i,s])=>{s||delete o[i]}),Object.keys(o).length!==0)return o}static toTextCommand(t){return t.children&&(t.children=t.children.map(wr.toTextCommand)),{...t,id:`text/${t.id}`}}static fromTextCommandId(t){const e="text/";return g(Sz,t.startsWith(e),`invalid item id: ${t}`),t.substring(e.length)}static fromTextCommand(t){return{...t,id:this.fromTextCommandId(t.id)}}static toTextCommands(t){return t.map(wr.toTextCommand)}static fromTextCommands(t){return t.map(wr.fromTextCommand)}}function c8(n){const t=n.getCustom("toolbar-handler");t.disableTextToolbar(),t.hide(),setTimeout(()=>{t.enableTextToolbar()},300)}function Lz(n){n.undoManager.canUndo()&&c8(n)}function Mz(n){n.undoManager.canRedo()&&c8(n)}const Rz={"CtrlOrCmd+Z":Lz,"CtrlOrCmd+Shift+Z":Mz},Oz={commands:{bold:"\u7C97\u4F53",italic:"\u659C\u4F53",underline:"\u4E0B\u5212\u7EBF",strikethrough:"\u5220\u9664\u7EBF",code:"\u884C\u5185\u4EE3\u7801",subscript:"\u4E0B\u6807",superscript:"\u4E0A\u6807",more:"\u66F4\u591A"}},_z={commands:{bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",code:"Inline code",subscript:"Subscript",superscript:"Superscript",more:"More"}},Fz={commands:{bold:"\u592A\u5B57",italic:"\u659C\u4F53",underline:"\u4E0B\u7DDA",strikethrough:"\u53D6\u308A\u6D88\u3057\u7DDA",code:"\u30A4\u30F3\u30E9\u30A4\u30F3\u30B3\u30FC\u30C9",subscript:"\u4E0B\u4ED8\u304D\u6587\u5B57",superscript:"\u4E0A\u4ED8\u304D\u6587\u5B57",more:"\u305D\u306E\u4ED6"}};L.mergeLang({"zh-CN":Oz,"en-US":_z,"ja-JP":Fz});const Pz={embedProperties:{edit:"\u7F16\u8F91",addComment:"\u6DFB\u52A0\u6279\u6CE8"}},Nz={embedProperties:{edit:"Edit",addComment:"Add annotation"}},$z={embedProperties:{edit:"\u7DE8\u96C6",addComment:"\u30B3\u30E1\u30F3\u30C8\u3092\u8FFD\u52A0"}};L.mergeLang({"zh-CN":Pz,"en-US":Nz,"ja-JP":$z});const a8=S("embed-block-properties");function Uu(n,t){var e;for(const o of n.blockHooks){const r=(e=o.commands)==null?void 0:e.call(o,n,t);if(!!r&&r.group==="block-comment-actions")return r.executeCommand(n,t,r.commands[0]),!0}return!1}class D2{constructor(t,e,o){m(this,"group","hovering-toolbar");m(this,"_commands",[{id:"edit",name:L.t("embedProperties.edit"),icon:Mp},{id:"add-comment",name:L.t("embedProperties.addComment"),icon:ec}]);this.editor=t,this.block=e,this.properties=o}get commands(){var r,i,s;if(this.editor.readonly)return[];let t=this._commands;const{enableComments:e=!0}=this.editor.options;e||(t=t.filter(l=>l.id!=="add-comment")),t.forEach(l=>{(l.id==="add-comment"||l.id==="edit")&&(l.states=this.editor.isBlockWritable(this.block)?[]:["disabled"])});
|
|
530
|
+
`,Ks=S("text-commands");function l8(n){const t={id:"more",name:L.t("commands.more"),icon:Xb,childrenType:"menu",childrenPlacement:"bottom-start",manualShowChildren:!0,children:[]},e={"style-bold":[L.t("commands.bold"),io("CtrlOrCmd+B"),vz],"style-italic":[L.t("commands.italic"),io("CtrlOrCmd+I"),yz],"style-underline":[L.t("commands.underline"),io("CtrlOrCmd+U"),kz],"style-strikethrough":[L.t("commands.strikethrough"),io("CtrlOrCmd+D"),wz],"style-code":[L.t("commands.code"),void 0,Bz]},o={"style-super":[L.t("commands.superscript"),void 0,xz],"style-sub":[L.t("commands.subscript"),void 0,Ez]};if(rn(n)===0){const l=Object.entries(e).map(([a,[d,h,p]])=>({id:a,name:d,icon:p,desc:h}));return t.children=Object.entries(o).map(([a,[d,h,p]])=>({id:a,name:d,icon:p,desc:h})),l.concat(t)}const r=Az(n);function i([l,[a,d,h]]){const p=r.get(l);return p!==void 0?{id:l,name:a,value:p,states:p===!0?["checked"]:void 0,icon:h,desc:d}:{id:l,name:a,icon:h,desc:d}}const s=Object.entries(e).map(i);return t.children=Object.entries(o).map(i),s.concat(t)}function Iz(n,t){const e=it(t),o=Dt(t),r=So(n,t);return l8([]).map(i=>({blockId:e,blockType:o,blockKind:r,...i,groupIndex:500}))}function Tz(n,t,e){g(Ks,e.isSimple(),"nor a simple range");const{start:o,end:r}=e;g(Ks,o.isSimple(),"is not a simple block position"),g(Ks,r.isSimple(),"is not a simple block position"),g(Ks,nt(n,t),"invalid block type, not a text kind block");const i=it(t);g(Ks,o.blockId===i&&r.blockId===i,"invalid range");const s=n.getBlockText(t);let l=[];o.offset===r.offset?o.offset!==0&&(l=Ve(s,o.offset-1,1).middle):l=Ve(s,o.offset,r.offset-o.offset).middle;const a=Dt(t),d=So(n,t);return l8(l).map((h,p)=>({blockId:i,blockType:a,blockKind:d,...h,groupIndex:500,order:p*100}))}function Dz(n,t,e,o,r,i){if(!nt(n,t))return!1;if(!o.startsWith("style-"))return Ks.warn(`unknown command: ${o}`),!1;const s=r==null?void 0:r.value,l=typeof s;if(l!=="string"&&l!=="number"&&l!=="boolean"&&l!=="undefined")return Ks.warn(`invalid value type, accept string | number | boolean | undefined, current is ${l}`),!1;const a=bz(n,t,e,o,s);return i.result=a,!0}const Sz=S("text-command-provider");class wr{constructor(t){m(this,"id","TextCommandProvider");m(this,"emptyTextBlockAttributes",new Map);m(this,"colorItem");m(this,"updateButtonColor",()=>{const t=$g(this.editor,this.getEmptyTextBlockColor);this.colorItem.updateButtonColor(t)});m(this,"handleChangeColor",(t,e)=>{if(t==="color"||t==="backgroundColor")Q6(this.editor,t,e,this.setEmptyTextBlockColor);else{const o=["clearAll","clearColor","clearBackground"];Y6(this.editor,o[e],this.setEmptyTextBlockColor)}});m(this,"handleBeforePopupPalette",()=>{const t=$g(this.editor,this.getEmptyTextBlockColor);this.colorItem.updatePaletteColor(t)});m(this,"getEmptyTextBlockColor",(t,e)=>{const o=this.getEmptyBlockTextAttributes(t,e);return fg(o)});m(this,"setEmptyTextBlockColor",(t,e,o,r)=>{var s;const i=(s=this.emptyTextBlockAttributes.get(e))!=null?s:{};n6(i,o,r),this.emptyTextBlockAttributes.set(e,i)});this.editor=t,this.colorItem=t.addCustom("text-color-item",()=>new yM(t)),this.colorItem.addListener("onClick",this.handleChangeColor),this.colorItem.addListener("beforePopup",this.handleBeforePopupPalette)}destroy(){this.colorItem.destroy()}getAvailableCommands(t,e,o){if(!nt(t,e))return[];let r;ut(t,e)===0?r=this.getCommandsOnEmptyText(t,e).map(wr.toTextCommand):r=Tz(t,e,o).map(wr.toTextCommand),this.updateButtonColor();const s={...this.colorItem,blockId:it(e),blockKind:So(t,e),blockType:Dt(e),groupIndex:500,order:350};return r.push(s),r}executeCommand(t,e,o,r,i,s){if(!nt(t,e))return!1;let l=i.value;l===void 0&&(l=!r.value);const a=wr.fromTextCommandId(r.id);if(a.startsWith("style-")){if(a==="style-font")return this.handleChangeColor(i.type,l),!0;if(ut(t,e)===0)return this.executeCommandOnEmptyText(e,r,{value:l})}return Dz(t,e,o,a,{value:l},s)}executeCommandOnEmptyText(t,e,o){let r=this.emptyTextBlockAttributes.get(it(t));r||(r={},this.emptyTextBlockAttributes.set(it(t),r));const i=wr.fromTextCommandId(e.id),s=o.value;return s==null||s===!1?(delete r[i],!0):(r[i]=o.value,!0)}getCommandsOnEmptyText(t,e){const o=Iz(t,e);return this.setCommandsStates(o,e)}setCommandsStates(t,e){var i;const o=it(e),r=(i=this.emptyTextBlockAttributes.get(o))!=null?i:{};return t.map(s=>{const l=r[s.id],a=l?["checked"]:void 0;return s.children&&(s.children=this.setCommandsStates(s.children,e)),{...s,value:l,states:a}})}getEmptyBlockTextAttributes(t,e){var r;const o=mt.default((r=this.emptyTextBlockAttributes.get(e))!=null?r:{});if(Array.from(Object.entries(o)).forEach(([i,s])=>{s||delete o[i]}),Object.keys(o).length!==0)return o}static toTextCommand(t){return t.children&&(t.children=t.children.map(wr.toTextCommand)),{...t,id:`text/${t.id}`}}static fromTextCommandId(t){const e="text/";return g(Sz,t.startsWith(e),`invalid item id: ${t}`),t.substring(e.length)}static fromTextCommand(t){return{...t,id:this.fromTextCommandId(t.id)}}static toTextCommands(t){return t.map(wr.toTextCommand)}static fromTextCommands(t){return t.map(wr.fromTextCommand)}}function c8(n){const t=n.getCustom("toolbar-handler");t.disableTextToolbar(),t.hide(),setTimeout(()=>{t.enableTextToolbar()},300)}function Lz(n){n.undoManager.canUndo()&&c8(n)}function Mz(n){n.undoManager.canRedo()&&c8(n)}const Rz={"CtrlOrCmd+Z":Lz,"CtrlOrCmd+Shift+Z":Mz},Oz={commands:{bold:"\u7C97\u4F53",italic:"\u659C\u4F53",underline:"\u4E0B\u5212\u7EBF",strikethrough:"\u5220\u9664\u7EBF",code:"\u884C\u5185\u4EE3\u7801",subscript:"\u4E0B\u6807",superscript:"\u4E0A\u6807",more:"\u66F4\u591A"}},_z={commands:{bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",code:"Inline code",subscript:"Subscript",superscript:"Superscript",more:"More"}},Fz={commands:{bold:"\u592A\u5B57",italic:"\u659C\u4F53",underline:"\u4E0B\u7DDA",strikethrough:"\u53D6\u308A\u6D88\u3057\u7DDA",code:"\u30A4\u30F3\u30E9\u30A4\u30F3\u30B3\u30FC\u30C9",subscript:"\u4E0B\u4ED8\u304D\u6587\u5B57",superscript:"\u4E0A\u4ED8\u304D\u6587\u5B57",more:"\u305D\u306E\u4ED6"}};L.mergeLang({"zh-CN":Oz,"en-US":_z,"ja-JP":Fz});const Pz={embedProperties:{edit:"\u7F16\u8F91",addComment:"\u6DFB\u52A0\u6279\u6CE8"}},Nz={embedProperties:{edit:"Edit",addComment:"Add annotation"}},$z={embedProperties:{edit:"\u7DE8\u96C6",addComment:"\u30B3\u30E1\u30F3\u30C8\u3092\u8FFD\u52A0"}};L.mergeLang({"zh-CN":Pz,"en-US":Nz,"ja-JP":$z});const a8=S("embed-block-properties");function Uu(n,t){var e;for(const o of n.blockHooks){const r=(e=o.commands)==null?void 0:e.call(o,n,t);if(!!r&&r.group==="block-comment-actions")return r.executeCommand(n,t,r.commands[0]),!0}return!1}class D2{constructor(t,e,o){m(this,"group","hovering-toolbar");m(this,"_commands",[{id:"edit",name:L.t("embedProperties.edit"),icon:Mp},{id:"add-comment",name:L.t("embedProperties.addComment"),icon:ec}]);this.editor=t,this.block=e,this.properties=o}get commands(){var r,i,s;if(this.editor.readonly)return[];let t=this._commands;const{enableComments:e=!0}=this.editor.options;e||(t=t.filter(l=>l.id!=="add-comment")),t.forEach(l=>{(l.id==="add-comment"||l.id==="edit")&&(l.states=this.editor.isBlockWritable(this.block)?[]:["disabled"])});let o=(r=this.properties)!=null&&r.presetIds?t.filter(l=>{var a,d;return(d=(a=this.properties)==null?void 0:a.presetIds)==null?void 0:d.includes(l.id)}):[...t];return(s=(i=this.properties)==null?void 0:i.extCommands)!=null&&s.length&&(o.length&&o.push({id:K(),type:"separator",name:""}),o.push(...this.properties.extCommands)),o.length<=3&&(o=o.filter(l=>l.id!=="separator")),o}executeCommand(t,e,o){var r,i;if(!((i=(r=this.properties)==null?void 0:r.handleExecuteCommand)!=null&&i.call(r,t,e,o))){if(o.id==="add-comment"){Uu(t,e)||a8.error("failed to add comment to block");return}a8.error(`unknown command: ${JSON.stringify(o)}`)}}}function S2(n,t,e){return{blockCommands:{"hovering-toolbar":new D2(n,t,e)}}}class zu{constructor(t){m(this,"blockResizer");m(this,"handleResizing",(t,e)=>{var r,i;const o=t.getBlock();if(o){if(((i=(r=Yt(this.editor,o)).notify)==null?void 0:i.call(r,this.editor,"resize",{block:o,rect:e}))===!0)return;const s=Math.max(e.height,100),d={...this.editor.getBlockData(o).embedData,height:s};this.editor.updateEmbedData(o,d)}});m(this,"handleHoveringBlockChange",(t,e)=>{e&&Ie(e)&&xt(e,"resizable")&&this.disableResizer(),t&&Ie(t)&&xt(t,"resizable")&&this.editor.isBlockWritable(t)&&this.tryEnableResizer(t)});this.editor=t,Ce.get(t).addListener("change",this.handleHoveringBlockChange),this.blockResizer=new Iu(this.editor,{resize:["bottom"]}),this.blockResizer.addListener("resizing",this.handleResizing)}destroy(){Ce.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}tryEnableResizer(t){this.blockResizer.enableResize(t)}disableResizer(){this.blockResizer.disableResize()}static get(t){return t.addCustom("EmbedBlockResizer",()=>new zu(t))}static register(t,e){return W(e,"resizable"),t.addCustom("EmbedBlockResizer",()=>new zu(t))}}var u8=(n=>(n.Card="card",n.Preview="preview",n))(u8||{});const Hz=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="#5587F0">
|
|
531
531
|
<g clip-path="url(#clip0)">
|
|
532
532
|
<path d="M6.01 10.4886C5.85 10.4886 5.7 10.4286 5.58 10.3086L3.98 8.71859C3.35 8.07859 3 7.23859 3 6.34859C3 5.45859 3.35 4.60859 3.98 3.97859C5.29 2.66859 7.41 2.66859 8.72 3.97859L10.31 5.56859C10.55 5.80859 10.55 6.18859 10.31 6.42859C10.07 6.66859 9.69 6.66859 9.45 6.42859L7.86 4.83859C7.03 4.00859 5.68 4.00859 4.85 4.83859C4.45 5.23859 4.23 5.77859 4.23 6.34859C4.23 6.91859 4.45 7.44859 4.85 7.85859L6.44 9.44859C6.68 9.68859 6.68 10.0686 6.44 10.3086C6.32 10.4286 6.16 10.4886 6.01 10.4886ZM11.65 14.9986C10.79 14.9986 9.93 14.6686 9.28 14.0186L7.4 12.1386C7.16 11.8986 7.16 11.5186 7.4 11.2786C7.64 11.0386 8.02 11.0386 8.26 11.2786L10.14 13.1586C10.97 13.9886 12.32 13.9886 13.15 13.1586C13.55 12.7586 13.77 12.2186 13.77 11.6486C13.77 11.0786 13.55 10.5486 13.15 10.1386L11.28 8.25859C11.04 8.01859 11.04 7.63859 11.28 7.39859C11.52 7.15859 11.9 7.15859 12.14 7.39859L14.02 9.27859C14.65 9.90859 15 10.7486 15 11.6486C15 12.5386 14.65 13.3886 14.02 14.0186C13.37 14.6686 12.51 14.9986 11.65 14.9986Z" fill="currentColor"/>
|
|
533
533
|
<path d="M10.88 10.8604C10.67 11.0704 10.32 11.0704 10.1 10.8604L7.64004 8.40039C7.43004 8.19039 7.43004 7.84039 7.64004 7.62039C7.85004 7.41039 8.20004 7.41039 8.42004 7.62039L10.88 10.0804C11.1 10.3004 11.1 10.6404 10.88 10.8604Z" fill="currentColor"/>
|