@ones-editor/editor 0.0.3-beta.187 → 0.0.3-beta.188
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 f6={boxType:"br",updateBoxContent:jI,convertTo:UI},m6=S("editor-boxes");class g6{constructor(t){m(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);g(m6,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return g(m6,e,`unknown box type: ${t}`),e}createBox(t,e){const o=VC(e),r=qC(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}}function zI(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=w("img",a,e);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const p6={boxType:"image",updateBoxContent:zI},VI="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function WI(n,t,e){W(e,"editor-box-anchor"),Cm(VI,[],e)}const C6={boxType:"anchor",updateBoxContent:WI};function qI(n,t,e,o){w("span",[],e,o.text)}const A6={insertionType:"inputting",updateInsertionContent:qI},b6=S("editor-insertion");class v6{constructor(t){m(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);g(b6,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return g(b6,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=GC(e.type,e.id),r=QC(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class GI{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=ZC(this.editor,e);r&&ot(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 GI(d)).add(r.id,r.time),W(t,"active")),w("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 y6{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 QI{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)&&!Ss(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)&&!Ss(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=w("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 k6(n){const t=n.rootElement,e=t.getBoundingClientRect(),o=ys(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,A=0-e.left+h,v=0-e.top+p,B=n.input.inputElement;B.style.left=`${A/o}px`,B.style.top=`${v/o}px`}const wg=S("editor-caret");class YI{constructor(t){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=w("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 je))return!1;const e=this.editor.getBlockById(t.blockId);return!!tt(this.editor,e)}update(){if(eC(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",k6(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 je,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(wg,tt(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 A=ro(r,{horizontal:!0}).getBoundingClientRect(),v=A.left-l.left,B=v+A.width;a<v||a>B?(k6(this.editor),t.style.display="none"):t.style.display=""}}function JI(n){t4(n),n.selection.range.getSelectedBlocks().forEach(t=>e4(n,t.block,t.start,t.end))}const KI=S("editor-dom");function w6(n){return ro(n.rootContainer).clientHeight}function XI(n){return n.getFirstBlock().getBoundingClientRect().top}function tT(n){return n.getLastBlock().getBoundingClientRect().bottom}function Bg(n){const e=ro(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 eT(n,t){const e=Bg(n),o=n.getBlockById(t.blockId),i=So(n,o,t);return ks(e,i.x,i.y)&&ks(e,i.right,i.bottom)}function B6(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 nT(n,t){const e=Bg(n),o=t.getBoundingClientRect();return ks(e,o.x,o.y)||ks(e,o.right,o.bottom)}function oT(n){if(!ym(n.rootContainer)){KI.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 h=o,p=n.getContainerById(h.childContainerId);nT(n,p)||p.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const h=n.getBlockById(e.range.start.blockId);if(Me(h)&&B6(n,h)||Mt(n,h)&&B6(n,h))return}const r=o,i=n.getBlockById(r.blockId);if(eT(n,r))return;const s=So(n,i,r),l=i.getBoundingClientRect(),a=te(i),d=w("div",["editor-block-anchor"],a);d.style.top=`${s.top-l.top}px`,km(d,{elementToScroll:ro(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function rT(n,t){if(t.isCollapsed())return!1;const e=Le(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 E6=S("range-in-block");function x6(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||Kt(n,o),s=r===n||Kt(n,r);return!!(i||s)}function I6(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=ce(t);if(i){for(;i&&!o.has(it(i));)i=ce(i);g(E6,i,"no prev block while deleting a block"),r=ye(n,i,ut(n,i))}else{const s=Zt(t);g(E6,s,"no prev and next block while deleting a block"),r=ye(n,s,0)}return r}const iT=S("block-to-html");function Eg(n,t,e,o){const r=Ls(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;g(iT,t.text,"no text");const i=ie(t.text);return`<div>${iC(i)}</div>`}const T6=S("block-to-text");function sT(n,t,e){let o="";return t.forEach(r=>{if(g(T6,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 vh(n,t,e,o){const r=Ls(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(g(T6,t.text,"no text"),sT(n,t.text,e))}function xg(n,t,e,o){const r=Ls(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):vh(n,t,e,o)}function yh(n,t){return t.blocks.root.map((r,i)=>Eg(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
25
25
|
`)}function D6(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${yh(n,t)}</body></html>`}function La(n,t){return t.blocks.root.map((r,i)=>vh(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
26
26
|
`)}function Ma(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 lT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof je||g(lT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=nt(r),l=at(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=ze(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function cT(n,t,e){const o=nt(t),r=at(o),i=bt(t);return Ig(n,r,i,e)}function S6(n,t,e,o,r){const i=nt(t),s=at(i),l=bt(t),a=cT(n,t,e),d=uh(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),gn(n,t)}function L6(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=uh(e," ",o);return n.doc.localUpdateBlockText(i,s,l),gn(n,t)}function aT(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+dh(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")&&(aT(i.text,r)||delete s.link);const l=uh(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),gn(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 kh=S("update-composition-text");function M6(n){const t=n.selection.range.start;t instanceof je||g(kh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(kh,tt(n,o),"not a text kind block");const r=nt(o),i=at(r),s=bt(o),l=n.doc.getBlockData(i,s);g(kh,l,"no block data in doc"),g(kh,l.text,"no text data in text block");const a=Lt(o);sh(n,Li(o),e,a,l.text)}function R6(n){Hx(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ra=S("delete-block-text");function Sg(n,t,e,o,r){if(!n.isBlockWritable(t))return Ra.error("block is not writable"),0;g(Ra,tt(n,t),"block is not a text kind block");const i=nt(t),s=at(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Ra,a,"no block data in doc"),g(Ra,a.text,"no text data in text block");let d=e;sn(t,e)||(d=Ri(t,d));let h=e+o;g(Ra,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=Fs(t,h));const p=h-d,A=z4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Lg=S("break-text-block");function O6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Lg,tt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Lg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=nt(t),i=at(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?O6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...lr(""),...l,...o==null?void 0:o.newBlockData},D=ye(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=gn(n,t),{right:d}=In(a,e),h=rn(d);h>0&&Sg(n,t,e,h);const p={...lr(d),...l,...o==null?void 0:o.newBlockData},A=Zl(n,i,s+1,p,ye(n,p.id,0));return{block:t,newBlock:A}}const uT=S("prepare-insert-new-block");function dT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=pe(d);return g(uT,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=at(nt(r)),e=bt(r),!tt(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 hT=S("auto-insert-block");function _6(n,t,e,o,r,i){const s=dT(n,e,o);g(hT,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 fT=S("delete-block");function wh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{wh(n,i,e)})}))}function Bh(n,t,e){const o=nt(t),r=at(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(fT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ue(n,{anchor:e.start,focus:e.end})),s}function Mg(n,t,e){return n.undoManager.runInGroup(()=>{const o=nt(t);Io(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Mi(n,e):null;if(!r){const l=n.selection.range;x6(t,l)?r=I6(n,t):r=l}const i=Bh(n,t,r),s=[];return wh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function mT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{wh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function F6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{wh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Rg=S("merge-text-block");function P6(n,t,e){g(Rg,tt(n,t),"only text block can be merged"),g(Rg,tt(n,e),"only text block can be merged");const o=_i(n,t),r=_i(n,e),i=o.text,s=r.text;g(Rg,i&&s,"block data has no text");const l=nt(t),a=at(l),d=bt(t),h=ut(n,t),p=Tg(n,s,a,d,h),A=ye(n,t,rn(i));return Mg(n,e,A),p}const cr=S("clear-selected-contents");function Eh(n,t){g(cr,tt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(cr,e.isSimple(),"not a simple block position"),g(cr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(cr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function N6(n,t,e){const o=at(t),r=pe(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 gT(n,t){const{block:e,start:o,end:r}=t;if(tt(n,e)){Eh(n,t);return}if(Me(e)||o.isSimple()){g(cr,r.isSimple(),"invalid range");const s=nt(e),l=bt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(cr,Mt(n,e),"invalid block kind"),g(cr,!o.isSimple()&&!r.isSimple(),"invalid range"),Rs(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{N6(n,s,{focus:l===0})})}function pT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(cr,e.length>0,"no selected block"),e.length===1){gT(n,e[0]);return}const o=e[0],r=o.block,i=nt(r);g(cr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(tt(n,r)){Eh(n,o);const h=ye(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),tt(n,l)){Eh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(tt(n,l)){Eh(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===Io(i)){N6(n,i,{focus:!0});return}const a=ce(r),d=Zt(l);g(cr,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(),pT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const CT=S("core");function $6(n,t,e){const o=nt(t),r=at(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),gn(n,t)}function H6(n,t,e){if(!n.isBlockWritable(t)){CT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);$6(n,t,r)}function xh(n,t,e){const o=gn(n,t),r=typeof e=="string"?Oi(e):e,i=ln.diff(o,r);return $6(n,t,i)}const Oa=S("update-block-data");function Ih(n,t,e,o){const r=nt(t),i=at(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(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Oa.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(e).forEach(([A,v])=>{g(Oa,A!=="id"&&A!=="type",`invalid block data delta, ${A}`);const B=l[A];if(v==null){B!=null&&(Oa.debug(`delete key: ${A}`),a.delete.push(A));return}B!==v&&(aa.default(B,v)||A==="text"&&ln.diff(B,v).length===0||(d.has(A)?(Oa.debug(`replace key: ${A}`),a.delete.push(A)):Oa.debug(`insert key: ${A}`),a.insert[A]=v))}),n.doc.localUpdateBlockData(i,s,a,o),_i(n,t)}function j6(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=Le(r);_g(n,i,e)}function $s(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 Fi(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"),Fi(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(),A=t.blocks[h];g(_a,Array.isArray(A),"invalid child blocks");const v=A.map(_=>Fi(n,t,_,o)),B=$s(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[A,v]=p;{const B=`${A}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return _a.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${A}_`;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 A=d(h);A!==h&&delete l.key,l[A]=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=>Fi(n,t,l,o));return $s(i)}function Pg(n,t,e){const o=t.blocks.root.map(r=>Fi(n.editorBlocks,t,r,e));return mt.default($s(o))}const U6=S("insert-doc");function z6(n,t,e,o,r){if(Mt(n,t)){U6.warn("failed to insert doc into a complex block");return}const i=Pg(n,o,r),s=nt(t),l=bt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,H,z;Object.entries(i.blocks).forEach(([q,rt])=>{q!=="root"&&n.doc.localInsertChildContainer(q,rt)});const d=i.blocks.root;if(Me(t)){n.deleteBlock(t);let q;d.reverse().forEach(rt=>{const ft=n.insertBlock(a,l,rt);q||(q=ft)}),q&&n.selection.selectBlock(q,ut(n,q));return}if(g(U6,tt(n,t),"not a text block"),he(n,t)){const q=a==="root"&&n.getBlockByIndex(a,0)===t,rt=bt(t);let ft;d.forEach((Bt,jt)=>{const Ut=n.insertBlock(a,rt+jt,Bt);jt===d.length-1&&(ft=Ut)}),ft&&n.selection.selectBlock(ft,ut(n,ft)),q&&n.deleteBlock(t);return}if(d.length===1){const q=d[0];if(ya(n,q.type)){n.insertTextToBlock(t,e,(M=q.text)!=null?M:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,q);return}const h=e===ut(n,t),p=e===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(t,e,{forceInsertAfter:!0}):B=t;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ut(n,B))):(n.selection.selectBlock(B,0),ya(n,v.type)?n.insertTextToBlock(B,0,(H=v.text)!=null?H:[]):n.insertBlock(a,D,v));const x=n.selection.range;let _=D;ya(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(t,e,(z=A.text)!=null?z:[]):(n.insertBlock(a,D,A),_+=1),d.slice(1,d.length-1).reverse().forEach(q=>{n.insertBlock(a,_,q)}),n.selection.setRange(x)}),n.doc.endBatchUpdate()}function Ng(n,t,e,o,r){const i=Pg(n,o,r),s=at(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([d,h])=>{d!=="root"&&n.doc.localInsertChildContainer(d,h)}),i.blocks.root.reverse().forEach(d=>{const h=n.insertBlock(s,e,d);l.push(h)})}),l}function V6(n,t,e){const o=Io(t);Ng(n,t,o,e);for(let r=0;r<o;r++){const i=Le(t);n.deleteBlock(i)}}const Fa=S("add-text-attribute");function AT(n,t,e,o){const{start:r,end:i}=e;g(Fa,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Fa,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 W6(n,t,e,o,r){const{start:i,end:s}=e;g(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Fa,o,"invalid attribute name");const l=n.getBlockText(t),a=Ia(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(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=K4(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function q6(n,t,e,o){const r=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!tt(n,s))return;if(he(n,s)){o(n,it(s),t,e);return}const d=Ue(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 G6(n,t,e){const o=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!tt(n,i))return;if(he(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=Ue(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=Ro(n,{simpleBlockOnly:!0}).filter(s=>tt(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 e6(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 Z6(n){const t=[];for(;n;){const e=nt(n);if(t.unshift(e),Xt(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 Q6(n,t){for(;t;){const e=nt(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 bT(n,t){const e=Z6(n),o=Z6(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=Q6(r,n),s=Q6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Y6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=nt(e);g(Wn,Lo(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 Th(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof je&&e instanceof je?{anchor:t,focus:e}:t instanceof Mo&&e instanceof Mo?rh(n,o,t,e):null;const i=nt(o),s=nt(r);if(i===s)return t instanceof Mo&&(t=st(o,0,"home")),e instanceof Mo&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof je,"not valid position type"),g(Wn,e instanceof je,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof je&&e instanceof Mo){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,at(i)),_=fe(D,at(B));return rh(n,D,x,_)}}return null}const l=Hd(o,r)>0,{newBlock1:a,newBlock2:d}=bT(o,r);if(a===d){const B=a,D=Y6(B,o),x=Y6(B,r);return t=fe(a,at(D)),e=fe(a,at(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),rh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof je&&(h=t.offset);let A=l?0:ut(n,d);return d===r&&e instanceof je&&(A=e.offset),t=st(a,h,l?"end":"home"),e=st(d,A,l?"home":"end"),{anchor:t,focus:e}}const vT=S("move-complex-block-position");function yT(n,t,e){const o=n.getBlockById(t.blockId);g(vT,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,at(s)):null}const Pa=S("move-simple-block-position");function J6(n,t){const e=xn(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[0];return Le(o)}function K6(n,t){const e=xn(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qe(o)}function X6(n,t,e){const o=e?J6(n,t):K6(n,t);return Mt(n,o)?X6(n,o,e):o}function kT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?J6(n,e):Ds(e)}function wT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?K6(n,e):Ts(e)}function Hg(n){return n==="ArrowLeft"||n==="ArrowUp"}function jg(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);g(Pa,r,"child container has not parent block"),g(Pa,Mt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?Hg(e)?Qe(i):Le(i):jg(n,r,e)}function BT(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);if(g(Pa,r,"child container has not parent block"),Hg(e)){const l=ce(r);if(l)return l}else{const l=Zt(r);if(l)return l}const i=jg(n,r,e);if(i)return i;let s=r;for(;!Xt(nt(s));)s=et(nt(s));return Hg(e)?ce(s):Zt(s)}function ET(n,t,e){return!Mt(n,t)||zn(n,t).enableKeyboardSelect?t:X6(n,t,e==="ArrowDown"||e==="ArrowRight")}function xT(n,t,e){const o=n.getBlockById(t.blockId),i=Qt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?kT(n,t):wT(n,t);if(s||(s=jg(n,o,e),s||(s=BT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Xt(nt(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(l,0,"home")}return null}if(s=ET(n,s,e),tt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Kx(n,s,o,t,l);if(e==="ArrowUp")return Jx(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 IT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(tt(n,r))return o;const i=Zt(r);if(i)return st(i,0,"home");if(!Xt(nt(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(s,0,"home")}function TT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=IT(n,t,o):r=xT(n,o.getFocusedPos(),t);else if(r=yT(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=Le(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Th(n,o.anchor,r):null}function Pi(n,t,e){const o=TT(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 tA(n){return Pi(n,"ArrowLeft","move"),!0}function eA(n){return Pi(n,"ArrowRight","move"),!0}function nA(n){return Pi(n,"ArrowUp","move"),!0}function oA(n){if(Pi(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=nt(t);if(Xt(e)||Qe(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),Io(o)),!0}function rA(n){return Pi(n,"ArrowDown","select"),!0}function iA(n){return Pi(n,"ArrowLeft","select"),!0}function sA(n){return Pi(n,"ArrowRight","select"),!0}function lA(n){return Pi(n,"ArrowUp","select"),!0}const cA=S("word-offset");function Ug(n,t){const e=n.selection.range.focus;g(cA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"home");if(e.offset===0||!tt(n,o)){const s=ce(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&tt(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(cA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!tt(n,o)){const s=Zt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&tt(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 aA(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 uA(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 dA(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 hA(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=pe(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=pe(o),i=r[r.length-1];return Wg(n,i)}function fA(n){const t=Wg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function mA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function gA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function qg(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 pA=S("line-offset");function CA(n){const t=n.selection.range.focus;g(pA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!tt(n,e))return st(e,0,"home");let r=N4(e,t).start;const{next:i}=th(e,r);return i&&so(i)&&va(i)==="br"&&(r+=1),st(e,r,"home")}function AA(n){const t=n.selection.range.focus;g(pA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!tt(n,e))return st(e,ut(n,e),"end");const o=N4(e,t);return st(e,o.end,"end")}function bA(n){if(!n.selection.range.focus.isSimple())return!1;const e=CA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function vA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=CA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const wA=S("find-block-position");function DT(n,t,e,o){g(wA,Mt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(wA,r.length>0,"complex block has not any child container");const i=So(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=I4(n,t,s,l);return Gg(n,a,e,o)}function Gg(n,t,e,o){if(Mt(n,t))return DT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=So(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 A=st(r,p,"normal"),v=So(n,t,A),B=nr(v,l,a);B<i&&(i=B,d=A)}return d}const BA=S("page-offset");function ST(n,t){const e=w6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<XI(n))return n.getFirstBlock();const i=ce(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ce(s)}return n.getFirstBlock()}function LT(n,t){const e=w6(n)*.9,o=t.getBoundingClientRect(),r=tT(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Zt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Zt(l)}return n.getLastBlock()}function EA(n){const t=n.selection.range.focus;g(BA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ST(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Gg(n,o,e,t),r}function xA(n){const t=n.selection.range.focus;g(BA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=LT(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Gg(n,o,e,t),r}function IA(n){if(!n.selection.range.focus.isSimple())return!1;const e=EA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function TA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=EA(n);if(!e)return!1;const o=Th(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 SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);if(!e)return!1;const o=Th(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 Na=S("select-all");function LA(n,t){const e=Le(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 MT(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===at(r)&&t.end.blockId===s&&t.end.childContainerId===at(i)}function RT(n,t){g(Na,t,"no parent block"),g(Na,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(Ue(n,{anchor:fe(t,at(o)),focus:fe(t,at(r))}))}function MA(n,t){const e=nt(t);Zg(n,e)}function RA(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&tt(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"),MA(n,Le(n.rootContainer)),!1}return g(Na,!e.isSimple(),"invalid range type"),MT(t,e)?(MA(n,t),!1):(g(Na,t,"no parent block"),g(Na,Mt(n,t),"not a complex block"),RT(n,t),!0)}function Zg(n,t){const e=pe(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 OA(n){qg(n),n.focus()}const Qg=S("selected-block-to-doc");function _A(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{_A(n,i,e)}),e.blocks[o]=mt.default(r)})}function Dh(n,t){const e=Qt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(_i(n,t.block));if(tt(n,t.block)){const i=t.start,s=t.end;if(g(Qg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=ze(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Me(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Qg,Mt(n,t.block),"not complex block"),g(Qg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return _A(n,o,r),r}function Yg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Dh(n,{block:t,start:e,end:o})}const OT=S("block-to-doc");function _T(n,t){g(OT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Yg(n,o));return $s(e)}function Sh(n){const e=n.selection.range.getSelectedBlocks().map(o=>Dh(n,o));return $s(e)}function FA(n,t){const e=n.getContainerById(t),i=pe(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Dh(n,s));return $s(i)}const Lh=S("editor-selection");class FT{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(x6(e,i)){Lh.debug("adjust selection because remote deleted current block");const s=I6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new YI(t);const r=st(o,0,"normal");this._range=Ue(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=Ue(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()||!rT(this.editor,r))&&ot(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(),JI(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(!Ur(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=So(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){oT(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Lh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Lh,!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")&&(ot(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=Sh(this.editor);return t==="text"?La(this.editor,e):t==="markdown"?Ma(this.editor,e):D6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{ot(t,"focused"),ot(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=nt(t);for(;Lo(e);){const o=et(e);g(Lh,o,"parent block not found"),W(o,"child-focused"),e=nt(o)}return!0}}function PT(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 NT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!tt(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=S4(this.editor,t.x,t.y);if(o){if(o instanceof rr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=ro(s[0].block);this.autoScroll=new Zd({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=ih(this.editor,t.x,t.y);if(!e)return;const o=Th(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){NT(this.editor)}handleTripleClick(t){PT(this.editor)}}function HT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function jT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const PA=S("delete-text");function NA(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof je||g(PA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(PA,tt(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=Ri(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 $A(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const UT=S("handle-backspace");function Jg(n,t){if(!he(n,t))return;const e=nt(t);Io(e)!==1&&n.deleteBlock(t)}function zT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===0){if($A(n,o))return;const r=ce(o);if(r){if(!n.isBlockWritable(r))return;if(tt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Jg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Jg(n,o),g(UT,Me(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=nt(o);if(Lo(i)){const s=B4(n,i);if(s){if(!n.isBlockWritable(s))return;Jg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else NA(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function VT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===ut(n,o)){const r=Zt(o);if(r){if(!n.isBlockWritable(r))return;tt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):he(n,o)?n.deleteBlock(o,ye(n,r,0)):n.deleteBlock(r)}}else NA(n,"forward",1,null);else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function WT(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(Ur(e))return!0;const s=Rs(n,r,e,o),l=xn(n,r);return s.length===l.length}function qT(n,t){if(WT(n)){const o=n.getFocusedBlock(),r=bt(o),i=at(nt(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(tt(n,e)){if(he(n,e)&&$A(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function GT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!tt(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 ZT=S("input-handler-actions");function QT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(qT(n),!0))}function YT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(VT(n),!0))}function JT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function KT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(GT(n),!0))}function XT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{ZT.error(t)}),!0)}const Mh={ArrowDown:oA,ArrowUp:nA,ArrowLeft:tA,ArrowRight:eA,"Shift+ArrowDown":rA,"Shift+ArrowUp":lA,"Shift+ArrowLeft":iA,"Shift+ArrowRight":sA,"CtrlOrCmd+ArrowLeft":aA,"CtrlOrCmd+ArrowRight":uA,"CtrlOrCmd+Shift+ArrowLeft":dA,"CtrlOrCmd+Shift+ArrowRight":hA,"CtrlOrCmd+ArrowUp":mA,"CtrlOrCmd+ArrowDown":fA,"CtrlOrCmd+Shift+ArrowUp":gA,"CtrlOrCmd+Shift+ArrowDown":qg,"CtrlOrCmd+A":RA,Home:yA,End:kA,"Shift+Home":bA,"Shift+End":vA,PageUp:IA,PageDown:TA,"Shift+PageUp":DA,"Shift+PageDown":SA,"CtrlOrCmd+Z":HT,"CtrlOrCmd+Shift+Z":jT,Enter:QT,Delete:YT,Backspace:JT,"Shift+Enter":KT,"CtrlOrCmd+Shift+V":XT};function HA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function jA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(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=>{jA(n,l,e)})})}function UA(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):jA(t,r,e)})}async function tD(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 eD(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 nD(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(eD(n,t)){const s=Array.from(Object.keys(o));r=await tD(n,s),UA(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&&UA(n,t,i)}async function oD(n,t,e){await nD(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Me(i)){const s=nt(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 rD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function iD(n){let t;for(const e of rD)if(t=n[e],t)break;return t||null}function zA(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=>{zA(n,l,e)})})}function sD(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)}):zA(t,r,e)}),Array.from(e)}function Rh(n,t){return Ze.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><div id="ones-editor-doc">${Si(JSON.stringify(t))}</div>${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Si(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Oh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=sD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function lD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Sh(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Oh(n,o);const i=yh(n,o),s=Ma(n,o),l=Rh(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 _h(n,t){const e=Yg(n,t);Oh(n,e);const o=yh(n,e),r=Ma(n,e),i=Rh(o,e);return Lm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class cD{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(!tt(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){lD(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;Me(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(){ot(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 HA(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 oD(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=iD(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 aD(n,t,e){const o=Fr(t,e);return o.remove(),o}S("copy-dom-attributes");const VA=["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 uD(n,t){for(let l=0;l<VA.length;l++){const a=VA[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 WA(n){const t=Array.from(n.childNodes).filter(e=>!$C(e));return t.forEach(e=>{e.remove()}),t}function qA(n,t,e){var d;const o=n.getContainerById(t),r=Fr(o,e),i=Li(r),s=n.doc.getBlockData(t,e),l=Qt(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=WA(h);WA(r),p.forEach(v=>{r.appendChild(v)});const A=Kd(h);if(A){const v=Kd(r);v&&v.remove(),r.appendChild(A)}uD(h,r)}o4(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 dD=S("transform-selection");function GA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(dD,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 Ue(n,{anchor:l,focus:a})}const hD=S("handle-block-text-changed");function fD(n,t,e,o,r){const i=n.getContainerById(t),s=Fr(i,e),l=n.doc.getBlockData(t,e);if(g(hD,l.text,"no block text"),JC(n,s).setBlockText(n,s,l.text),!r){const a=GA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function mD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function ZA(n,t,e,o){const r=Qt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function gD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{ZA(n,i,o,{child:!0})}),ZA(n,r,o,{child:!1})}const _o=S("editor-doc");class pD extends ha{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(_o,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(_o,l,`no text, ${e}, ${o}`);const a=GA(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(_o,!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(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(mD(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(Mi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(_o,!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 this.editor.selection.setRange(Mi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(_o,!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(Mi(this.editor,r)),s}localDeleteChildContainers(e){return g(_o,!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)}localInsertChildContainer(e,o){return g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,mt.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){_o.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)}),fD(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)}),qA(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);ox(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){gD(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);aD(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){_o.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function QA(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 Kg=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(Kg,t,"no other action"),!1}combine(t){g(Kg,!1,"no other")}setAfterRange(t){this.afterRange&&Kg.warn("after range has already set"),this.afterRange=t}}const CD=S("block-action");class YA 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(CD,this.blockIndex===bt(i),"invalid block index"),Bh(e,i,Mi(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}class AD extends YA{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class bD extends YA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class vD extends Jl{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){QA(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 Hs=S("update-block-data-action");class Fh 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(Hs,this.blockId===i.id,"invalid block id"),g(Hs,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hs,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Ih(e,o,Fh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Ih(e,o,Fh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const Xg=S("update-block-text-action");class $a 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=$a.calType(i,s)}static calType(e,o){g(Xg,e,"no old data"),g(Xg,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>mC(h)?`cjk_${h}`:hC(h)?"number":Ud(h)?"space":fC(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?(xh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(xh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof $a)||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(Xg,e instanceof $a,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class JA 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.localInsertChildContainer(this.containerId,mt.default(this.blocks)),!0}}class yD extends JA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class kD extends JA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Fo=S("undo");class wD{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):(QA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new vD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Fo.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(Mi(this.editor,t.beforeRange))}catch(e){Fo.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(Mi(this.editor,e)):Fo.warn("no after range")}catch(e){Fo.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 $a(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Fh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,e>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new AD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new yD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new kD(this.editor,t,e)))}}class BD{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 ED{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new BD)}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 xD{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||!Kt(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&&Kt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&ot(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(!tt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:Nm(o)}}const KA="style-color-",XA="style-bg-color-";class ID{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(KA)?i["data-style-color"]=l.substring(KA.length):l.startsWith(XA)?i["data-style-bg-color"]=l.substring(XA.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 TD(n){n.editorBlocks.registerBlockClass(Tn),n.editorBlocks.registerBlockClass(w4),n.editorBoxes.registerBoxClass(h6),n.editorBoxes.registerBoxClass(f6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(C6),n.editorInsertions.registerInsertionClass(A6),n.editorBlockRenders.registerRender(new ID)}function DD(n,t){TD(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 tb=S("range-commands");function eb(n,t){n.forEach(e=>{e.source=t,e.children&&eb(e.children,t)})}function nb(n,t,e){const o=it(t);g(tb,o===e.start.blockId,"invalid start range"),g(tb,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);eb(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)&&Rs(n,t,e.start,e.end).forEach(l=>{pe(l).forEach(d=>{const h=ut(n,d),p=Ue(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),A=nb(n,d,p);i.push(...A)})}),i}function ob(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ue(t,{anchor:r.start,focus:r.end});nb(t,r.block,i).forEach(l=>{o.push(l)})}),o}function rb(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.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)&&Rs(n,t,e.start,e.end).forEach(A=>{pe(A).forEach(B=>{const D=ut(n,B),x=Ue(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});rb(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function ib(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=Ue(o,{anchor:l.start,focus:l.end});rb(o,l.block,a,t,e,r)}),r}const SD=S("command-providers");class sb{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(SD,e,`no command provider, id=${t}`),e}getCommands(t){return ob(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>ib(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 LD(n,t){const e=nt(t),o=at(e),r=bt(t);qA(n,o,r)}const MD=S("table-scroll");class lb{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 RD{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)){MD.warn(`event has already registered: ${e}`);return}i.push(new lb(this.editor,t,e,o,r))}else{const s=new lb(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 cb=S("update-block-text");function OD(n,t){const e=n.getBoxById(t.id),o=et(e);g(cb,o,"no parent block"),g(cb,tt(n,o),"not a text block");const r=n.getBlockText(o),i=o6(r,"id",t.id,t);H6(n,o,i)}function _D(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 FD(n){return n.readonly?!1:!Ro(n).find(o=>!n.isBlockWritable(o.block))}class PD{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 ND{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(_r(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Gr=S("editor");class $D 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 ND);m(this,"dataConverter",new ED);m(this,"editorBlocks",new b4(this));m(this,"editorBoxes",new g6(this));m(this,"editorInsertions",new v6(this));m(this,"editorEmbeds",new y4(this));m(this,"editorDecorators",new y6(this));m(this,"editorCommandProviders",new sb(this));m(this,"editorBlockRenders",new xD(this));m(this,"blockHooks",[]);m(this,"domEvents",new RD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new cD(this));m(this,"settingsProvider");m(this,"_readonly",!1);Gr.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 PD(this),DD(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 wD(this),this.doc=new pD(this,o,this.undoManager),this.parent=e,this.rootElement=w("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=w("div",["editor-content"],this.rootElement),this.rootContainerObject=p4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new QI(this,this.inputHandlers),this.selection=new FT(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"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:ro(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(Gr,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(){Gr.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 FD(this)}isBlockWritable(e){return _D(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return g(Gr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Gr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return C4(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(Gr,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Gr,Pm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Gr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Gr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Fr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return jr(this,e)}getParentContainer(e){return nt(e)}reloadBlock(e){LD(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 P6(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 _i(this,e)}getBoxData(e){return u6(this,e)}getBlockText(e){return gn(this,e)}setBlockText(e,o){H6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Sg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return S6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return L6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){z6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Ng(this,e,o,r,i)}deleteChildContainers(e){F6(this,e)}replaceBlockText(e,o){return xh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Ih(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return j6(this,e,o,r)}updateBoxData(e){OD(this,e)}getSelectedText(){const e=Sh(this);return La(this,e)}clearSelectedContents(){Og(this)}insertTextBlock(e,o,r,i){const s=lr(e!=null?e:"");return _6(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){R6(this);return}o?(this.compositingText="",zd()||Dg(this,e)):(this.compositingText=e,M6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Ha(n,t,e){return new $D(n,t,e)}function HD(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=mm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const jD=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Ph 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:jD}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&aa.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.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){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&&gh(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(gh(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 tp extends ha{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[lr("")]}},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}localInsertChildContainer(e,o){this.doc.blocks[e]=o,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!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 Ph}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 UD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function ep(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new UD(o)})}const ab=S("find-block");function ub(n,t){const e=Ts(t);if(!e){if(io(t))return null;const o=xs(t);return g(ab,o,"no parent block"),ub(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function db(n,t){const e=Ds(t);if(!e){if(io(t))return null;const o=xs(t);return g(ab,o,"no parent block"),db(n,o)}return Mt(n,e)?Xm(n,e,{visibleOnly:!0}):e}const zD=S("remote-cursor");class VD{constructor(){m(this,"remoteUsers",new Ph)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):zD.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 WD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function qD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function ja(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=WD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Ni(n){return n==="root"?"blocks":n}function Kl(n){return n==="blocks"?"root":n}const GD={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 ar=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$i={},np=q5.default.EventEmitter;$i.EventEmitter=np,$i.mixin=ZD;function ZD(n){for(var t in np.prototype)n.prototype[t]=np.prototype[t]}var hb=["info","warn","error"];function fb(){var n={};hb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var QD=fb;fb.prototype.setMethods=function(n){n=n||{};var t=this;hb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var YD=QD,JD=new YD,mb=JD;function js(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,js):this.stack=new Error().stack}js.prototype=Object.create(Error.prototype),js.prototype.constructor=js,js.prototype.name="ShareDBError",js.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 Nh=js,Ua={},gb=KD;function KD(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=[],A=0;A<s.length;){var v=[];if(r(s[A],h,p,v),A++,v.length===1)h=v[0];else if(v.length===0){for(var B=A;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(A),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 pb={exports:{}},Hi=pb.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||""}},op=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},rp=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")},$h=function(n){for(var t=0;t<n.length;t++)rp(n[t])};Hi.apply=function(n,t){var e;$h(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=op(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 Zr=Hi._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:op(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:op(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Hi.compose=function(n,t){$h(n),$h(t);for(var e=n.slice(),o=0;o<t.length;o++)Zr(e,t[o]);return e},Hi.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),Zr(t,o)}return t};var ip=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};Hi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=ip(n,t[r],o);return n};var XD=Hi._tc=function(n,t,e,o){if(rp(t),rp(e),t.i!=null)Zr(n,{i:t.i,p:ip(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Zr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Zr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Zr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Zr(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=ip(i.p,e),Zr(n,i))}return n},tS=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Hi.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=tS(n[t]);return n},gb(Hi,XD,$h,Zr);var Hh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},eS=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Qr={};It.registerSubtype=function(n){Qr[n.name]=n},It.create=function(n){return n===void 0?null:Po(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Qr[n.t]&&(t.t=n.t,t.o=Qr[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(!Hh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Hh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!eS(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function za(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 Va(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=Po(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&za(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&&Qr[r.t])s[l]=Qr[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 nS=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=Po(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)&&(za(t),za(e)),nS(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Qr[t.t]){if(e.o=Qr[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(),Va(t),n.push(t);Va(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)&&(Va(t),Va(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=Po(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Hh(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=Po(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=Po(e);a.p=a.p.slice(s),t.ld=It.apply(Po(t.ld),[a])}else if(t.od!==void 0){var a=Po(e);a.p=a.p.slice(s),t.od=It.apply(Po(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)&&(za(t),a=Po(e),za(a)),a.t&&Qr[a.t]){if(t.t&&t.t===a.t){var h=Qr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,A=0;A<h.length;A++)t.o=[h[A]],t.p=p.slice(),Va(t),It.append(n,t);else(!Hh(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=Po(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},gb(It,It.transformComponent,It.checkValidOp,It.append);var oS=pb.exports;It.registerSubtype(oS);var rS=It,iS={type:rS};(function(n){n.defaultType=iS.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)})(Ua);var No={};(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))}})(No);var Cb=Array.isArray,Ab=Object.keys,sS=Object.prototype.hasOwnProperty,lS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Cb(t),r=Cb(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 A=Ab(t);if(s=A.length,s!==Ab(e).length)return!1;for(i=s;i--!==0;)if(!sS.call(e,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},bb=$i,cS=mb,qn=Nh,jh=Ua,$o=No,aS=$o.clone,uS=lS,Dn=qn.CODES,dS=Ft;function Ft(n,t,e){bb.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}bb.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=jh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Dn.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(Dn.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(Dn.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?jh.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;$o.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===Dn.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){$o.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){$o.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===Dn.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=Uh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Uh(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);hS(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=fS([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;$o.nextTick(function(){n._handleSubscribe()})}}};function hS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function fS(n){return n=n.filter($o.truthy),n.length?function(t){$o.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function mS(n){delete n.op,delete n.create,delete n.del}function Uh(n,t){if(n.del)return mS(t);if(t.del)return new qn(Dn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Dn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Dn.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(Dn.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===jh.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=Uh(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(Dn.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>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Dn.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(Dn.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;$o.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&&!uS(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=jh.defaultType.uri),this.type){var r=new qn(Dn.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(Dn.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:aS(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 cS.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=Uh(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=$o.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=$o.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Us={};Us.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 vb=$i,yb=Us.ACTIONS,gS=No,pS=Sn;function Sn(n,t,e,o,r,i,s){vb.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}vb.mixin(Sn),Sn.prototype.hasPending=function(){return!this.ready},Sn.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}},Sn.prototype.destroy=function(n){this.connection.canSend&&this.action===yb.querySubscribe&&this.connection.send({a:yb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&gS.nextTick(n)},Sn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Sn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Sn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Sn.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()},Sn.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},Sn.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)},Sn.prototype._handleError=function(n){this.emit("error",n)},Sn.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)},Sn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var kb=$i,CS=Us.ACTIONS,AS=No,wb=ur;function ur(n,t){if(kb.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={}}kb.mixin(ur),ur.prototype.submit=function(n,t){this.value=n,this.send(t)},ur.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},ur.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()})},ur.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},ur.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},ur.prototype._message=function(){return{a:CS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ur.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},ur.prototype._callbackOrEmit=function(n,t){if(t)return AS.nextTick(t,n);n&&this.emit("error",n)};var bS=No,Bb=sp;function sp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}sp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},sp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&bS.nextTick(n)};var lp={exports:{}};(function(n,t){(function(e,o){o(t)})(ar,function(e){function o(k,T){T=T|0;for(var L=Math.max(k.length-T,0),F=Array(L),U=0;U<L;U++)F[U]=k[T+U];return F}var r=function(k){var T=o(arguments,1);return function(){var L=o(arguments);return k.apply(null,T.concat(L))}},i=function(k){return function(){var T=o(arguments),L=T.pop();k.call(this,T,L)}};function s(k){var T=typeof k;return k!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(k){setTimeout(k,0)}function h(k){return function(T){var L=o(arguments,1);k(function(){T.apply(null,L)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var A=h(p);function v(k){return i(function(T,L){var F;try{F=k.apply(this,T)}catch(U){return L(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(L,null,U)},function(U){B(L,U.message?U:new Error(U))}):L(null,F)})}function B(k,T,L){try{k(T,L)}catch(F){A(D,F)}}function D(k){throw k}var x=typeof Symbol=="function";function _(k){return x&&k[Symbol.toStringTag]==="AsyncFunction"}function M(k){return _(k)?v(k):k}function H(k){return function(T){var L=o(arguments,1),F=i(function(U,j){var Z=this;return k(T,function(J,lt){M(J).apply(Z,U.concat(lt))},j)});return L.length?F.apply(this,L):F}}var z=typeof ar=="object"&&ar&&ar.Object===Object&&ar,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=z||q||Function("return this")(),ft=rt.Symbol,Bt=Object.prototype,jt=Bt.hasOwnProperty,Ut=Bt.toString,ne=ft?ft.toStringTag:void 0;function qe(k){var T=jt.call(k,ne),L=k[ne];try{k[ne]=void 0;var F=!0}catch{}var U=Ut.call(k);return F&&(T?k[ne]=L:delete k[ne]),U}var Yn=Object.prototype,$e=Yn.toString;function Rn(k){return $e.call(k)}var kr="[object Null]",vn="[object Undefined]",an=ft?ft.toStringTag:void 0;function wr(k){return k==null?k===void 0?vn:kr:an&&an in Object(k)?qe(k):Rn(k)}var oi="[object AsyncFunction]",po="[object Function]",K2="[object GeneratorFunction]",X2="[object Proxy]";function t3(k){if(!s(k))return!1;var T=wr(k);return T==po||T==K2||T==oi||T==X2}var ns=9007199254740991;function nl(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=ns}function ol(k){return k!=null&&nl(k.length)&&!t3(k)}var ri={};function Nt(){}function Br(k){return function(){if(k!==null){var T=k;k=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Fc=function(k){return os&&k[os]&&k[os]()};function l1(k,T){for(var L=-1,F=Array(k);++L<k;)F[L]=T(L);return F}function un(k){return k!=null&&typeof k=="object"}var rl="[object Arguments]";function c1(k){return un(k)&&wr(k)==rl}var Co=Object.prototype,a1=Co.hasOwnProperty,e3=Co.propertyIsEnumerable,il=c1(function(){return arguments}())?c1:function(k){return un(k)&&a1.call(k,"callee")&&!e3.call(k,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,u1=ll&&!0&&n&&!n.nodeType&&n,cl=u1&&u1.exports===ll,d1=cl?rt.Buffer:void 0,al=d1?d1.isBuffer:void 0,rs=al||sl,Hu=9007199254740991,ju=/^(?:0|[1-9]\d*)$/;function Uu(k,T){var L=typeof k;return T=T==null?Hu:T,!!T&&(L=="number"||L!="symbol"&&ju.test(k))&&k>-1&&k%1==0&&k<T}var zu="[object Arguments]",Vu="[object Array]",Wu="[object Boolean]",qu="[object Date]",Gu="[object Error]",Zu="[object Function]",n3="[object Map]",o3="[object Number]",r3="[object Object]",h1="[object RegExp]",f1="[object Set]",i3="[object String]",s3="[object WeakMap]",l3="[object ArrayBuffer]",c3="[object DataView]",m1="[object Float32Array]",a3="[object Float64Array]",u3="[object Int8Array]",d3="[object Int16Array]",Qu="[object Int32Array]",h3="[object Uint8Array]",Yu="[object Uint8ClampedArray]",f3="[object Uint16Array]",m3="[object Uint32Array]",se={};se[m1]=se[a3]=se[u3]=se[d3]=se[Qu]=se[h3]=se[Yu]=se[f3]=se[m3]=!0,se[zu]=se[Vu]=se[l3]=se[Wu]=se[c3]=se[qu]=se[Gu]=se[Zu]=se[n3]=se[o3]=se[r3]=se[h1]=se[f1]=se[i3]=se[s3]=!1;function g3(k){return un(k)&&nl(k.length)&&!!se[wr(k)]}function p3(k){return function(T){return k(T)}}var g1=typeof e=="object"&&e&&!e.nodeType&&e,ul=g1&&!0&&n&&!n.nodeType&&n,C3=ul&&ul.exports===g1,Pc=C3&&z.process,p1=function(){try{var k=ul&&ul.require&&ul.require("util").types;return k||Pc&&Pc.binding&&Pc.binding("util")}catch{}}(),C1=p1&&p1.isTypedArray,A3=C1?p3(C1):g3,b3=Object.prototype,v3=b3.hasOwnProperty;function y3(k,T){var L=Ae(k),F=!L&&il(k),U=!L&&!F&&rs(k),j=!L&&!F&&!U&&A3(k),Z=L||F||U||j,J=Z?l1(k.length,String):[],lt=J.length;for(var pt in k)(T||v3.call(k,pt))&&!(Z&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Uu(pt,lt)))&&J.push(pt);return J}var Nc=Object.prototype;function k3(k){var T=k&&k.constructor,L=typeof T=="function"&&T.prototype||Nc;return k===L}function $c(k,T){return function(L){return k(T(L))}}var w3=$c(Object.keys,Object),B3=Object.prototype,E3=B3.hasOwnProperty;function A1(k){if(!k3(k))return w3(k);var T=[];for(var L in Object(k))E3.call(k,L)&&L!="constructor"&&T.push(L);return T}function Hc(k){return ol(k)?y3(k):A1(k)}function b1(k){var T=-1,L=k.length;return function(){return++T<L?{value:k[T],key:T}:null}}function x3(k){var T=-1;return function(){var F=k.next();return F.done?null:(T++,{value:F.value,key:T})}}function I3(k){var T=Hc(k),L=-1,F=T.length;return function U(){var j=T[++L];return j==="__proto__"?U():L<F?{value:k[j],key:j}:null}}function T3(k){if(ol(k))return b1(k);var T=Fc(k);return T?x3(T):I3(k)}function Ao(k){return function(){if(k===null)throw new Error("Callback was already called.");var T=k;k=null,T.apply(this,arguments)}}function dl(k){return function(T,L,F){if(F=Br(F||Nt),k<=0||!T)return F(null);var U=T3(T),j=!1,Z=0,J=!1;function lt(ct,At){if(Z-=1,ct)j=!0,F(ct);else{if(At===ri||j&&Z<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Z<k&&!j;){var ct=U();if(ct===null){j=!0,Z<=0&&F(null);return}Z+=1,L(ct.value,ct.key,Ao(lt))}J=!1}pt()}}function Er(k,T,L,F){dl(T)(k,M(L),F)}function He(k,T){return function(L,F,U){return k(L,T,F,U)}}function Ju(k,T,L){L=Br(L||Nt);var F=0,U=0,j=k.length;j===0&&L(null);function Z(J,lt){J?L(J):(++U===j||lt===ri)&&L(null)}for(;F<j;F++)T(k[F],F,Ao(Z))}var D3=He(Er,1/0),Go=function(k,T,L){var F=ol(k)?Ju:D3;F(k,M(T),L)};function Zo(k){return function(T,L,F){return k(Go,T,M(L),F)}}function Ku(k,T,L,F){F=F||Nt,T=T||[];var U=[],j=0,Z=M(L);k(T,function(J,lt,pt){var ct=j++;Z(J,function(At,Gt){U[ct]=Gt,pt(At)})},function(J){F(J,U)})}var jc=Zo(Ku),Xu=H(jc);function ii(k){return function(T,L,F,U){return k(dl(L),T,M(F),U)}}var xr=ii(Ku),td=He(xr,1),ed=H(td);function is(k,T){for(var L=-1,F=k==null?0:k.length;++L<F&&T(k[L],L,k)!==!1;);return k}function nd(k){return function(T,L,F){for(var U=-1,j=Object(T),Z=F(T),J=Z.length;J--;){var lt=Z[k?J:++U];if(L(j[lt],lt,j)===!1)break}return T}}var ss=nd();function ls(k,T){return k&&ss(k,T,Hc)}function v1(k,T,L,F){for(var U=k.length,j=L+(F?1:-1);F?j--:++j<U;)if(T(k[j],j,k))return j;return-1}function S3(k){return k!==k}function y1(k,T,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===T)return F;return-1}function hl(k,T,L){return T===T?y1(k,T,L):v1(k,S3,L)}var Uc=function(k,T,L){typeof T=="function"&&(L=T,T=null),L=Br(L||Nt);var F=Hc(k),U=F.length;if(!U)return L(null);T||(T=U);var j={},Z=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ls(k,function(de,re){if(!Ae(de)){Gt(re,[de]),ct.push(re);return}var ge=de.slice(0,de.length-1),vo=ge.length;if(vo===0){Gt(re,de),ct.push(re);return}At[re]=vo,is(ge,function(E){if(!k[E])throw new Error("async.auto task `"+re+"` has a non-existent dependency `"+E+"` in "+ge.join(", "));en(E,function(){vo--,vo===0&&Gt(re,de)})})}),K3(),Ie();function Gt(de,re){pt.push(function(){bo(de,re)})}function Ie(){if(pt.length===0&&Z===0)return L(null,j);for(;pt.length&&Z<T;){var de=pt.shift();de()}}function en(de,re){var ge=lt[de];ge||(ge=lt[de]=[]),ge.push(re)}function Fn(de){var re=lt[de]||[];is(re,function(ge){ge()}),Ie()}function bo(de,re){if(!J){var ge=Ao(function(E,Dr){if(Z--,arguments.length>2&&(Dr=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pt){ds[Pt]=Pn}),ds[de]=Dr,J=!0,lt=Object.create(null),L(E,ds)}else j[de]=Dr,Fn(de)});Z++;var vo=M(re[re.length-1]);re.length>1?vo(j,ge):vo(ge)}}function K3(){for(var de,re=0;ct.length;)de=ct.pop(),re++,is(X3(de),function(ge){--At[ge]===0&&ct.push(ge)});if(re!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function X3(de){var re=[];return ls(k,function(ge,vo){Ae(ge)&&hl(ge,de,0)>=0&&re.push(vo)}),re}};function si(k,T){for(var L=-1,F=k==null?0:k.length,U=Array(F);++L<F;)U[L]=T(k[L],L,k);return U}var L3="[object Symbol]";function M3(k){return typeof k=="symbol"||un(k)&&wr(k)==L3}var R3=1/0,od=ft?ft.prototype:void 0,k1=od?od.toString:void 0;function rd(k){if(typeof k=="string")return k;if(Ae(k))return si(k,rd)+"";if(M3(k))return k1?k1.call(k):"";var T=k+"";return T=="0"&&1/k==-R3?"-0":T}function O3(k,T,L){var F=-1,U=k.length;T<0&&(T=-T>U?0:U+T),L=L>U?U:L,L<0&&(L+=U),U=T>L?0:L-T>>>0,T>>>=0;for(var j=Array(U);++F<U;)j[F]=k[F+T];return j}function _3(k,T,L){var F=k.length;return L=L===void 0?F:L,!T&&L>=F?k:O3(k,T,L)}function id(k,T){for(var L=k.length;L--&&hl(T,k[L],0)>-1;);return L}function F3(k,T){for(var L=-1,F=k.length;++L<F&&hl(T,k[L],0)>-1;);return L}function P3(k){return k.split("")}var N3="\\ud800-\\udfff",$3="\\u0300-\\u036f",H3="\\ufe20-\\ufe2f",le="\\u20d0-\\u20ff",oe=$3+H3+le,j3="\\ufe0e\\ufe0f",U3="\\u200d",z3=RegExp("["+U3+N3+oe+j3+"]");function V3(k){return z3.test(k)}var w1="\\ud800-\\udfff",W3="\\u0300-\\u036f",B1="\\ufe20-\\ufe2f",q3="\\u20d0-\\u20ff",Ge=W3+B1+q3,sd="\\ufe0e\\ufe0f",li="["+w1+"]",zc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+zc+"|"+fl+")",ld="[^"+w1+"]",cd="(?:\\ud83c[\\udde6-\\uddff]){2}",ad="[\\ud800-\\udbff][\\udc00-\\udfff]",E1="\\u200d",ud=On+"?",dd="["+sd+"]?",yn="(?:"+E1+"(?:"+[ld,cd,ad].join("|")+")"+dd+ud+")*",G3=dd+ud+yn,_n="(?:"+[ld+zc+"?",zc,cd,ad,li].join("|")+")",Z3=RegExp(fl+"(?="+fl+")|"+_n+G3,"g");function x1(k){return k.match(Z3)||[]}function Qo(k){return V3(k)?x1(k):P3(k)}function Vc(k){return k==null?"":rd(k)}var hd=/^\s+|\s+$/g;function ue(k,T,L){if(k=Vc(k),k&&(L||T===void 0))return k.replace(hd,"");if(!k||!(T=rd(T)))return k;var F=Qo(k),U=Qo(T),j=F3(F,U),Z=id(F,U)+1;return _3(F,j,Z).join("")}var Ir=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,fd=/,/,Q3=/(=.+)?(\s*)$/,md=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Y3(k){return k=k.toString().replace(md,""),k=k.match(Ir)[2].replace(" ",""),k=k?k.split(fd):[],k=k.map(function(T){return ue(T.replace(Q3,""))}),k}function I1(k,T){var L={};ls(k,function(F,U){var j,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],L[U]=j.concat(j.length>0?lt:F);else if(J)L[U]=F;else{if(j=Y3(F),F.length===0&&!Z&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||j.pop(),L[U]=j.concat(lt)}function lt(pt,ct){var At=si(j,function(Gt){return pt[Gt]});At.push(ct),M(F).apply(null,At)}}),Uc(L,T)}function Jn(){this.head=this.tail=null,this.length=0}function gd(k,T){k.length=1,k.head=k.tail=T}Jn.prototype.removeLink=function(k){return k.prev?k.prev.next=k.next:this.head=k.next,k.next?k.next.prev=k.prev:this.tail=k.prev,k.prev=k.next=null,this.length-=1,k},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.prototype.insertAfter=function(k,T){T.prev=k,T.next=k.next,k.next?k.next.prev=T:this.tail=T,k.next=T,this.length+=1},Jn.prototype.insertBefore=function(k,T){T.prev=k.prev,T.next=k,k.prev?k.prev.next=T:this.head=T,k.prev=T,this.length+=1},Jn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):gd(this,k)},Jn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):gd(this,k)},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 k=Array(this.length),T=this.head,L=0;L<this.length;L++)k[L]=T.data,T=T.next;return k},Jn.prototype.remove=function(k){for(var T=this.head;T;){var L=T.next;k(T)&&this.removeLink(T),T=L}return this};function ml(k,T,L){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=M(k),U=0,j=[],Z=!1;function J(At,Gt,Ie){if(Ie!=null&&typeof Ie!="function")throw new Error("task callback must be a function");if(ct.started=!0,Ae(At)||(At=[At]),At.length===0&&ct.idle())return A(function(){ct.drain()});for(var en=0,Fn=At.length;en<Fn;en++){var bo={data:At[en],callback:Ie||Nt};Gt?ct._tasks.unshift(bo):ct._tasks.push(bo)}Z||(Z=!0,A(function(){Z=!1,ct.process()}))}function lt(At){return function(Gt){U-=1;for(var Ie=0,en=At.length;Ie<en;Ie++){var Fn=At[Ie],bo=hl(j,Fn,0);bo===0?j.shift():bo>0&&j.splice(bo,1),Fn.callback.apply(Fn,arguments),Gt!=null&&ct.error(Gt,Fn.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Jn,concurrency:T,payload:L,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Gt){J(At,!1,Gt)},kill:function(){ct.drain=Nt,ct._tasks.empty()},unshift:function(At,Gt){J(At,!0,Gt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Gt=[],Ie=ct._tasks.length;ct.payload&&(Ie=Math.min(Ie,ct.payload));for(var en=0;en<Ie;en++){var Fn=ct._tasks.shift();At.push(Fn),j.push(Fn),Gt.push(Fn.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var bo=Ao(lt(At));F(Gt,bo)}pt=!1}},length:function(){return ct._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ct._tasks.length+U===0},pause:function(){ct.paused=!0},resume:function(){ct.paused!==!1&&(ct.paused=!1,A(ct.process))}};return ct}function ci(k,T){return ml(k,1,T)}var cs=He(Er,1);function Yo(k,T,L,F){F=Br(F||Nt);var U=M(L);cs(k,function(j,Z,J){U(T,j,function(lt,pt){T=pt,J(lt)})},function(j){F(j,T)})}function Wc(){var k=si(arguments,M);return function(){var T=o(arguments),L=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Nt,Yo(k,T,function(U,j,Z){j.apply(L,U.concat(function(J){var lt=o(arguments,1);Z(J,lt)}))},function(U,j){F.apply(L,[U].concat(j))})}}var qc=function(){return Wc.apply(null,o(arguments).reverse())},pd=Array.prototype.concat,gl=function(k,T,L,F){F=F||Nt;var U=M(L);xr(k,T,function(j,Z){U(j,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(j,Z){for(var J=[],lt=0;lt<Z.length;lt++)Z[lt]&&(J=pd.apply(J,Z[lt]));return F(j,J)})},T1=He(gl,1/0),Gc=He(gl,1),Zc=function(){var k=o(arguments),T=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,T)}};function pl(k){return k}function ai(k,T){return function(L,F,U,j){j=j||Nt;var Z=!1,J;L(F,function(lt,pt,ct){U(lt,function(At,Gt){At?ct(At):k(Gt)&&!J?(Z=!0,J=T(!0,lt),ct(null,ri)):ct()})},function(lt){lt?j(lt):j(null,Z?J:T(!1))})}}function dn(k,T){return T}var as=Zo(ai(pl,dn)),Jo=ii(ai(pl,dn)),Cl=He(Jo,1);function Cd(k){return function(T){var L=o(arguments,1);L.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[k]&&is(U,function(j){console[k](j)}))}),M(T).apply(null,L)}}var D1=Cd("dir");function S1(k,T,L){L=Ao(L||Nt);var F=M(k),U=M(T);function j(J){if(J)return L(J);var lt=o(arguments,1);lt.push(Z),U.apply(this,lt)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}Z(null,!0)}function Ad(k,T,L){L=Ao(L||Nt);var F=M(k),U=function(j){if(j)return L(j);var Z=o(arguments,1);if(T.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function L1(k,T,L){Ad(k,function(){return!T.apply(this,arguments)},L)}function M1(k,T,L){L=Ao(L||Nt);var F=M(T),U=M(k);function j(J){if(J)return L(J);U(Z)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}U(Z)}function ui(k){return function(T,L,F){return k(T,F)}}function Qc(k,T,L){Go(k,ui(M(T)),L)}function Al(k,T,L,F){dl(T)(k,ui(M(L)),F)}var di=He(Al,1);function Yc(k){return _(k)?k:i(function(T,L){var F=!0;T.push(function(){var U=arguments;F?A(function(){L.apply(null,U)}):L.apply(null,U)}),k.apply(this,T),F=!1})}function Kn(k){return!k}var hi=Zo(ai(Kn,Kn)),bl=ii(ai(Kn,Kn)),Jc=He(bl,1);function R1(k){return function(T){return T==null?void 0:T[k]}}function us(k,T,L,F){var U=new Array(T.length);k(T,function(j,Z,J){L(j,function(lt,pt){U[Z]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Z=[],J=0;J<T.length;J++)U[J]&&Z.push(T[J]);F(null,Z)})}function Xn(k,T,L,F){var U=[];k(T,function(j,Z,J){L(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Z,value:j}),J())})},function(j){j?F(j):F(null,si(U.sort(function(Z,J){return Z.index-J.index}),R1("value")))})}function Kc(k,T,L,F){var U=ol(T)?us:Xn;U(k,T,M(L),F||Nt)}var Xc=Zo(Kc),vl=ii(Kc),ta=He(vl,1);function O1(k,T){var L=Ao(T||Nt),F=M(Yc(k));function U(j){if(j)return L(j);F(U)}U()}var ea=function(k,T,L,F){F=F||Nt;var U=M(L);xr(k,T,function(j,Z){U(j,function(J,lt){return J?Z(J):Z(null,{key:lt,val:j})})},function(j,Z){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Z.length;pt++)if(Z[pt]){var ct=Z[pt].key,At=Z[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},fi=He(ea,1/0),N=He(ea,1),G=Cd("log");function V(k,T,L,F){F=Br(F||Nt);var U={},j=M(L);Er(k,T,function(Z,J,lt){j(Z,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Z){F(Z,U)})}var ht=He(V,1/0),Et=He(V,1);function Vt(k,T){return T in k}function we(k,T){var L=Object.create(null),F=Object.create(null);T=T||pl;var U=M(k),j=i(function(J,lt){var pt=T.apply(null,J);Vt(L,pt)?A(function(){lt.apply(null,L[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);L[pt]=ct;var At=F[pt];delete F[pt];for(var Gt=0,Ie=At.length;Gt<Ie;Gt++)At[Gt].apply(null,ct)})))});return j.memo=L,j.unmemoized=k,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var na=h(qt);function bd(k,T,L){L=L||Nt;var F=ol(T)?[]:{};k(T,function(U,j,Z){M(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Z(J)})},function(U){L(U,F)})}function kn(k,T){bd(Go,k,T)}function yl(k,T,L){bd(dl(T),k,L)}var vd=function(k,T){var L=M(k);return ml(function(F,U){L(F[0],U)},T,1)},mi=function(k,T){var L=vd(k,T);return L.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(L.started=!0,Ae(F)||(F=[F]),F.length===0)return A(function(){L.drain()});U=U||0;for(var Z=L._tasks.head;Z&&U>=Z.priority;)Z=Z.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Z?L._tasks.insertBefore(Z,pt):L._tasks.push(pt)}A(L.process)},delete L.unshift,L};function kl(k,T){if(T=Br(T||Nt),!Ae(k))return T(new TypeError("First argument to race must be an array of functions"));if(!k.length)return T();for(var L=0,F=k.length;L<F;L++)M(k[L])(T)}function gi(k,T,L,F){var U=o(k).reverse();Yo(U,T,L,F)}function Wt(k){var T=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function _1(k){var T;return Ae(k)?T=si(k,Wt):(T={},ls(k,function(L,F){T[F]=Wt.call(this,L)})),T}function yd(k,T,L,F){Kc(k,T,function(U,j){L(U,function(Z,J){j(Z,!J)})},F)}var wl=Zo(yd),kd=ii(yd),F1=He(kd,1);function P1(k){return function(){return k}}function pi(k,T,L){var F=5,U=0,j={times:F,intervalFunc:P1(U)};function Z(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:P1(+At.interval||U),ct.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")ct.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=T||Nt,T=k):(Z(j,k),L=L||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=M(T),lt=1;function pt(){J(function(ct){ct&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):L.apply(null,arguments)})}pt()}var Ko=function(k,T){T||(T=k,k=null);var L=M(T);return i(function(F,U){function j(Z){L.apply(null,F.concat(Z))}k?pi(k,j,U):pi(j,U)})};function Bl(k,T){bd(cs,k,T)}var El=Zo(ai(Boolean,pl)),Tr=ii(ai(Boolean,pl)),xl=He(Tr,1);function wd(k,T,L){var F=M(T);jc(k,function(j,Z){F(j,function(J,lt){if(J)return Z(J);Z(null,{value:j,criteria:lt})})},function(j,Z){if(j)return L(j);L(null,si(Z.sort(U),R1("value")))});function U(j,Z){var J=j.criteria,lt=Z.criteria;return J<lt?-1:J>lt?1:0}}function Il(k,T,L){var F=M(k);return i(function(U,j){var Z=!1,J;function lt(){var pt=k.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",L&&(ct.info=L),Z=!0,j(ct)}U.push(function(){Z||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var N1=Math.ceil,Tl=Math.max;function Ci(k,T,L,F){for(var U=-1,j=Tl(N1((T-k)/(L||1)),0),Z=Array(j);j--;)Z[F?j:++U]=k,k+=L;return Z}function Ai(k,T,L,F){var U=M(L);xr(Ci(0,k,1),T,U,F)}var $1=He(Ai,1/0),H1=He(Ai,1);function j1(k,T,L,F){arguments.length<=3&&(F=L,L=T,T=Ae(k)?[]:{}),F=Br(F||Nt);var U=M(L);Go(k,function(j,Z,J){U(T,j,Z,J)},function(j){F(j,T)})}function Dl(k,T){var L=null,F;T=T||Nt,di(k,function(U,j){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,j(!Z)})},function(){T(L,F)})}function Sl(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Ll(k,T,L){L=Ao(L||Nt);var F=M(T);if(!k())return L(null);var U=function(j){if(j)return L(j);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function U1(k,T,L){Ll(function(){return!k.apply(this,arguments)},T,L)}var Bd=function(k,T){if(T=Br(T||Nt),!Ae(k))return T(new Error("First argument to waterfall must be an array of functions"));if(!k.length)return T();var L=0;function F(j){var Z=M(k[L++]);j.push(Ao(U)),Z.apply(null,j)}function U(j){if(j||L===k.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},J3={apply:r,applyEach:Xu,applyEachSeries:ed,asyncify:v,auto:Uc,autoInject:I1,cargo:ci,compose:qc,concat:T1,concatLimit:gl,concatSeries:Gc,constant:Zc,detect:as,detectLimit:Jo,detectSeries:Cl,dir:D1,doDuring:S1,doUntil:L1,doWhilst:Ad,during:M1,each:Qc,eachLimit:Al,eachOf:Go,eachOfLimit:Er,eachOfSeries:cs,eachSeries:di,ensureAsync:Yc,every:hi,everyLimit:bl,everySeries:Jc,filter:Xc,filterLimit:vl,filterSeries:ta,forever:O1,groupBy:fi,groupByLimit:ea,groupBySeries:N,log:G,map:jc,mapLimit:xr,mapSeries:td,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:we,nextTick:na,parallel:kn,parallelLimit:yl,priorityQueue:mi,queue:vd,race:kl,reduce:Yo,reduceRight:gi,reflect:Wt,reflectAll:_1,reject:wl,rejectLimit:kd,rejectSeries:F1,retry:pi,retryable:Ko,seq:Wc,series:Bl,setImmediate:A,some:El,someLimit:Tr,someSeries:xl,sortBy:wd,timeout:Il,times:$1,timesLimit:Ai,timesSeries:H1,transform:j1,tryEach:Dl,unmemoize:Sl,until:U1,waterfall:Bd,whilst:Ll,all:hi,allLimit:bl,allSeries:Jc,any:El,anyLimit:Tr,anySeries:xl,find:as,findLimit:Jo,findSeries:Cl,forEach:Qc,forEachSeries:di,forEachLimit:Al,forEachOf:Go,forEachOfSeries:cs,forEachOfLimit:Er,inject:Yo,foldl:Yo,foldr:gi,select:Xc,selectLimit:vl,selectSeries:ta,wrapSync:v};e.default=J3,e.apply=r,e.applyEach=Xu,e.applyEachSeries=ed,e.asyncify=v,e.auto=Uc,e.autoInject=I1,e.cargo=ci,e.compose=qc,e.concat=T1,e.concatLimit=gl,e.concatSeries=Gc,e.constant=Zc,e.detect=as,e.detectLimit=Jo,e.detectSeries=Cl,e.dir=D1,e.doDuring=S1,e.doUntil=L1,e.doWhilst=Ad,e.during=M1,e.each=Qc,e.eachLimit=Al,e.eachOf=Go,e.eachOfLimit=Er,e.eachOfSeries=cs,e.eachSeries=di,e.ensureAsync=Yc,e.every=hi,e.everyLimit=bl,e.everySeries=Jc,e.filter=Xc,e.filterLimit=vl,e.filterSeries=ta,e.forever=O1,e.groupBy=fi,e.groupByLimit=ea,e.groupBySeries=N,e.log=G,e.map=jc,e.mapLimit=xr,e.mapSeries=td,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=we,e.nextTick=na,e.parallel=kn,e.parallelLimit=yl,e.priorityQueue=mi,e.queue=vd,e.race=kl,e.reduce=Yo,e.reduceRight=gi,e.reflect=Wt,e.reflectAll=_1,e.reject=wl,e.rejectLimit=kd,e.rejectSeries=F1,e.retry=pi,e.retryable=Ko,e.seq=Wc,e.series=Bl,e.setImmediate=A,e.some=El,e.someLimit=Tr,e.someSeries=xl,e.sortBy=wd,e.timeout=Il,e.times=$1,e.timesLimit=Ai,e.timesSeries=H1,e.transform=j1,e.tryEach=Dl,e.unmemoize=Sl,e.until=U1,e.waterfall=Bd,e.whilst=Ll,e.all=hi,e.allLimit=bl,e.allSeries=Jc,e.any=El,e.anyLimit=Tr,e.anySeries=xl,e.find=as,e.findLimit=Jo,e.findSeries=Cl,e.forEach=Qc,e.forEachSeries=di,e.forEachLimit=Al,e.forEachOf=Go,e.forEachOfSeries=cs,e.forEachOfLimit=Er,e.inject=Yo,e.foldl=Yo,e.foldr=gi,e.select=Xc,e.selectLimit=vl,e.selectSeries=ta,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(lp,lp.exports);var Eb={exports:{}},cp=Eb.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)?cp(n,t):i};cp.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=cp(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 xb=$i,vS=wb,yS=Bb,zh=No,ap=lp.exports,kS=Eb.exports,Ib=Us.ACTIONS,Tb=Re;function Re(n,t){if(xb.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}xb.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||kS();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);ap.parallel([function(i){ap.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();ap.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?Ib.presenceSubscribe:Ib.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=zh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=zh.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 zh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new vS(this,n)},Re.prototype._createRemotePresence=function(n){return new yS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=zh.callEach(n,t);!e&&t&&this.emit("error",t)};var Wa=wb,Db=Nh,wS=No,Sb=Db.CODES,BS=Ho;function Ho(n,t){Wa.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()}Ho.prototype=Object.create(Wa.prototype),Ho.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Sb.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,Wa.prototype.submit.call(this,n,t)},Ho.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),Wa.prototype.destroy.call(this,n)},Ho.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Ho.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},Ho.prototype._transformAgainstOp=function(n,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)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.prototype._message=function(){var n=Wa.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Ho.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!wS.supportsPresence(o))throw new Db(Sb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Lb={};(function(n){var t=Ua,e=Nh,o=No,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(A){return A}}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 A=n.apply(l,p);if(A)return A}},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(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}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 A=d[p];typeof A.lm=="string"&&(A.lm=+A.lm);for(var v=A.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,[A]))}}}}})(Lb);var qa=Bb,ES=Lb,xS=ao;function ao(n,t){qa.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()}ao.prototype=Object.create(qa.prototype),ao.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ao.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),qa.prototype.destroy.call(this,n)},ao.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)},ao.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))}})}},ao.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},qa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},qa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ao.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)}},ao.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++):ES.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ao.prototype._startCachingOps=function(){this._opCache=[]},ao.prototype._stopCachingOps=function(){this._opCache=null},ao.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Mb=Tb,IS=BS,TS=xS;function Xl(n,t,e){var o=Xl.channel(t,e);Mb.call(this,n,o),this.collection=t,this.id=e}var DS=Xl;Xl.prototype=Object.create(Mb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new IS(this,n)},Xl.prototype._createRemotePresence=function(n){return new TS(this,n)};var SS=LS;function LS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var MS=SS,Rb=$i,Ob=Ga;function Ga(n,t,e,o,r){if(Rb.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}Rb.mixin(Ga),Ga.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ga.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ga.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new MS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var _b=Ob,RS=No,OS=Us.ACTIONS,_S=up;function up(n,t,e,o,r,i){if(_b.call(this,n,t,e,o,i),!RS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}up.prototype=Object.create(_b.prototype),up.prototype._message=function(){return{a:OS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Fb=Ob,FS=No,PS=Us.ACTIONS,NS=dp;function dp(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!FS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}dp.prototype=Object.create(Fb.prototype),dp.prototype._message=function(){return{a:PS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var $S=dS,HS=pS,jS=Tb,Pb=DS,US=_S,zS=NS,Nb=$i,tc=Nh,ee=Us.ACTIONS,$b=Ua,jo=No,Za=mb,Qa=tc.CODES;function Hb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var VS=wt;function wt(n){Nb.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=Hb(n),this.bindToSocket(n)}Nb.mixin(wt),wt.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=Hb(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{Za.warn("Failed to parse message",o);return}e.debug&&Za.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){jo.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)}},wt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=jb(n.error,n),delete n.error),n.a){case ee.initLegacy:return this._handleLegacyInit(n);case ee.handshake:return this._handleHandshake(t,n);case ee.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ee.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ee.queryUnsubscribe:return;case ee.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 ee.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ee.bulkSubscribe:case ee.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ee.snapshotFetch:case ee.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ee.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ee.subscribe:case ee.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ee.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ee.presence:return this._handlePresence(t,n);case ee.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ee.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ee.presenceRequest:return this._handlePresenceRequest(t,n);case ee.pingPong:return this._handlePingPong(t);default:Za.warn("Ignoring unrecognized message",n)}};function jb(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}wt.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](jb(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 Za.error("Invalid bulk message",t)},wt.prototype._reset=function(){this.agent=null},wt.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(Qa.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)}},wt.prototype.startBulk=function(){this.bulk||(this.bulk={})},wt.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},wt.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})}},wt.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)}},wt.prototype.sendFetch=function(n){return this._sendActions(ee.fetch,n,n.version)},wt.prototype.sendSubscribe=function(n){return this._sendActions(ee.subscribe,n,n.version)},wt.prototype.sendUnsubscribe=function(n){return this._sendActions(ee.unsubscribe,n)},wt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ee.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)},wt.prototype.send=function(n){this.debug&&Za.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},wt.prototype.ping=function(){if(!this.canSend)throw new tc(Qa.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ee.pingPong};this.send(n)},wt.prototype.close=function(){this.socket.close()},wt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},wt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new $S(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},wt.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},wt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},wt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new HS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},wt.prototype._destroyQuery=function(n){delete this.queries[n.id]},wt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ee.queryFetch,n,t,e,o)},wt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ee.querySubscribe,n,t,e,o)},wt.prototype.hasPending=function(){return!!(this._firstDoc(Vh)||this._firstQuery(Vh)||this._firstSnapshotRequest())};function Vh(n){return n.hasPending()}wt.prototype.hasWritePending=function(){return!!this._firstDoc(WS)};function WS(n){return n.hasWritePending()}wt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Vh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Vh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},wt.prototype._nothingPendingRetry=function(n){var t=this;return function(){jo.nextTick(function(){t.whenNothingPending(n)})}},wt.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}}},wt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},wt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},wt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new US(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new zS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},wt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},wt.prototype._initializeHandshake=function(){this.send({a:ee.handshake,id:this.id})},wt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},wt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},wt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Qa.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if($b.map[n.type]!==$b.defaultType)return this.emit("error",new tc(Qa.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Qa.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},wt.prototype.getPresence=function(n){var t=this,e=jo.digOrCreate(this._presences,n,function(){return new jS(t,n)});return e._wantsDestroy=!1,e},wt.prototype.getDocPresence=function(n,t){var e=Pb.channel(n,t),o=this,r=jo.digOrCreate(this._presences,e,function(){return new Pb(o,n,t)});return r._wantsDestroy=!1,r},wt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},wt.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},wt.prototype._handlePresenceSubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},wt.prototype._handlePresenceUnsubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},wt.prototype._handlePresence=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},wt.prototype._handlePresenceRequest=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Ub=VS,qS=Ua;const Wh={err:1001,msg:"user auth error",name:"AuthError"},GS={err:1002,msg:"you don't have required permission",name:"PermissionError"},hp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ya={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},ZS={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"},Ja="x-live-editor-token",qh="x-live-editor-base-url",pn=S("auth-connection");function YS(n){try{n()}catch(t){pn.error(t)}}class JS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new V5.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 Si(this.getBaseURL())}async auth(t){g(pn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Ja]:t.token,[qh]: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:{[qh]:Si(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new WB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Ub.prototype),g(pn,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}}},Ub.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,pn.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){pn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else pn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Wh.msg);t.code=Wh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ya.msg);t.code=Ya.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===Wh.err)pn.warn("auth error"),this.handleAuthError();else if(o===hp.err)pn.warn(hp.msg),this.emitMaxUsersError();else if(o===Ya.err){pn.warn(Ya.msg);try{this.emitRequestReloadError()}catch(r){pn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else pn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(pn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(pn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(pn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(pn,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(),YS(()=>{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 KS(){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}KS();async function XS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new qB.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 Si(i)}const dr=S("sharedb-doc/client");class tL{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(dr,!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),dr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;qS.register(_d.type),this.connection=new JS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(dr,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,{[Ja]: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=>{dr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await XS(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 A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return dr.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(dr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Ja]:this.connection.token},e,o);return g(dr,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(dr,o,"no token"),a.headers={...a.headers,[Ja]:o,[qh]:this.connection.getBase64BaseURL()};try{return await zB.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(dr,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=VB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(dr,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/${Si(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 eL(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const fp=S("block-ids");class nL{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(fp,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(fp,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 oL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new nL,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(fp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class zb{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 Gh=S("op-parse-handler");class rL{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 oL,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&&(Gh.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)){Gh.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 zb,o.set(d,h)),h.delete(l.key)}else g(Gh,!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 zb,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);Gh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Oe=S("op-parser");class Vb{}class mp{constructor(t){m(this,"key");this.key=t}}function iL(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 gp(n,t,e,o){if(e==="upsert"&&iL(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 mp(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 Vb),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 mp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Vb?o.onDeleteBlock(n,i):l instanceof mp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function sL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function lL(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 pp(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{pp(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){sL(n);return}if(r==="comments"){lL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{gp(i,s,t,e)}):n.slice(1).forEach(s=>{gp(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)}`),gp(i,n.slice(1),t,e)}function Wb(n,t,e){const o=new rL(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=>{pp(a,i,o)}):pp(s,i,o)}o.end()}const cL=S("sharedb-comments");function Cp(n){const t=n.blocks;g(cL,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 qb(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 Ap(n,t){const e=qD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ae=S("sharedb-doc/doc-container"),Gb="ot-json1";_d.type.registerSubtype(GD.type),_d.type.name=Gb,_d.type.invert=null;class Ka extends ha{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new VD);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(!aa.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){ae.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ae.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ae.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ae.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,Gb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainer",async(e,o)=>{const r=[Ni(e),{i:o}];return this.submitOp(r)});m(this,"submitDeleteChildContainer",async e=>{const o=[Ni(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Ni(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Ni(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=[Ni(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=[Ni(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ae.warn("handleOp: destroyed");return}Wb(e,this,!!o)});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(ae,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new tL(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new Ka(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||eL())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ae.error(o),ae.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 ja(this.data())}getContainerBlocks(e){const o=this.data();g(ae,o,"no doc data");const r=o[Ni(e)];return g(ae,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(ae,r,"no doc data");const i=r[Ni(e)];g(ae,i,`no container data: ${e}`);const s=i[o];return g(ae,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(ae,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(ae,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>qb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Cp(o)}localCreateComment(e,o){const r=Ap(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=Ap(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(ae,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(ae,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(ae,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(ae,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(ae,this.callbacks.length>0,"no callbacks"),g(ae,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(ae,this.callbacks.length>0,"no callbacks"),g(ae,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(ae,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(ae,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(ae,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 ja(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ja(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:ja(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:ja(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){Wb(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 Zb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Se.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 Qb=S("remote-cursor-decorator");class bp{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(Qb,typeof s=="string","invalid path containerId"),g(Qb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,A)=>{A>d&&(A=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(A);B?B.push(...v):i.set(A,v)}),{insertions:i}}}class Yb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Xt(jr(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 aL(n,t){n.addCustom("child-block-tracker",()=>new Yb(n)).addListener("change",t)}function uL(n,t){n.addCustom("child-block-tracker",()=>new Yb(n)).removeListener("change",t)}const dnt="",dL={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"}},hL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},fL={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"}};R.mergeLang({"zh-CN":dL,"en-US":hL,"js-JP":fL});const hnt="";S("button");function uo(n,t,e,o,r){const i=w("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}function Jb(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const fnt="",ec=S("ui-command-bar-base"),mL={itemElementTag:"div",tippyArrow:!1},Y2=class extends ve.TypedEmitter{constructor(e,o,r){var i,s;super();m(this,"content");m(this,"items");m(this,"subBar",null);m(this,"parentItem",null);m(this,"closeable",null);m(this,"closeReason",null);m(this,"options");m(this,"id");m(this,"header",null);m(this,"footer",null);m(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing&&!Ss(e.target)){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close("cancelBar");return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(e.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});m(this,"handleDocumentMouseDown",e=>{if(e.target instanceof Element&&!this.isInCommandBar(e.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,e)===!1)return;this.close("clickBackground")}});m(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),wC(this.id)});m(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&W(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&kC(this.id)});m(this,"lastEnterPauseTime",0);m(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});m(this,"handleItemMouseEnter",e=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});m(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(ot(o,"selected"),this.emit("selectionChange",this,""))});m(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close("clickItem"))}});m(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=ro(r);if(!Kt(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:K(),this.options={...mL,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(e){this.closeReason=e,this.subBar&&this.subBar.close(e),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r,i;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=e==null?void 0:e.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),e}destroy(){var e;this.close(null),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.findIndex(s=>{var l,a;return s.id===((a=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:a.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(e){let o=e+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&ot(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&ot(s,"selected")}const r=this.getItemElementById(e);r?(W(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=Y2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(a,d,h)=>{this.emit("click",a,d,h)}),this.subBar.on("close",()=>{var a;(a=this.subBar)==null||a.destroy(),this.subBar=null,ot(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Kt(o,e)||Kt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=w(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(a=e.states)!=null&&a.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return g(ec,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return g(ec,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(ec,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(ec,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(xt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=w("div",["editor-command-bar-root"],null);if(this.options.header){const i=w("div",["editor-command-bar-header"],null);if(this.options.header instanceof Function){const s=this.options.header();s&&i.appendChild(s)}else i.appendChild(this.options.header);this.header=i,this.header&&o.appendChild(this.header)}const r=w("div",["editor-command-bar"],o);if(e.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.options.footer){const i=w("div",["menu-item","editor-command-bar","footer"],null);if(this.options.footer instanceof Function){const s=this.options.footer();s&&i.appendChild(s)}else i.appendChild(this.options.footer);this.footer=i,this.footer&&o.appendChild(this.footer)}return(this.options.header||this.options.footer)&&W(o,"scrollable-bar"),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;g(ec,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(ec,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let ji=Y2;m(ji,"commandBarCreators",new Map),S("ui-command-bar");class Zh extends ji{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=GB.default(e,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(e){var o;super.close(e),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const Kb=S("ui-base");class Xa extends Zh{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${K()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){W(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(Kb,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(Kb,e,"no item element"),e}}const Ui=S("filterable-list");function Xb(n){var e,o;const t=w("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(w("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&W(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(t,"disabled"),t}function tv(n){const t=w("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Xb(e))}),n.length||t.appendChild(Xb({id:"placeholder",states:["disabled"],name:R.t("search.emptyTips")})),t}function ev(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function gL(n,t){const e=w("div",["filterable-list"],null),o=w("div",["filter"],e),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=w("div",["list"],e),l=tv(ev(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function nv(n,t,e){const o=n.querySelector(".list");g(Ui,o,"no list root");const r=tv(ev(t,e)),i=o.querySelector(".list-root");if(g(Ui,i,"no exists menu"),Ca(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(Ui,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class pL{constructor(t,e){m(this,"root");m(this,"visibleItems");m(this,"selectedId");m(this,"filter","");m(this,"onSelected",null);m(this,"handleKeydown",t=>{this.processKeyDown(t)});m(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");g(Ui,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});m(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=gL(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,nv(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),nv(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(a=>a.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(t){var e;if(t.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class CL extends pL{constructor(e,o,r){super(e,r);m(this,"popup");m(this,"onShow",null);m(this,"onHide",null);m(this,"custom",null);m(this,"handleShow",()=>{this.onShow&&this.onShow(this)});m(this,"handleHide",()=>{this.onHide&&this.onHide(this)});m(this,"handleShown",()=>{this.focus()});this.popup=new Xa(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close("cancelBar")}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const mnt="",gnt="";function AL(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const ov=`<?xml version="1.0" ?>
|
|
27
|
+
`)}const lT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof je||g(lT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=nt(r),l=at(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=ze(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function cT(n,t,e){const o=nt(t),r=at(o),i=bt(t);return Ig(n,r,i,e)}function S6(n,t,e,o,r){const i=nt(t),s=at(i),l=bt(t),a=cT(n,t,e),d=uh(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),gn(n,t)}function L6(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=uh(e," ",o);return n.doc.localUpdateBlockText(i,s,l),gn(n,t)}function aT(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+dh(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")&&(aT(i.text,r)||delete s.link);const l=uh(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),gn(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 kh=S("update-composition-text");function M6(n){const t=n.selection.range.start;t instanceof je||g(kh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(kh,tt(n,o),"not a text kind block");const r=nt(o),i=at(r),s=bt(o),l=n.doc.getBlockData(i,s);g(kh,l,"no block data in doc"),g(kh,l.text,"no text data in text block");const a=Lt(o);sh(n,Li(o),e,a,l.text)}function R6(n){Hx(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ra=S("delete-block-text");function Sg(n,t,e,o,r){if(!n.isBlockWritable(t))return Ra.error("block is not writable"),0;g(Ra,tt(n,t),"block is not a text kind block");const i=nt(t),s=at(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Ra,a,"no block data in doc"),g(Ra,a.text,"no text data in text block");let d=e;sn(t,e)||(d=Ri(t,d));let h=e+o;g(Ra,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=Fs(t,h));const p=h-d,A=z4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Lg=S("break-text-block");function O6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Lg,tt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Lg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=nt(t),i=at(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?O6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...lr(""),...l,...o==null?void 0:o.newBlockData},D=ye(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=gn(n,t),{right:d}=In(a,e),h=rn(d);h>0&&Sg(n,t,e,h);const p={...lr(d),...l,...o==null?void 0:o.newBlockData},A=Zl(n,i,s+1,p,ye(n,p.id,0));return{block:t,newBlock:A}}const uT=S("prepare-insert-new-block");function dT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=pe(d);return g(uT,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=at(nt(r)),e=bt(r),!tt(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 hT=S("auto-insert-block");function _6(n,t,e,o,r,i){const s=dT(n,e,o);g(hT,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 fT=S("delete-block");function wh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{wh(n,i,e)})}))}function Bh(n,t,e){const o=nt(t),r=at(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(fT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ue(n,{anchor:e.start,focus:e.end})),s}function Mg(n,t,e){return n.undoManager.runInGroup(()=>{const o=nt(t);Io(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Mi(n,e):null;if(!r){const l=n.selection.range;x6(t,l)?r=I6(n,t):r=l}const i=Bh(n,t,r),s=[];return wh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function mT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{wh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function F6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{wh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Rg=S("merge-text-block");function P6(n,t,e){g(Rg,tt(n,t),"only text block can be merged"),g(Rg,tt(n,e),"only text block can be merged");const o=_i(n,t),r=_i(n,e),i=o.text,s=r.text;g(Rg,i&&s,"block data has no text");const l=nt(t),a=at(l),d=bt(t),h=ut(n,t),p=Tg(n,s,a,d,h),A=ye(n,t,rn(i));return Mg(n,e,A),p}const cr=S("clear-selected-contents");function Eh(n,t){g(cr,tt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(cr,e.isSimple(),"not a simple block position"),g(cr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(cr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function N6(n,t,e){const o=at(t),r=pe(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 gT(n,t){const{block:e,start:o,end:r}=t;if(tt(n,e)){Eh(n,t);return}if(Me(e)||o.isSimple()){g(cr,r.isSimple(),"invalid range");const s=nt(e),l=bt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(cr,Mt(n,e),"invalid block kind"),g(cr,!o.isSimple()&&!r.isSimple(),"invalid range"),Rs(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{N6(n,s,{focus:l===0})})}function pT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(cr,e.length>0,"no selected block"),e.length===1){gT(n,e[0]);return}const o=e[0],r=o.block,i=nt(r);g(cr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(tt(n,r)){Eh(n,o);const h=ye(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),tt(n,l)){Eh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(tt(n,l)){Eh(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===Io(i)){N6(n,i,{focus:!0});return}const a=ce(r),d=Zt(l);g(cr,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(),pT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const CT=S("core");function $6(n,t,e){const o=nt(t),r=at(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),gn(n,t)}function H6(n,t,e){if(!n.isBlockWritable(t)){CT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);$6(n,t,r)}function xh(n,t,e){const o=gn(n,t),r=typeof e=="string"?Oi(e):e,i=ln.diff(o,r);return $6(n,t,i)}const Oa=S("update-block-data");function Ih(n,t,e,o){const r=nt(t),i=at(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(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Oa.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(e).forEach(([A,v])=>{g(Oa,A!=="id"&&A!=="type",`invalid block data delta, ${A}`);const B=l[A];if(v==null){B!=null&&(Oa.debug(`delete key: ${A}`),a.delete.push(A));return}B!==v&&(aa.default(B,v)||A==="text"&&ln.diff(B,v).length===0||(d.has(A)?(Oa.debug(`replace key: ${A}`),a.delete.push(A)):Oa.debug(`insert key: ${A}`),a.insert[A]=v))}),n.doc.localUpdateBlockData(i,s,a,o),_i(n,t)}function j6(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=Le(r);_g(n,i,e)}function $s(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 Fi(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"),Fi(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(),A=t.blocks[h];g(_a,Array.isArray(A),"invalid child blocks");const v=A.map(_=>Fi(n,t,_,o)),B=$s(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[A,v]=p;{const B=`${A}/`;if(h.startsWith(B)){const D=h.substring(B.length),x=`${v}/${D}`;return _a.debug(`replace key: ${h} -> ${x}`),x}}{const B=`${A}_`;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 A=d(h);A!==h&&delete l.key,l[A]=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=>Fi(n,t,l,o));return $s(i)}function Pg(n,t,e){const o=t.blocks.root.map(r=>Fi(n.editorBlocks,t,r,e));return mt.default($s(o))}const U6=S("insert-doc");function z6(n,t,e,o,r){if(Mt(n,t)){U6.warn("failed to insert doc into a complex block");return}const i=Pg(n,o,r),s=nt(t),l=bt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,H,z;Object.entries(i.blocks).forEach(([q,rt])=>{q!=="root"&&n.doc.localInsertChildContainer(q,rt)});const d=i.blocks.root;if(Me(t)){n.deleteBlock(t);let q;d.reverse().forEach(rt=>{const ft=n.insertBlock(a,l,rt);q||(q=ft)}),q&&n.selection.selectBlock(q,ut(n,q));return}if(g(U6,tt(n,t),"not a text block"),he(n,t)){const q=a==="root"&&n.getBlockByIndex(a,0)===t,rt=bt(t);let ft;d.forEach((Bt,jt)=>{const Ut=n.insertBlock(a,rt+jt,Bt);jt===d.length-1&&(ft=Ut)}),ft&&n.selection.selectBlock(ft,ut(n,ft)),q&&n.deleteBlock(t);return}if(d.length===1){const q=d[0];if(ya(n,q.type)){n.insertTextToBlock(t,e,(M=q.text)!=null?M:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,q);return}const h=e===ut(n,t),p=e===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(t,e,{forceInsertAfter:!0}):B=t;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ut(n,B))):(n.selection.selectBlock(B,0),ya(n,v.type)?n.insertTextToBlock(B,0,(H=v.text)!=null?H:[]):n.insertBlock(a,D,v));const x=n.selection.range;let _=D;ya(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(t,e,(z=A.text)!=null?z:[]):(n.insertBlock(a,D,A),_+=1),d.slice(1,d.length-1).reverse().forEach(q=>{n.insertBlock(a,_,q)}),n.selection.setRange(x)}),n.doc.endBatchUpdate()}function Ng(n,t,e,o,r){const i=Pg(n,o,r),s=at(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([d,h])=>{d!=="root"&&n.doc.localInsertChildContainer(d,h)}),i.blocks.root.reverse().forEach(d=>{const h=n.insertBlock(s,e,d);l.push(h)})}),l}function V6(n,t,e){const o=Io(t);Ng(n,t,o,e);for(let r=0;r<o;r++){const i=Le(t);n.deleteBlock(i)}}const Fa=S("add-text-attribute");function AT(n,t,e,o){const{start:r,end:i}=e;g(Fa,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Fa,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 W6(n,t,e,o,r){const{start:i,end:s}=e;g(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Fa,o,"invalid attribute name");const l=n.getBlockText(t),a=Ia(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(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=K4(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function q6(n,t,e,o){const r=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!tt(n,s))return;if(he(n,s)){o(n,it(s),t,e);return}const d=Ue(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 G6(n,t,e){const o=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!tt(n,i))return;if(he(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=Ue(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=Ro(n,{simpleBlockOnly:!0}).filter(s=>tt(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 e6(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 Z6(n){const t=[];for(;n;){const e=nt(n);if(t.unshift(e),Xt(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 Q6(n,t){for(;t;){const e=nt(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 bT(n,t){const e=Z6(n),o=Z6(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=Q6(r,n),s=Q6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Y6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=nt(e);g(Wn,Lo(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 Th(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof je&&e instanceof je?{anchor:t,focus:e}:t instanceof Mo&&e instanceof Mo?rh(n,o,t,e):null;const i=nt(o),s=nt(r);if(i===s)return t instanceof Mo&&(t=st(o,0,"home")),e instanceof Mo&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof je,"not valid position type"),g(Wn,e instanceof je,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof je&&e instanceof Mo){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,at(i)),_=fe(D,at(B));return rh(n,D,x,_)}}return null}const l=Hd(o,r)>0,{newBlock1:a,newBlock2:d}=bT(o,r);if(a===d){const B=a,D=Y6(B,o),x=Y6(B,r);return t=fe(a,at(D)),e=fe(a,at(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),rh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof je&&(h=t.offset);let A=l?0:ut(n,d);return d===r&&e instanceof je&&(A=e.offset),t=st(a,h,l?"end":"home"),e=st(d,A,l?"home":"end"),{anchor:t,focus:e}}const vT=S("move-complex-block-position");function yT(n,t,e){const o=n.getBlockById(t.blockId);g(vT,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,at(s)):null}const Pa=S("move-simple-block-position");function J6(n,t){const e=xn(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[0];return Le(o)}function K6(n,t){const e=xn(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qe(o)}function X6(n,t,e){const o=e?J6(n,t):K6(n,t);return Mt(n,o)?X6(n,o,e):o}function kT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?J6(n,e):Ds(e)}function wT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?K6(n,e):Ts(e)}function Hg(n){return n==="ArrowLeft"||n==="ArrowUp"}function jg(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);g(Pa,r,"child container has not parent block"),g(Pa,Mt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?Hg(e)?Qe(i):Le(i):jg(n,r,e)}function BT(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);if(g(Pa,r,"child container has not parent block"),Hg(e)){const l=ce(r);if(l)return l}else{const l=Zt(r);if(l)return l}const i=jg(n,r,e);if(i)return i;let s=r;for(;!Xt(nt(s));)s=et(nt(s));return Hg(e)?ce(s):Zt(s)}function ET(n,t,e){return!Mt(n,t)||zn(n,t).enableKeyboardSelect?t:X6(n,t,e==="ArrowDown"||e==="ArrowRight")}function xT(n,t,e){const o=n.getBlockById(t.blockId),i=Qt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?kT(n,t):wT(n,t);if(s||(s=jg(n,o,e),s||(s=BT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Xt(nt(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(l,0,"home")}return null}if(s=ET(n,s,e),tt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Kx(n,s,o,t,l);if(e==="ArrowUp")return Jx(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 IT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(tt(n,r))return o;const i=Zt(r);if(i)return st(i,0,"home");if(!Xt(nt(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(s,0,"home")}function TT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=IT(n,t,o):r=xT(n,o.getFocusedPos(),t);else if(r=yT(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=Le(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Th(n,o.anchor,r):null}function Pi(n,t,e){const o=TT(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 tA(n){return Pi(n,"ArrowLeft","move"),!0}function eA(n){return Pi(n,"ArrowRight","move"),!0}function nA(n){return Pi(n,"ArrowUp","move"),!0}function oA(n){if(Pi(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=nt(t);if(Xt(e)||Qe(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),Io(o)),!0}function rA(n){return Pi(n,"ArrowDown","select"),!0}function iA(n){return Pi(n,"ArrowLeft","select"),!0}function sA(n){return Pi(n,"ArrowRight","select"),!0}function lA(n){return Pi(n,"ArrowUp","select"),!0}const cA=S("word-offset");function Ug(n,t){const e=n.selection.range.focus;g(cA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"home");if(e.offset===0||!tt(n,o)){const s=ce(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&tt(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(cA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!tt(n,o)){const s=Zt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&tt(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 aA(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 uA(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 dA(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 hA(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=pe(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=pe(o),i=r[r.length-1];return Wg(n,i)}function fA(n){const t=Wg(n,Qe(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function mA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function gA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function qg(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 pA=S("line-offset");function CA(n){const t=n.selection.range.focus;g(pA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!tt(n,e))return st(e,0,"home");let r=N4(e,t).start;const{next:i}=th(e,r);return i&&so(i)&&va(i)==="br"&&(r+=1),st(e,r,"home")}function AA(n){const t=n.selection.range.focus;g(pA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!tt(n,e))return st(e,ut(n,e),"end");const o=N4(e,t);return st(e,o.end,"end")}function bA(n){if(!n.selection.range.focus.isSimple())return!1;const e=CA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function vA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=CA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const wA=S("find-block-position");function DT(n,t,e,o){g(wA,Mt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(wA,r.length>0,"complex block has not any child container");const i=So(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=I4(n,t,s,l);return Gg(n,a,e,o)}function Gg(n,t,e,o){if(Mt(n,t))return DT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=So(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 A=st(r,p,"normal"),v=So(n,t,A),B=nr(v,l,a);B<i&&(i=B,d=A)}return d}const BA=S("page-offset");function ST(n,t){const e=w6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<XI(n))return n.getFirstBlock();const i=ce(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ce(s)}return n.getFirstBlock()}function LT(n,t){const e=w6(n)*.9,o=t.getBoundingClientRect(),r=tT(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Zt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Zt(l)}return n.getLastBlock()}function EA(n){const t=n.selection.range.focus;g(BA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ST(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Gg(n,o,e,t),r}function xA(n){const t=n.selection.range.focus;g(BA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=LT(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Gg(n,o,e,t),r}function IA(n){if(!n.selection.range.focus.isSimple())return!1;const e=EA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function TA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=EA(n);if(!e)return!1;const o=Th(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 SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);if(!e)return!1;const o=Th(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 Na=S("select-all");function LA(n,t){const e=Le(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 MT(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===at(r)&&t.end.blockId===s&&t.end.childContainerId===at(i)}function RT(n,t){g(Na,t,"no parent block"),g(Na,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(Ue(n,{anchor:fe(t,at(o)),focus:fe(t,at(r))}))}function MA(n,t){const e=nt(t);Zg(n,e)}function RA(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&tt(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"),MA(n,Le(n.rootContainer)),!1}return g(Na,!e.isSimple(),"invalid range type"),MT(t,e)?(MA(n,t),!1):(g(Na,t,"no parent block"),g(Na,Mt(n,t),"not a complex block"),RT(n,t),!0)}function Zg(n,t){const e=pe(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 OA(n){qg(n),n.focus()}const Qg=S("selected-block-to-doc");function _A(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{_A(n,i,e)}),e.blocks[o]=mt.default(r)})}function Dh(n,t){const e=Qt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(_i(n,t.block));if(tt(n,t.block)){const i=t.start,s=t.end;if(g(Qg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=ze(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Me(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Qg,Mt(n,t.block),"not complex block"),g(Qg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return _A(n,o,r),r}function Yg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Dh(n,{block:t,start:e,end:o})}const OT=S("block-to-doc");function _T(n,t){g(OT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Yg(n,o));return $s(e)}function Sh(n){const e=n.selection.range.getSelectedBlocks().map(o=>Dh(n,o));return $s(e)}function FA(n,t){const e=n.getContainerById(t),i=pe(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Dh(n,s));return $s(i)}const Lh=S("editor-selection");class FT{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(x6(e,i)){Lh.debug("adjust selection because remote deleted current block");const s=I6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new YI(t);const r=st(o,0,"normal");this._range=Ue(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=Ue(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()||!rT(this.editor,r))&&ot(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(),JI(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(!Ur(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=So(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){oT(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Lh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Lh,!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")&&(ot(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=Sh(this.editor);return t==="text"?La(this.editor,e):t==="markdown"?Ma(this.editor,e):D6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{ot(t,"focused"),ot(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=nt(t);for(;Lo(e);){const o=et(e);g(Lh,o,"parent block not found"),W(o,"child-focused"),e=nt(o)}return!0}}function PT(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 NT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!tt(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=S4(this.editor,t.x,t.y);if(o){if(o instanceof rr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=ro(s[0].block);this.autoScroll=new Zd({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=ih(this.editor,t.x,t.y);if(!e)return;const o=Th(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){NT(this.editor)}handleTripleClick(t){PT(this.editor)}}function HT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function jT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const PA=S("delete-text");function NA(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof je||g(PA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(PA,tt(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=Ri(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 $A(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const UT=S("handle-backspace");function Jg(n,t){if(!he(n,t))return;const e=nt(t);Io(e)!==1&&n.deleteBlock(t)}function zT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===0){if($A(n,o))return;const r=ce(o);if(r){if(!n.isBlockWritable(r))return;if(tt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Jg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Jg(n,o),g(UT,Me(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=nt(o);if(Lo(i)){const s=B4(n,i);if(s){if(!n.isBlockWritable(s))return;Jg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else NA(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function VT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===ut(n,o)){const r=Zt(o);if(r){if(!n.isBlockWritable(r))return;tt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):he(n,o)?n.deleteBlock(o,ye(n,r,0)):n.deleteBlock(r)}}else NA(n,"forward",1,null);else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function WT(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(Ur(e))return!0;const s=Rs(n,r,e,o),l=xn(n,r);return s.length===l.length}function qT(n,t){if(WT(n)){const o=n.getFocusedBlock(),r=bt(o),i=at(nt(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(tt(n,e)){if(he(n,e)&&$A(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function GT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!tt(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 ZT=S("input-handler-actions");function QT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(qT(n),!0))}function YT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(VT(n),!0))}function JT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function KT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(GT(n),!0))}function XT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{ZT.error(t)}),!0)}const Mh={ArrowDown:oA,ArrowUp:nA,ArrowLeft:tA,ArrowRight:eA,"Shift+ArrowDown":rA,"Shift+ArrowUp":lA,"Shift+ArrowLeft":iA,"Shift+ArrowRight":sA,"CtrlOrCmd+ArrowLeft":aA,"CtrlOrCmd+ArrowRight":uA,"CtrlOrCmd+Shift+ArrowLeft":dA,"CtrlOrCmd+Shift+ArrowRight":hA,"CtrlOrCmd+ArrowUp":mA,"CtrlOrCmd+ArrowDown":fA,"CtrlOrCmd+Shift+ArrowUp":gA,"CtrlOrCmd+Shift+ArrowDown":qg,"CtrlOrCmd+A":RA,Home:yA,End:kA,"Shift+Home":bA,"Shift+End":vA,PageUp:IA,PageDown:TA,"Shift+PageUp":DA,"Shift+PageDown":SA,"CtrlOrCmd+Z":HT,"CtrlOrCmd+Shift+Z":jT,Enter:QT,Delete:YT,Backspace:JT,"Shift+Enter":KT,"CtrlOrCmd+Shift+V":XT};function HA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function jA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(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=>{jA(n,l,e)})})}function UA(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):jA(t,r,e)})}async function tD(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 eD(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 nD(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(eD(n,t)){const s=Array.from(Object.keys(o));r=await tD(n,s),UA(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&&UA(n,t,i)}async function oD(n,t,e){await nD(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Me(i)){const s=nt(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 rD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function iD(n){let t;for(const e of rD)if(t=n[e],t)break;return t||null}function zA(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=>{zA(n,l,e)})})}function sD(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)}):zA(t,r,e)}),Array.from(e)}function Rh(n,t){return Ze.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Si(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::${Si(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Oh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=sD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function lD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Sh(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Oh(n,o);const i=yh(n,o),s=Ma(n,o),l=Rh(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 _h(n,t){const e=Yg(n,t);Oh(n,e);const o=yh(n,e),r=Ma(n,e),i=Rh(o,e);return Lm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class cD{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(!tt(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){lD(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;Me(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(){ot(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 HA(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 oD(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=iD(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 aD(n,t,e){const o=Fr(t,e);return o.remove(),o}S("copy-dom-attributes");const VA=["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 uD(n,t){for(let l=0;l<VA.length;l++){const a=VA[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 WA(n){const t=Array.from(n.childNodes).filter(e=>!$C(e));return t.forEach(e=>{e.remove()}),t}function qA(n,t,e){var d;const o=n.getContainerById(t),r=Fr(o,e),i=Li(r),s=n.doc.getBlockData(t,e),l=Qt(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=WA(h);WA(r),p.forEach(v=>{r.appendChild(v)});const A=Kd(h);if(A){const v=Kd(r);v&&v.remove(),r.appendChild(A)}uD(h,r)}o4(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 dD=S("transform-selection");function GA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(dD,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 Ue(n,{anchor:l,focus:a})}const hD=S("handle-block-text-changed");function fD(n,t,e,o,r){const i=n.getContainerById(t),s=Fr(i,e),l=n.doc.getBlockData(t,e);if(g(hD,l.text,"no block text"),JC(n,s).setBlockText(n,s,l.text),!r){const a=GA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function mD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function ZA(n,t,e,o){const r=Qt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function gD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{ZA(n,i,o,{child:!0})}),ZA(n,r,o,{child:!1})}const _o=S("editor-doc");class pD extends ha{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(_o,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(_o,l,`no text, ${e}, ${o}`);const a=GA(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(_o,!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(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(mD(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(Mi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(_o,!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 this.editor.selection.setRange(Mi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(_o,!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(Mi(this.editor,r)),s}localDeleteChildContainers(e){return g(_o,!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)}localInsertChildContainer(e,o){return g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,mt.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){_o.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)}),fD(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)}),qA(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);ox(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){gD(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);aD(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){_o.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function QA(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 Kg=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(Kg,t,"no other action"),!1}combine(t){g(Kg,!1,"no other")}setAfterRange(t){this.afterRange&&Kg.warn("after range has already set"),this.afterRange=t}}const CD=S("block-action");class YA 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(CD,this.blockIndex===bt(i),"invalid block index"),Bh(e,i,Mi(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}class AD extends YA{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class bD extends YA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class vD extends Jl{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){QA(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 Hs=S("update-block-data-action");class Fh 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(Hs,this.blockId===i.id,"invalid block id"),g(Hs,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hs,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Ih(e,o,Fh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Ih(e,o,Fh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const Xg=S("update-block-text-action");class $a 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=$a.calType(i,s)}static calType(e,o){g(Xg,e,"no old data"),g(Xg,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>mC(h)?`cjk_${h}`:hC(h)?"number":Ud(h)?"space":fC(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?(xh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(xh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof $a)||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(Xg,e instanceof $a,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class JA 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.localInsertChildContainer(this.containerId,mt.default(this.blocks)),!0}}class yD extends JA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class kD extends JA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Fo=S("undo");class wD{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):(QA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new vD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Fo.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(Mi(this.editor,t.beforeRange))}catch(e){Fo.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(Mi(this.editor,e)):Fo.warn("no after range")}catch(e){Fo.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 $a(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Fh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,e>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new AD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new bD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new yD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new kD(this.editor,t,e)))}}class BD{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 ED{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new BD)}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 xD{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||!Kt(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&&Kt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&ot(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(!tt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:Nm(o)}}const KA="style-color-",XA="style-bg-color-";class ID{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(KA)?i["data-style-color"]=l.substring(KA.length):l.startsWith(XA)?i["data-style-bg-color"]=l.substring(XA.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 TD(n){n.editorBlocks.registerBlockClass(Tn),n.editorBlocks.registerBlockClass(w4),n.editorBoxes.registerBoxClass(h6),n.editorBoxes.registerBoxClass(f6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(C6),n.editorInsertions.registerInsertionClass(A6),n.editorBlockRenders.registerRender(new ID)}function DD(n,t){TD(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 tb=S("range-commands");function eb(n,t){n.forEach(e=>{e.source=t,e.children&&eb(e.children,t)})}function nb(n,t,e){const o=it(t);g(tb,o===e.start.blockId,"invalid start range"),g(tb,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);eb(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)&&Rs(n,t,e.start,e.end).forEach(l=>{pe(l).forEach(d=>{const h=ut(n,d),p=Ue(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),A=nb(n,d,p);i.push(...A)})}),i}function ob(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ue(t,{anchor:r.start,focus:r.end});nb(t,r.block,i).forEach(l=>{o.push(l)})}),o}function rb(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.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)&&Rs(n,t,e.start,e.end).forEach(A=>{pe(A).forEach(B=>{const D=ut(n,B),x=Ue(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});rb(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function ib(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=Ue(o,{anchor:l.start,focus:l.end});rb(o,l.block,a,t,e,r)}),r}const SD=S("command-providers");class sb{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(SD,e,`no command provider, id=${t}`),e}getCommands(t){return ob(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>ib(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 LD(n,t){const e=nt(t),o=at(e),r=bt(t);qA(n,o,r)}const MD=S("table-scroll");class lb{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 RD{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)){MD.warn(`event has already registered: ${e}`);return}i.push(new lb(this.editor,t,e,o,r))}else{const s=new lb(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 cb=S("update-block-text");function OD(n,t){const e=n.getBoxById(t.id),o=et(e);g(cb,o,"no parent block"),g(cb,tt(n,o),"not a text block");const r=n.getBlockText(o),i=o6(r,"id",t.id,t);H6(n,o,i)}function _D(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 FD(n){return n.readonly?!1:!Ro(n).find(o=>!n.isBlockWritable(o.block))}class PD{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 ND{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(_r(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Gr=S("editor");class $D 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 ND);m(this,"dataConverter",new ED);m(this,"editorBlocks",new b4(this));m(this,"editorBoxes",new g6(this));m(this,"editorInsertions",new v6(this));m(this,"editorEmbeds",new y4(this));m(this,"editorDecorators",new y6(this));m(this,"editorCommandProviders",new sb(this));m(this,"editorBlockRenders",new xD(this));m(this,"blockHooks",[]);m(this,"domEvents",new RD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new cD(this));m(this,"settingsProvider");m(this,"_readonly",!1);Gr.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 PD(this),DD(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 wD(this),this.doc=new pD(this,o,this.undoManager),this.parent=e,this.rootElement=w("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=w("div",["editor-content"],this.rootElement),this.rootContainerObject=p4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new QI(this,this.inputHandlers),this.selection=new FT(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"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:ro(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(Gr,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(){Gr.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 FD(this)}isBlockWritable(e){return _D(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return g(Gr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Gr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return C4(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(Gr,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Gr,Pm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Gr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Gr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Fr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return jr(this,e)}getParentContainer(e){return nt(e)}reloadBlock(e){LD(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 P6(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 _i(this,e)}getBoxData(e){return u6(this,e)}getBlockText(e){return gn(this,e)}setBlockText(e,o){H6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Sg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return S6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return L6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){z6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Ng(this,e,o,r,i)}deleteChildContainers(e){F6(this,e)}replaceBlockText(e,o){return xh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Ih(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return j6(this,e,o,r)}updateBoxData(e){OD(this,e)}getSelectedText(){const e=Sh(this);return La(this,e)}clearSelectedContents(){Og(this)}insertTextBlock(e,o,r,i){const s=lr(e!=null?e:"");return _6(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){R6(this);return}o?(this.compositingText="",zd()||Dg(this,e)):(this.compositingText=e,M6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Ha(n,t,e){return new $D(n,t,e)}function HD(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=mm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const jD=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Ph 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:jD}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&aa.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.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){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&&gh(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(gh(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 tp extends ha{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[lr("")]}},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}localInsertChildContainer(e,o){this.doc.blocks[e]=o,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!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 Ph}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 UD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function ep(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new UD(o)})}const ab=S("find-block");function ub(n,t){const e=Ts(t);if(!e){if(io(t))return null;const o=xs(t);return g(ab,o,"no parent block"),ub(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function db(n,t){const e=Ds(t);if(!e){if(io(t))return null;const o=xs(t);return g(ab,o,"no parent block"),db(n,o)}return Mt(n,e)?Xm(n,e,{visibleOnly:!0}):e}const zD=S("remote-cursor");class VD{constructor(){m(this,"remoteUsers",new Ph)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):zD.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 WD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function qD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function ja(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=WD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Ni(n){return n==="root"?"blocks":n}function Kl(n){return n==="blocks"?"root":n}const GD={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 ar=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$i={},np=q5.default.EventEmitter;$i.EventEmitter=np,$i.mixin=ZD;function ZD(n){for(var t in np.prototype)n.prototype[t]=np.prototype[t]}var hb=["info","warn","error"];function fb(){var n={};hb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var QD=fb;fb.prototype.setMethods=function(n){n=n||{};var t=this;hb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var YD=QD,JD=new YD,mb=JD;function js(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,js):this.stack=new Error().stack}js.prototype=Object.create(Error.prototype),js.prototype.constructor=js,js.prototype.name="ShareDBError",js.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 Nh=js,Ua={},gb=KD;function KD(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=[],A=0;A<s.length;){var v=[];if(r(s[A],h,p,v),A++,v.length===1)h=v[0];else if(v.length===0){for(var B=A;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(A),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 pb={exports:{}},Hi=pb.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||""}},op=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},rp=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")},$h=function(n){for(var t=0;t<n.length;t++)rp(n[t])};Hi.apply=function(n,t){var e;$h(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=op(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 Zr=Hi._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:op(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:op(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Hi.compose=function(n,t){$h(n),$h(t);for(var e=n.slice(),o=0;o<t.length;o++)Zr(e,t[o]);return e},Hi.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),Zr(t,o)}return t};var ip=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};Hi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=ip(n,t[r],o);return n};var XD=Hi._tc=function(n,t,e,o){if(rp(t),rp(e),t.i!=null)Zr(n,{i:t.i,p:ip(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Zr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Zr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Zr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Zr(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=ip(i.p,e),Zr(n,i))}return n},tS=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Hi.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=tS(n[t]);return n},gb(Hi,XD,$h,Zr);var Hh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},eS=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Qr={};It.registerSubtype=function(n){Qr[n.name]=n},It.create=function(n){return n===void 0?null:Po(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Qr[n.t]&&(t.t=n.t,t.o=Qr[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(!Hh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Hh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!eS(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function za(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 Va(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=Po(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&za(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&&Qr[r.t])s[l]=Qr[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 nS=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=Po(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)&&(za(t),za(e)),nS(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Qr[t.t]){if(e.o=Qr[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(),Va(t),n.push(t);Va(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)&&(Va(t),Va(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=Po(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Hh(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=Po(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=Po(e);a.p=a.p.slice(s),t.ld=It.apply(Po(t.ld),[a])}else if(t.od!==void 0){var a=Po(e);a.p=a.p.slice(s),t.od=It.apply(Po(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)&&(za(t),a=Po(e),za(a)),a.t&&Qr[a.t]){if(t.t&&t.t===a.t){var h=Qr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,A=0;A<h.length;A++)t.o=[h[A]],t.p=p.slice(),Va(t),It.append(n,t);else(!Hh(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=Po(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},gb(It,It.transformComponent,It.checkValidOp,It.append);var oS=pb.exports;It.registerSubtype(oS);var rS=It,iS={type:rS};(function(n){n.defaultType=iS.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)})(Ua);var No={};(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))}})(No);var Cb=Array.isArray,Ab=Object.keys,sS=Object.prototype.hasOwnProperty,lS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Cb(t),r=Cb(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 A=Ab(t);if(s=A.length,s!==Ab(e).length)return!1;for(i=s;i--!==0;)if(!sS.call(e,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},bb=$i,cS=mb,qn=Nh,jh=Ua,$o=No,aS=$o.clone,uS=lS,Dn=qn.CODES,dS=Ft;function Ft(n,t,e){bb.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}bb.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=jh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Dn.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(Dn.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(Dn.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?jh.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;$o.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===Dn.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){$o.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){$o.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===Dn.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=Uh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Uh(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);hS(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=fS([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;$o.nextTick(function(){n._handleSubscribe()})}}};function hS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function fS(n){return n=n.filter($o.truthy),n.length?function(t){$o.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function mS(n){delete n.op,delete n.create,delete n.del}function Uh(n,t){if(n.del)return mS(t);if(t.del)return new qn(Dn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Dn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Dn.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(Dn.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===jh.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=Uh(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(Dn.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>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Dn.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(Dn.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;$o.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&&!uS(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=jh.defaultType.uri),this.type){var r=new qn(Dn.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(Dn.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:aS(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 cS.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=Uh(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=$o.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=$o.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Us={};Us.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 vb=$i,yb=Us.ACTIONS,gS=No,pS=Sn;function Sn(n,t,e,o,r,i,s){vb.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}vb.mixin(Sn),Sn.prototype.hasPending=function(){return!this.ready},Sn.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}},Sn.prototype.destroy=function(n){this.connection.canSend&&this.action===yb.querySubscribe&&this.connection.send({a:yb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&gS.nextTick(n)},Sn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Sn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Sn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Sn.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()},Sn.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},Sn.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)},Sn.prototype._handleError=function(n){this.emit("error",n)},Sn.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)},Sn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var kb=$i,CS=Us.ACTIONS,AS=No,wb=ur;function ur(n,t){if(kb.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={}}kb.mixin(ur),ur.prototype.submit=function(n,t){this.value=n,this.send(t)},ur.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},ur.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()})},ur.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},ur.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},ur.prototype._message=function(){return{a:CS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ur.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},ur.prototype._callbackOrEmit=function(n,t){if(t)return AS.nextTick(t,n);n&&this.emit("error",n)};var bS=No,Bb=sp;function sp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}sp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},sp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&bS.nextTick(n)};var lp={exports:{}};(function(n,t){(function(e,o){o(t)})(ar,function(e){function o(k,T){T=T|0;for(var L=Math.max(k.length-T,0),F=Array(L),U=0;U<L;U++)F[U]=k[T+U];return F}var r=function(k){var T=o(arguments,1);return function(){var L=o(arguments);return k.apply(null,T.concat(L))}},i=function(k){return function(){var T=o(arguments),L=T.pop();k.call(this,T,L)}};function s(k){var T=typeof k;return k!=null&&(T=="object"||T=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(k){setTimeout(k,0)}function h(k){return function(T){var L=o(arguments,1);k(function(){T.apply(null,L)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var A=h(p);function v(k){return i(function(T,L){var F;try{F=k.apply(this,T)}catch(U){return L(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(L,null,U)},function(U){B(L,U.message?U:new Error(U))}):L(null,F)})}function B(k,T,L){try{k(T,L)}catch(F){A(D,F)}}function D(k){throw k}var x=typeof Symbol=="function";function _(k){return x&&k[Symbol.toStringTag]==="AsyncFunction"}function M(k){return _(k)?v(k):k}function H(k){return function(T){var L=o(arguments,1),F=i(function(U,j){var Z=this;return k(T,function(J,lt){M(J).apply(Z,U.concat(lt))},j)});return L.length?F.apply(this,L):F}}var z=typeof ar=="object"&&ar&&ar.Object===Object&&ar,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=z||q||Function("return this")(),ft=rt.Symbol,Bt=Object.prototype,jt=Bt.hasOwnProperty,Ut=Bt.toString,ne=ft?ft.toStringTag:void 0;function qe(k){var T=jt.call(k,ne),L=k[ne];try{k[ne]=void 0;var F=!0}catch{}var U=Ut.call(k);return F&&(T?k[ne]=L:delete k[ne]),U}var Yn=Object.prototype,$e=Yn.toString;function Rn(k){return $e.call(k)}var kr="[object Null]",vn="[object Undefined]",an=ft?ft.toStringTag:void 0;function wr(k){return k==null?k===void 0?vn:kr:an&&an in Object(k)?qe(k):Rn(k)}var oi="[object AsyncFunction]",po="[object Function]",K2="[object GeneratorFunction]",X2="[object Proxy]";function t3(k){if(!s(k))return!1;var T=wr(k);return T==po||T==K2||T==oi||T==X2}var ns=9007199254740991;function nl(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=ns}function ol(k){return k!=null&&nl(k.length)&&!t3(k)}var ri={};function Nt(){}function Br(k){return function(){if(k!==null){var T=k;k=null,T.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Fc=function(k){return os&&k[os]&&k[os]()};function l1(k,T){for(var L=-1,F=Array(k);++L<k;)F[L]=T(L);return F}function un(k){return k!=null&&typeof k=="object"}var rl="[object Arguments]";function c1(k){return un(k)&&wr(k)==rl}var Co=Object.prototype,a1=Co.hasOwnProperty,e3=Co.propertyIsEnumerable,il=c1(function(){return arguments}())?c1:function(k){return un(k)&&a1.call(k,"callee")&&!e3.call(k,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,u1=ll&&!0&&n&&!n.nodeType&&n,cl=u1&&u1.exports===ll,d1=cl?rt.Buffer:void 0,al=d1?d1.isBuffer:void 0,rs=al||sl,Hu=9007199254740991,ju=/^(?:0|[1-9]\d*)$/;function Uu(k,T){var L=typeof k;return T=T==null?Hu:T,!!T&&(L=="number"||L!="symbol"&&ju.test(k))&&k>-1&&k%1==0&&k<T}var zu="[object Arguments]",Vu="[object Array]",Wu="[object Boolean]",qu="[object Date]",Gu="[object Error]",Zu="[object Function]",n3="[object Map]",o3="[object Number]",r3="[object Object]",h1="[object RegExp]",f1="[object Set]",i3="[object String]",s3="[object WeakMap]",l3="[object ArrayBuffer]",c3="[object DataView]",m1="[object Float32Array]",a3="[object Float64Array]",u3="[object Int8Array]",d3="[object Int16Array]",Qu="[object Int32Array]",h3="[object Uint8Array]",Yu="[object Uint8ClampedArray]",f3="[object Uint16Array]",m3="[object Uint32Array]",se={};se[m1]=se[a3]=se[u3]=se[d3]=se[Qu]=se[h3]=se[Yu]=se[f3]=se[m3]=!0,se[zu]=se[Vu]=se[l3]=se[Wu]=se[c3]=se[qu]=se[Gu]=se[Zu]=se[n3]=se[o3]=se[r3]=se[h1]=se[f1]=se[i3]=se[s3]=!1;function g3(k){return un(k)&&nl(k.length)&&!!se[wr(k)]}function p3(k){return function(T){return k(T)}}var g1=typeof e=="object"&&e&&!e.nodeType&&e,ul=g1&&!0&&n&&!n.nodeType&&n,C3=ul&&ul.exports===g1,Pc=C3&&z.process,p1=function(){try{var k=ul&&ul.require&&ul.require("util").types;return k||Pc&&Pc.binding&&Pc.binding("util")}catch{}}(),C1=p1&&p1.isTypedArray,A3=C1?p3(C1):g3,b3=Object.prototype,v3=b3.hasOwnProperty;function y3(k,T){var L=Ae(k),F=!L&&il(k),U=!L&&!F&&rs(k),j=!L&&!F&&!U&&A3(k),Z=L||F||U||j,J=Z?l1(k.length,String):[],lt=J.length;for(var pt in k)(T||v3.call(k,pt))&&!(Z&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Uu(pt,lt)))&&J.push(pt);return J}var Nc=Object.prototype;function k3(k){var T=k&&k.constructor,L=typeof T=="function"&&T.prototype||Nc;return k===L}function $c(k,T){return function(L){return k(T(L))}}var w3=$c(Object.keys,Object),B3=Object.prototype,E3=B3.hasOwnProperty;function A1(k){if(!k3(k))return w3(k);var T=[];for(var L in Object(k))E3.call(k,L)&&L!="constructor"&&T.push(L);return T}function Hc(k){return ol(k)?y3(k):A1(k)}function b1(k){var T=-1,L=k.length;return function(){return++T<L?{value:k[T],key:T}:null}}function x3(k){var T=-1;return function(){var F=k.next();return F.done?null:(T++,{value:F.value,key:T})}}function I3(k){var T=Hc(k),L=-1,F=T.length;return function U(){var j=T[++L];return j==="__proto__"?U():L<F?{value:k[j],key:j}:null}}function T3(k){if(ol(k))return b1(k);var T=Fc(k);return T?x3(T):I3(k)}function Ao(k){return function(){if(k===null)throw new Error("Callback was already called.");var T=k;k=null,T.apply(this,arguments)}}function dl(k){return function(T,L,F){if(F=Br(F||Nt),k<=0||!T)return F(null);var U=T3(T),j=!1,Z=0,J=!1;function lt(ct,At){if(Z-=1,ct)j=!0,F(ct);else{if(At===ri||j&&Z<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Z<k&&!j;){var ct=U();if(ct===null){j=!0,Z<=0&&F(null);return}Z+=1,L(ct.value,ct.key,Ao(lt))}J=!1}pt()}}function Er(k,T,L,F){dl(T)(k,M(L),F)}function He(k,T){return function(L,F,U){return k(L,T,F,U)}}function Ju(k,T,L){L=Br(L||Nt);var F=0,U=0,j=k.length;j===0&&L(null);function Z(J,lt){J?L(J):(++U===j||lt===ri)&&L(null)}for(;F<j;F++)T(k[F],F,Ao(Z))}var D3=He(Er,1/0),Go=function(k,T,L){var F=ol(k)?Ju:D3;F(k,M(T),L)};function Zo(k){return function(T,L,F){return k(Go,T,M(L),F)}}function Ku(k,T,L,F){F=F||Nt,T=T||[];var U=[],j=0,Z=M(L);k(T,function(J,lt,pt){var ct=j++;Z(J,function(At,Gt){U[ct]=Gt,pt(At)})},function(J){F(J,U)})}var jc=Zo(Ku),Xu=H(jc);function ii(k){return function(T,L,F,U){return k(dl(L),T,M(F),U)}}var xr=ii(Ku),td=He(xr,1),ed=H(td);function is(k,T){for(var L=-1,F=k==null?0:k.length;++L<F&&T(k[L],L,k)!==!1;);return k}function nd(k){return function(T,L,F){for(var U=-1,j=Object(T),Z=F(T),J=Z.length;J--;){var lt=Z[k?J:++U];if(L(j[lt],lt,j)===!1)break}return T}}var ss=nd();function ls(k,T){return k&&ss(k,T,Hc)}function v1(k,T,L,F){for(var U=k.length,j=L+(F?1:-1);F?j--:++j<U;)if(T(k[j],j,k))return j;return-1}function S3(k){return k!==k}function y1(k,T,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===T)return F;return-1}function hl(k,T,L){return T===T?y1(k,T,L):v1(k,S3,L)}var Uc=function(k,T,L){typeof T=="function"&&(L=T,T=null),L=Br(L||Nt);var F=Hc(k),U=F.length;if(!U)return L(null);T||(T=U);var j={},Z=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ls(k,function(de,re){if(!Ae(de)){Gt(re,[de]),ct.push(re);return}var ge=de.slice(0,de.length-1),vo=ge.length;if(vo===0){Gt(re,de),ct.push(re);return}At[re]=vo,is(ge,function(E){if(!k[E])throw new Error("async.auto task `"+re+"` has a non-existent dependency `"+E+"` in "+ge.join(", "));en(E,function(){vo--,vo===0&&Gt(re,de)})})}),K3(),Ie();function Gt(de,re){pt.push(function(){bo(de,re)})}function Ie(){if(pt.length===0&&Z===0)return L(null,j);for(;pt.length&&Z<T;){var de=pt.shift();de()}}function en(de,re){var ge=lt[de];ge||(ge=lt[de]=[]),ge.push(re)}function Fn(de){var re=lt[de]||[];is(re,function(ge){ge()}),Ie()}function bo(de,re){if(!J){var ge=Ao(function(E,Dr){if(Z--,arguments.length>2&&(Dr=o(arguments,1)),E){var ds={};ls(j,function(Pn,Pt){ds[Pt]=Pn}),ds[de]=Dr,J=!0,lt=Object.create(null),L(E,ds)}else j[de]=Dr,Fn(de)});Z++;var vo=M(re[re.length-1]);re.length>1?vo(j,ge):vo(ge)}}function K3(){for(var de,re=0;ct.length;)de=ct.pop(),re++,is(X3(de),function(ge){--At[ge]===0&&ct.push(ge)});if(re!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function X3(de){var re=[];return ls(k,function(ge,vo){Ae(ge)&&hl(ge,de,0)>=0&&re.push(vo)}),re}};function si(k,T){for(var L=-1,F=k==null?0:k.length,U=Array(F);++L<F;)U[L]=T(k[L],L,k);return U}var L3="[object Symbol]";function M3(k){return typeof k=="symbol"||un(k)&&wr(k)==L3}var R3=1/0,od=ft?ft.prototype:void 0,k1=od?od.toString:void 0;function rd(k){if(typeof k=="string")return k;if(Ae(k))return si(k,rd)+"";if(M3(k))return k1?k1.call(k):"";var T=k+"";return T=="0"&&1/k==-R3?"-0":T}function O3(k,T,L){var F=-1,U=k.length;T<0&&(T=-T>U?0:U+T),L=L>U?U:L,L<0&&(L+=U),U=T>L?0:L-T>>>0,T>>>=0;for(var j=Array(U);++F<U;)j[F]=k[F+T];return j}function _3(k,T,L){var F=k.length;return L=L===void 0?F:L,!T&&L>=F?k:O3(k,T,L)}function id(k,T){for(var L=k.length;L--&&hl(T,k[L],0)>-1;);return L}function F3(k,T){for(var L=-1,F=k.length;++L<F&&hl(T,k[L],0)>-1;);return L}function P3(k){return k.split("")}var N3="\\ud800-\\udfff",$3="\\u0300-\\u036f",H3="\\ufe20-\\ufe2f",le="\\u20d0-\\u20ff",oe=$3+H3+le,j3="\\ufe0e\\ufe0f",U3="\\u200d",z3=RegExp("["+U3+N3+oe+j3+"]");function V3(k){return z3.test(k)}var w1="\\ud800-\\udfff",W3="\\u0300-\\u036f",B1="\\ufe20-\\ufe2f",q3="\\u20d0-\\u20ff",Ge=W3+B1+q3,sd="\\ufe0e\\ufe0f",li="["+w1+"]",zc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",On="(?:"+zc+"|"+fl+")",ld="[^"+w1+"]",cd="(?:\\ud83c[\\udde6-\\uddff]){2}",ad="[\\ud800-\\udbff][\\udc00-\\udfff]",E1="\\u200d",ud=On+"?",dd="["+sd+"]?",yn="(?:"+E1+"(?:"+[ld,cd,ad].join("|")+")"+dd+ud+")*",G3=dd+ud+yn,_n="(?:"+[ld+zc+"?",zc,cd,ad,li].join("|")+")",Z3=RegExp(fl+"(?="+fl+")|"+_n+G3,"g");function x1(k){return k.match(Z3)||[]}function Qo(k){return V3(k)?x1(k):P3(k)}function Vc(k){return k==null?"":rd(k)}var hd=/^\s+|\s+$/g;function ue(k,T,L){if(k=Vc(k),k&&(L||T===void 0))return k.replace(hd,"");if(!k||!(T=rd(T)))return k;var F=Qo(k),U=Qo(T),j=F3(F,U),Z=id(F,U)+1;return _3(F,j,Z).join("")}var Ir=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,fd=/,/,Q3=/(=.+)?(\s*)$/,md=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Y3(k){return k=k.toString().replace(md,""),k=k.match(Ir)[2].replace(" ",""),k=k?k.split(fd):[],k=k.map(function(T){return ue(T.replace(Q3,""))}),k}function I1(k,T){var L={};ls(k,function(F,U){var j,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],L[U]=j.concat(j.length>0?lt:F);else if(J)L[U]=F;else{if(j=Y3(F),F.length===0&&!Z&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||j.pop(),L[U]=j.concat(lt)}function lt(pt,ct){var At=si(j,function(Gt){return pt[Gt]});At.push(ct),M(F).apply(null,At)}}),Uc(L,T)}function Jn(){this.head=this.tail=null,this.length=0}function gd(k,T){k.length=1,k.head=k.tail=T}Jn.prototype.removeLink=function(k){return k.prev?k.prev.next=k.next:this.head=k.next,k.next?k.next.prev=k.prev:this.tail=k.prev,k.prev=k.next=null,this.length-=1,k},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.prototype.insertAfter=function(k,T){T.prev=k,T.next=k.next,k.next?k.next.prev=T:this.tail=T,k.next=T,this.length+=1},Jn.prototype.insertBefore=function(k,T){T.prev=k.prev,T.next=k,k.prev?k.prev.next=T:this.head=T,k.prev=T,this.length+=1},Jn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):gd(this,k)},Jn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):gd(this,k)},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 k=Array(this.length),T=this.head,L=0;L<this.length;L++)k[L]=T.data,T=T.next;return k},Jn.prototype.remove=function(k){for(var T=this.head;T;){var L=T.next;k(T)&&this.removeLink(T),T=L}return this};function ml(k,T,L){if(T==null)T=1;else if(T===0)throw new Error("Concurrency must not be zero");var F=M(k),U=0,j=[],Z=!1;function J(At,Gt,Ie){if(Ie!=null&&typeof Ie!="function")throw new Error("task callback must be a function");if(ct.started=!0,Ae(At)||(At=[At]),At.length===0&&ct.idle())return A(function(){ct.drain()});for(var en=0,Fn=At.length;en<Fn;en++){var bo={data:At[en],callback:Ie||Nt};Gt?ct._tasks.unshift(bo):ct._tasks.push(bo)}Z||(Z=!0,A(function(){Z=!1,ct.process()}))}function lt(At){return function(Gt){U-=1;for(var Ie=0,en=At.length;Ie<en;Ie++){var Fn=At[Ie],bo=hl(j,Fn,0);bo===0?j.shift():bo>0&&j.splice(bo,1),Fn.callback.apply(Fn,arguments),Gt!=null&&ct.error(Gt,Fn.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Jn,concurrency:T,payload:L,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Gt){J(At,!1,Gt)},kill:function(){ct.drain=Nt,ct._tasks.empty()},unshift:function(At,Gt){J(At,!0,Gt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Gt=[],Ie=ct._tasks.length;ct.payload&&(Ie=Math.min(Ie,ct.payload));for(var en=0;en<Ie;en++){var Fn=ct._tasks.shift();At.push(Fn),j.push(Fn),Gt.push(Fn.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var bo=Ao(lt(At));F(Gt,bo)}pt=!1}},length:function(){return ct._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ct._tasks.length+U===0},pause:function(){ct.paused=!0},resume:function(){ct.paused!==!1&&(ct.paused=!1,A(ct.process))}};return ct}function ci(k,T){return ml(k,1,T)}var cs=He(Er,1);function Yo(k,T,L,F){F=Br(F||Nt);var U=M(L);cs(k,function(j,Z,J){U(T,j,function(lt,pt){T=pt,J(lt)})},function(j){F(j,T)})}function Wc(){var k=si(arguments,M);return function(){var T=o(arguments),L=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Nt,Yo(k,T,function(U,j,Z){j.apply(L,U.concat(function(J){var lt=o(arguments,1);Z(J,lt)}))},function(U,j){F.apply(L,[U].concat(j))})}}var qc=function(){return Wc.apply(null,o(arguments).reverse())},pd=Array.prototype.concat,gl=function(k,T,L,F){F=F||Nt;var U=M(L);xr(k,T,function(j,Z){U(j,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(j,Z){for(var J=[],lt=0;lt<Z.length;lt++)Z[lt]&&(J=pd.apply(J,Z[lt]));return F(j,J)})},T1=He(gl,1/0),Gc=He(gl,1),Zc=function(){var k=o(arguments),T=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,T)}};function pl(k){return k}function ai(k,T){return function(L,F,U,j){j=j||Nt;var Z=!1,J;L(F,function(lt,pt,ct){U(lt,function(At,Gt){At?ct(At):k(Gt)&&!J?(Z=!0,J=T(!0,lt),ct(null,ri)):ct()})},function(lt){lt?j(lt):j(null,Z?J:T(!1))})}}function dn(k,T){return T}var as=Zo(ai(pl,dn)),Jo=ii(ai(pl,dn)),Cl=He(Jo,1);function Cd(k){return function(T){var L=o(arguments,1);L.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[k]&&is(U,function(j){console[k](j)}))}),M(T).apply(null,L)}}var D1=Cd("dir");function S1(k,T,L){L=Ao(L||Nt);var F=M(k),U=M(T);function j(J){if(J)return L(J);var lt=o(arguments,1);lt.push(Z),U.apply(this,lt)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}Z(null,!0)}function Ad(k,T,L){L=Ao(L||Nt);var F=M(k),U=function(j){if(j)return L(j);var Z=o(arguments,1);if(T.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function L1(k,T,L){Ad(k,function(){return!T.apply(this,arguments)},L)}function M1(k,T,L){L=Ao(L||Nt);var F=M(T),U=M(k);function j(J){if(J)return L(J);U(Z)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}U(Z)}function ui(k){return function(T,L,F){return k(T,F)}}function Qc(k,T,L){Go(k,ui(M(T)),L)}function Al(k,T,L,F){dl(T)(k,ui(M(L)),F)}var di=He(Al,1);function Yc(k){return _(k)?k:i(function(T,L){var F=!0;T.push(function(){var U=arguments;F?A(function(){L.apply(null,U)}):L.apply(null,U)}),k.apply(this,T),F=!1})}function Kn(k){return!k}var hi=Zo(ai(Kn,Kn)),bl=ii(ai(Kn,Kn)),Jc=He(bl,1);function R1(k){return function(T){return T==null?void 0:T[k]}}function us(k,T,L,F){var U=new Array(T.length);k(T,function(j,Z,J){L(j,function(lt,pt){U[Z]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Z=[],J=0;J<T.length;J++)U[J]&&Z.push(T[J]);F(null,Z)})}function Xn(k,T,L,F){var U=[];k(T,function(j,Z,J){L(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Z,value:j}),J())})},function(j){j?F(j):F(null,si(U.sort(function(Z,J){return Z.index-J.index}),R1("value")))})}function Kc(k,T,L,F){var U=ol(T)?us:Xn;U(k,T,M(L),F||Nt)}var Xc=Zo(Kc),vl=ii(Kc),ta=He(vl,1);function O1(k,T){var L=Ao(T||Nt),F=M(Yc(k));function U(j){if(j)return L(j);F(U)}U()}var ea=function(k,T,L,F){F=F||Nt;var U=M(L);xr(k,T,function(j,Z){U(j,function(J,lt){return J?Z(J):Z(null,{key:lt,val:j})})},function(j,Z){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Z.length;pt++)if(Z[pt]){var ct=Z[pt].key,At=Z[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},fi=He(ea,1/0),N=He(ea,1),G=Cd("log");function V(k,T,L,F){F=Br(F||Nt);var U={},j=M(L);Er(k,T,function(Z,J,lt){j(Z,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Z){F(Z,U)})}var ht=He(V,1/0),Et=He(V,1);function Vt(k,T){return T in k}function we(k,T){var L=Object.create(null),F=Object.create(null);T=T||pl;var U=M(k),j=i(function(J,lt){var pt=T.apply(null,J);Vt(L,pt)?A(function(){lt.apply(null,L[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);L[pt]=ct;var At=F[pt];delete F[pt];for(var Gt=0,Ie=At.length;Gt<Ie;Gt++)At[Gt].apply(null,ct)})))});return j.memo=L,j.unmemoized=k,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var na=h(qt);function bd(k,T,L){L=L||Nt;var F=ol(T)?[]:{};k(T,function(U,j,Z){M(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Z(J)})},function(U){L(U,F)})}function kn(k,T){bd(Go,k,T)}function yl(k,T,L){bd(dl(T),k,L)}var vd=function(k,T){var L=M(k);return ml(function(F,U){L(F[0],U)},T,1)},mi=function(k,T){var L=vd(k,T);return L.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(L.started=!0,Ae(F)||(F=[F]),F.length===0)return A(function(){L.drain()});U=U||0;for(var Z=L._tasks.head;Z&&U>=Z.priority;)Z=Z.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Z?L._tasks.insertBefore(Z,pt):L._tasks.push(pt)}A(L.process)},delete L.unshift,L};function kl(k,T){if(T=Br(T||Nt),!Ae(k))return T(new TypeError("First argument to race must be an array of functions"));if(!k.length)return T();for(var L=0,F=k.length;L<F;L++)M(k[L])(T)}function gi(k,T,L,F){var U=o(k).reverse();Yo(U,T,L,F)}function Wt(k){var T=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function _1(k){var T;return Ae(k)?T=si(k,Wt):(T={},ls(k,function(L,F){T[F]=Wt.call(this,L)})),T}function yd(k,T,L,F){Kc(k,T,function(U,j){L(U,function(Z,J){j(Z,!J)})},F)}var wl=Zo(yd),kd=ii(yd),F1=He(kd,1);function P1(k){return function(){return k}}function pi(k,T,L){var F=5,U=0,j={times:F,intervalFunc:P1(U)};function Z(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:P1(+At.interval||U),ct.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")ct.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=T||Nt,T=k):(Z(j,k),L=L||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=M(T),lt=1;function pt(){J(function(ct){ct&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):L.apply(null,arguments)})}pt()}var Ko=function(k,T){T||(T=k,k=null);var L=M(T);return i(function(F,U){function j(Z){L.apply(null,F.concat(Z))}k?pi(k,j,U):pi(j,U)})};function Bl(k,T){bd(cs,k,T)}var El=Zo(ai(Boolean,pl)),Tr=ii(ai(Boolean,pl)),xl=He(Tr,1);function wd(k,T,L){var F=M(T);jc(k,function(j,Z){F(j,function(J,lt){if(J)return Z(J);Z(null,{value:j,criteria:lt})})},function(j,Z){if(j)return L(j);L(null,si(Z.sort(U),R1("value")))});function U(j,Z){var J=j.criteria,lt=Z.criteria;return J<lt?-1:J>lt?1:0}}function Il(k,T,L){var F=M(k);return i(function(U,j){var Z=!1,J;function lt(){var pt=k.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",L&&(ct.info=L),Z=!0,j(ct)}U.push(function(){Z||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var N1=Math.ceil,Tl=Math.max;function Ci(k,T,L,F){for(var U=-1,j=Tl(N1((T-k)/(L||1)),0),Z=Array(j);j--;)Z[F?j:++U]=k,k+=L;return Z}function Ai(k,T,L,F){var U=M(L);xr(Ci(0,k,1),T,U,F)}var $1=He(Ai,1/0),H1=He(Ai,1);function j1(k,T,L,F){arguments.length<=3&&(F=L,L=T,T=Ae(k)?[]:{}),F=Br(F||Nt);var U=M(L);Go(k,function(j,Z,J){U(T,j,Z,J)},function(j){F(j,T)})}function Dl(k,T){var L=null,F;T=T||Nt,di(k,function(U,j){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,j(!Z)})},function(){T(L,F)})}function Sl(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Ll(k,T,L){L=Ao(L||Nt);var F=M(T);if(!k())return L(null);var U=function(j){if(j)return L(j);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function U1(k,T,L){Ll(function(){return!k.apply(this,arguments)},T,L)}var Bd=function(k,T){if(T=Br(T||Nt),!Ae(k))return T(new Error("First argument to waterfall must be an array of functions"));if(!k.length)return T();var L=0;function F(j){var Z=M(k[L++]);j.push(Ao(U)),Z.apply(null,j)}function U(j){if(j||L===k.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},J3={apply:r,applyEach:Xu,applyEachSeries:ed,asyncify:v,auto:Uc,autoInject:I1,cargo:ci,compose:qc,concat:T1,concatLimit:gl,concatSeries:Gc,constant:Zc,detect:as,detectLimit:Jo,detectSeries:Cl,dir:D1,doDuring:S1,doUntil:L1,doWhilst:Ad,during:M1,each:Qc,eachLimit:Al,eachOf:Go,eachOfLimit:Er,eachOfSeries:cs,eachSeries:di,ensureAsync:Yc,every:hi,everyLimit:bl,everySeries:Jc,filter:Xc,filterLimit:vl,filterSeries:ta,forever:O1,groupBy:fi,groupByLimit:ea,groupBySeries:N,log:G,map:jc,mapLimit:xr,mapSeries:td,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:we,nextTick:na,parallel:kn,parallelLimit:yl,priorityQueue:mi,queue:vd,race:kl,reduce:Yo,reduceRight:gi,reflect:Wt,reflectAll:_1,reject:wl,rejectLimit:kd,rejectSeries:F1,retry:pi,retryable:Ko,seq:Wc,series:Bl,setImmediate:A,some:El,someLimit:Tr,someSeries:xl,sortBy:wd,timeout:Il,times:$1,timesLimit:Ai,timesSeries:H1,transform:j1,tryEach:Dl,unmemoize:Sl,until:U1,waterfall:Bd,whilst:Ll,all:hi,allLimit:bl,allSeries:Jc,any:El,anyLimit:Tr,anySeries:xl,find:as,findLimit:Jo,findSeries:Cl,forEach:Qc,forEachSeries:di,forEachLimit:Al,forEachOf:Go,forEachOfSeries:cs,forEachOfLimit:Er,inject:Yo,foldl:Yo,foldr:gi,select:Xc,selectLimit:vl,selectSeries:ta,wrapSync:v};e.default=J3,e.apply=r,e.applyEach=Xu,e.applyEachSeries=ed,e.asyncify=v,e.auto=Uc,e.autoInject=I1,e.cargo=ci,e.compose=qc,e.concat=T1,e.concatLimit=gl,e.concatSeries=Gc,e.constant=Zc,e.detect=as,e.detectLimit=Jo,e.detectSeries=Cl,e.dir=D1,e.doDuring=S1,e.doUntil=L1,e.doWhilst=Ad,e.during=M1,e.each=Qc,e.eachLimit=Al,e.eachOf=Go,e.eachOfLimit=Er,e.eachOfSeries=cs,e.eachSeries=di,e.ensureAsync=Yc,e.every=hi,e.everyLimit=bl,e.everySeries=Jc,e.filter=Xc,e.filterLimit=vl,e.filterSeries=ta,e.forever=O1,e.groupBy=fi,e.groupByLimit=ea,e.groupBySeries=N,e.log=G,e.map=jc,e.mapLimit=xr,e.mapSeries=td,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=we,e.nextTick=na,e.parallel=kn,e.parallelLimit=yl,e.priorityQueue=mi,e.queue=vd,e.race=kl,e.reduce=Yo,e.reduceRight=gi,e.reflect=Wt,e.reflectAll=_1,e.reject=wl,e.rejectLimit=kd,e.rejectSeries=F1,e.retry=pi,e.retryable=Ko,e.seq=Wc,e.series=Bl,e.setImmediate=A,e.some=El,e.someLimit=Tr,e.someSeries=xl,e.sortBy=wd,e.timeout=Il,e.times=$1,e.timesLimit=Ai,e.timesSeries=H1,e.transform=j1,e.tryEach=Dl,e.unmemoize=Sl,e.until=U1,e.waterfall=Bd,e.whilst=Ll,e.all=hi,e.allLimit=bl,e.allSeries=Jc,e.any=El,e.anyLimit=Tr,e.anySeries=xl,e.find=as,e.findLimit=Jo,e.findSeries=Cl,e.forEach=Qc,e.forEachSeries=di,e.forEachLimit=Al,e.forEachOf=Go,e.forEachOfSeries=cs,e.forEachOfLimit=Er,e.inject=Yo,e.foldl=Yo,e.foldr=gi,e.select=Xc,e.selectLimit=vl,e.selectSeries=ta,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(lp,lp.exports);var Eb={exports:{}},cp=Eb.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)?cp(n,t):i};cp.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=cp(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 xb=$i,vS=wb,yS=Bb,zh=No,ap=lp.exports,kS=Eb.exports,Ib=Us.ACTIONS,Tb=Re;function Re(n,t){if(xb.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}xb.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||kS();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);ap.parallel([function(i){ap.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();ap.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?Ib.presenceSubscribe:Ib.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=zh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=zh.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 zh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new vS(this,n)},Re.prototype._createRemotePresence=function(n){return new yS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=zh.callEach(n,t);!e&&t&&this.emit("error",t)};var Wa=wb,Db=Nh,wS=No,Sb=Db.CODES,BS=Ho;function Ho(n,t){Wa.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()}Ho.prototype=Object.create(Wa.prototype),Ho.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Sb.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,Wa.prototype.submit.call(this,n,t)},Ho.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),Wa.prototype.destroy.call(this,n)},Ho.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Ho.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},Ho.prototype._transformAgainstOp=function(n,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)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.prototype._message=function(){var n=Wa.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Ho.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!wS.supportsPresence(o))throw new Db(Sb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Lb={};(function(n){var t=Ua,e=Nh,o=No,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(A){return A}}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 A=n.apply(l,p);if(A)return A}},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(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}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 A=d[p];typeof A.lm=="string"&&(A.lm=+A.lm);for(var v=A.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,[A]))}}}}})(Lb);var qa=Bb,ES=Lb,xS=ao;function ao(n,t){qa.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()}ao.prototype=Object.create(qa.prototype),ao.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ao.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),qa.prototype.destroy.call(this,n)},ao.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)},ao.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))}})}},ao.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},qa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},qa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},ao.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)}},ao.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++):ES.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ao.prototype._startCachingOps=function(){this._opCache=[]},ao.prototype._stopCachingOps=function(){this._opCache=null},ao.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Mb=Tb,IS=BS,TS=xS;function Xl(n,t,e){var o=Xl.channel(t,e);Mb.call(this,n,o),this.collection=t,this.id=e}var DS=Xl;Xl.prototype=Object.create(Mb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new IS(this,n)},Xl.prototype._createRemotePresence=function(n){return new TS(this,n)};var SS=LS;function LS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var MS=SS,Rb=$i,Ob=Ga;function Ga(n,t,e,o,r){if(Rb.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}Rb.mixin(Ga),Ga.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ga.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ga.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new MS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var _b=Ob,RS=No,OS=Us.ACTIONS,_S=up;function up(n,t,e,o,r,i){if(_b.call(this,n,t,e,o,i),!RS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}up.prototype=Object.create(_b.prototype),up.prototype._message=function(){return{a:OS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Fb=Ob,FS=No,PS=Us.ACTIONS,NS=dp;function dp(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!FS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}dp.prototype=Object.create(Fb.prototype),dp.prototype._message=function(){return{a:PS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var $S=dS,HS=pS,jS=Tb,Pb=DS,US=_S,zS=NS,Nb=$i,tc=Nh,ee=Us.ACTIONS,$b=Ua,jo=No,Za=mb,Qa=tc.CODES;function Hb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var VS=wt;function wt(n){Nb.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=Hb(n),this.bindToSocket(n)}Nb.mixin(wt),wt.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=Hb(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{Za.warn("Failed to parse message",o);return}e.debug&&Za.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){jo.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)}},wt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=jb(n.error,n),delete n.error),n.a){case ee.initLegacy:return this._handleLegacyInit(n);case ee.handshake:return this._handleHandshake(t,n);case ee.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ee.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ee.queryUnsubscribe:return;case ee.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 ee.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ee.bulkSubscribe:case ee.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ee.snapshotFetch:case ee.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ee.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ee.subscribe:case ee.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ee.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ee.presence:return this._handlePresence(t,n);case ee.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ee.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ee.presenceRequest:return this._handlePresenceRequest(t,n);case ee.pingPong:return this._handlePingPong(t);default:Za.warn("Ignoring unrecognized message",n)}};function jb(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}wt.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](jb(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 Za.error("Invalid bulk message",t)},wt.prototype._reset=function(){this.agent=null},wt.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(Qa.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)}},wt.prototype.startBulk=function(){this.bulk||(this.bulk={})},wt.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},wt.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})}},wt.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)}},wt.prototype.sendFetch=function(n){return this._sendActions(ee.fetch,n,n.version)},wt.prototype.sendSubscribe=function(n){return this._sendActions(ee.subscribe,n,n.version)},wt.prototype.sendUnsubscribe=function(n){return this._sendActions(ee.unsubscribe,n)},wt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ee.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)},wt.prototype.send=function(n){this.debug&&Za.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},wt.prototype.ping=function(){if(!this.canSend)throw new tc(Qa.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ee.pingPong};this.send(n)},wt.prototype.close=function(){this.socket.close()},wt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},wt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new $S(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},wt.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},wt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},wt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new HS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},wt.prototype._destroyQuery=function(n){delete this.queries[n.id]},wt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ee.queryFetch,n,t,e,o)},wt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ee.querySubscribe,n,t,e,o)},wt.prototype.hasPending=function(){return!!(this._firstDoc(Vh)||this._firstQuery(Vh)||this._firstSnapshotRequest())};function Vh(n){return n.hasPending()}wt.prototype.hasWritePending=function(){return!!this._firstDoc(WS)};function WS(n){return n.hasWritePending()}wt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Vh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Vh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},wt.prototype._nothingPendingRetry=function(n){var t=this;return function(){jo.nextTick(function(){t.whenNothingPending(n)})}},wt.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}}},wt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},wt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},wt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new US(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new zS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},wt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},wt.prototype._initializeHandshake=function(){this.send({a:ee.handshake,id:this.id})},wt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},wt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},wt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Qa.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if($b.map[n.type]!==$b.defaultType)return this.emit("error",new tc(Qa.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Qa.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},wt.prototype.getPresence=function(n){var t=this,e=jo.digOrCreate(this._presences,n,function(){return new jS(t,n)});return e._wantsDestroy=!1,e},wt.prototype.getDocPresence=function(n,t){var e=Pb.channel(n,t),o=this,r=jo.digOrCreate(this._presences,e,function(){return new Pb(o,n,t)});return r._wantsDestroy=!1,r},wt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},wt.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},wt.prototype._handlePresenceSubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},wt.prototype._handlePresenceUnsubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},wt.prototype._handlePresence=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},wt.prototype._handlePresenceRequest=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Ub=VS,qS=Ua;const Wh={err:1001,msg:"user auth error",name:"AuthError"},GS={err:1002,msg:"you don't have required permission",name:"PermissionError"},hp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ya={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},ZS={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"},Ja="x-live-editor-token",qh="x-live-editor-base-url",pn=S("auth-connection");function YS(n){try{n()}catch(t){pn.error(t)}}class JS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new V5.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 Si(this.getBaseURL())}async auth(t){g(pn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Ja]:t.token,[qh]: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:{[qh]:Si(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new WB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Ub.prototype),g(pn,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}}},Ub.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,pn.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){pn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else pn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Wh.msg);t.code=Wh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ya.msg);t.code=Ya.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===Wh.err)pn.warn("auth error"),this.handleAuthError();else if(o===hp.err)pn.warn(hp.msg),this.emitMaxUsersError();else if(o===Ya.err){pn.warn(Ya.msg);try{this.emitRequestReloadError()}catch(r){pn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else pn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(pn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(pn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(pn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(pn,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(),YS(()=>{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 KS(){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}KS();async function XS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new qB.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 Si(i)}const dr=S("sharedb-doc/client");class tL{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(dr,!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),dr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;qS.register(_d.type),this.connection=new JS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(dr,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,{[Ja]: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=>{dr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await XS(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 A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return dr.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(dr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Ja]:this.connection.token},e,o);return g(dr,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(dr,o,"no token"),a.headers={...a.headers,[Ja]:o,[qh]:this.connection.getBase64BaseURL()};try{return await zB.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(dr,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=VB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(dr,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/${Si(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 eL(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const fp=S("block-ids");class nL{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(fp,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(fp,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 oL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new nL,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(fp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class zb{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 Gh=S("op-parse-handler");class rL{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 oL,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&&(Gh.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)){Gh.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 zb,o.set(d,h)),h.delete(l.key)}else g(Gh,!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 zb,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);Gh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Oe=S("op-parser");class Vb{}class mp{constructor(t){m(this,"key");this.key=t}}function iL(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 gp(n,t,e,o){if(e==="upsert"&&iL(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 mp(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 Vb),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 mp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Vb?o.onDeleteBlock(n,i):l instanceof mp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function sL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function lL(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 pp(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{pp(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){sL(n);return}if(r==="comments"){lL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{gp(i,s,t,e)}):n.slice(1).forEach(s=>{gp(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)}`),gp(i,n.slice(1),t,e)}function Wb(n,t,e){const o=new rL(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=>{pp(a,i,o)}):pp(s,i,o)}o.end()}const cL=S("sharedb-comments");function Cp(n){const t=n.blocks;g(cL,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 qb(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 Ap(n,t){const e=qD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ae=S("sharedb-doc/doc-container"),Gb="ot-json1";_d.type.registerSubtype(GD.type),_d.type.name=Gb,_d.type.invert=null;class Ka extends ha{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new VD);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(!aa.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){ae.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ae.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ae.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ae.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,Gb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainer",async(e,o)=>{const r=[Ni(e),{i:o}];return this.submitOp(r)});m(this,"submitDeleteChildContainer",async e=>{const o=[Ni(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Ni(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Ni(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=[Ni(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=[Ni(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ae.warn("handleOp: destroyed");return}Wb(e,this,!!o)});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(ae,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new tL(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new Ka(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||eL())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ae.error(o),ae.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 ja(this.data())}getContainerBlocks(e){const o=this.data();g(ae,o,"no doc data");const r=o[Ni(e)];return g(ae,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(ae,r,"no doc data");const i=r[Ni(e)];g(ae,i,`no container data: ${e}`);const s=i[o];return g(ae,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(ae,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(ae,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>qb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Cp(o)}localCreateComment(e,o){const r=Ap(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=Ap(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(ae,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(ae,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(ae,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(ae,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(ae,this.callbacks.length>0,"no callbacks"),g(ae,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(ae,this.callbacks.length>0,"no callbacks"),g(ae,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(ae,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(ae,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(ae,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 ja(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ja(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:ja(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:ja(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){Wb(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 Zb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Se.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 Qb=S("remote-cursor-decorator");class bp{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(Qb,typeof s=="string","invalid path containerId"),g(Qb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,A)=>{A>d&&(A=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(A);B?B.push(...v):i.set(A,v)}),{insertions:i}}}class Yb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Xt(jr(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 aL(n,t){n.addCustom("child-block-tracker",()=>new Yb(n)).addListener("change",t)}function uL(n,t){n.addCustom("child-block-tracker",()=>new Yb(n)).removeListener("change",t)}const dnt="",dL={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"}},hL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},fL={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"}};R.mergeLang({"zh-CN":dL,"en-US":hL,"js-JP":fL});const hnt="";S("button");function uo(n,t,e,o,r){const i=w("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}function Jb(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const fnt="",ec=S("ui-command-bar-base"),mL={itemElementTag:"div",tippyArrow:!1},Y2=class extends ve.TypedEmitter{constructor(e,o,r){var i,s;super();m(this,"content");m(this,"items");m(this,"subBar",null);m(this,"parentItem",null);m(this,"closeable",null);m(this,"closeReason",null);m(this,"options");m(this,"id");m(this,"header",null);m(this,"footer",null);m(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing&&!Ss(e.target)){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close("cancelBar");return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(e.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});m(this,"handleDocumentMouseDown",e=>{if(e.target instanceof Element&&!this.isInCommandBar(e.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,e)===!1)return;this.close("clickBackground")}});m(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),wC(this.id)});m(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&W(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&kC(this.id)});m(this,"lastEnterPauseTime",0);m(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});m(this,"handleItemMouseEnter",e=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});m(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(ot(o,"selected"),this.emit("selectionChange",this,""))});m(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close("clickItem"))}});m(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=ro(r);if(!Kt(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:K(),this.options={...mL,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(e){this.closeReason=e,this.subBar&&this.subBar.close(e),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r,i;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=e==null?void 0:e.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),e}destroy(){var e;this.close(null),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.findIndex(s=>{var l,a;return s.id===((a=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:a.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(e){let o=e+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&ot(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&ot(s,"selected")}const r=this.getItemElementById(e);r?(W(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=Y2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(a,d,h)=>{this.emit("click",a,d,h)}),this.subBar.on("close",()=>{var a;(a=this.subBar)==null||a.destroy(),this.subBar=null,ot(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Kt(o,e)||Kt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=w(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(a=e.states)!=null&&a.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return g(ec,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return g(ec,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(ec,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(ec,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(xt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=w("div",["editor-command-bar-root"],null);if(this.options.header){const i=w("div",["editor-command-bar-header"],null);if(this.options.header instanceof Function){const s=this.options.header();s&&i.appendChild(s)}else i.appendChild(this.options.header);this.header=i,this.header&&o.appendChild(this.header)}const r=w("div",["editor-command-bar"],o);if(e.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.options.footer){const i=w("div",["menu-item","editor-command-bar","footer"],null);if(this.options.footer instanceof Function){const s=this.options.footer();s&&i.appendChild(s)}else i.appendChild(this.options.footer);this.footer=i,this.footer&&o.appendChild(this.footer)}return(this.options.header||this.options.footer)&&W(o,"scrollable-bar"),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;g(ec,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(ec,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let ji=Y2;m(ji,"commandBarCreators",new Map),S("ui-command-bar");class Zh extends ji{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=GB.default(e,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(e){var o;super.close(e),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const Kb=S("ui-base");class Xa extends Zh{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${K()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){W(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(Kb,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(Kb,e,"no item element"),e}}const Ui=S("filterable-list");function Xb(n){var e,o;const t=w("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(w("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&W(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(t,"disabled"),t}function tv(n){const t=w("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Xb(e))}),n.length||t.appendChild(Xb({id:"placeholder",states:["disabled"],name:R.t("search.emptyTips")})),t}function ev(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function gL(n,t){const e=w("div",["filterable-list"],null),o=w("div",["filter"],e),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=w("div",["list"],e),l=tv(ev(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function nv(n,t,e){const o=n.querySelector(".list");g(Ui,o,"no list root");const r=tv(ev(t,e)),i=o.querySelector(".list-root");if(g(Ui,i,"no exists menu"),Ca(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(Ui,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class pL{constructor(t,e){m(this,"root");m(this,"visibleItems");m(this,"selectedId");m(this,"filter","");m(this,"onSelected",null);m(this,"handleKeydown",t=>{this.processKeyDown(t)});m(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");g(Ui,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});m(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=gL(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,nv(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),nv(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(a=>a.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(t){var e;if(t.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class CL extends pL{constructor(e,o,r){super(e,r);m(this,"popup");m(this,"onShow",null);m(this,"onHide",null);m(this,"custom",null);m(this,"handleShow",()=>{this.onShow&&this.onShow(this)});m(this,"handleHide",()=>{this.onHide&&this.onHide(this)});m(this,"handleShown",()=>{this.focus()});this.popup=new Xa(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close("cancelBar")}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const mnt="",gnt="";function AL(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const ov=`<?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">
|
|
@@ -423,7 +423,7 @@ ${s}
|
|
|
423
423
|
Click to open the menu`,insertTips:"Click to add block"}}},z$={blockMenu:{section:{basics:"\u4E00\u822C",system:"\u30B7\u30B9\u30C6\u30E0",styles:"\u30B9\u30BF\u30A4\u30EB",common:"\u4E00\u822C",actions:"\u64CD\u4F5C",thirdParty:"\u5916\u90E8\u30B3\u30F3\u30C6\u30F3\u30C4"},command:{insertAbove:"\u4E0A\u306B\u633F\u5165",insertAfter:"\u4E0B\u306B\u633F\u5165",copy:"\u8907\u88FD",cut:"\u5207\u308B",delete:"\u524A\u9664"},button:{searchPlaceholder:"\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u691C\u7D22",tips:"\u3092\u30C9\u30E9\u30C3\u30B0\u3057\u3066\u30AF\u30EA\u30C3\u30AF\u3067\u30E1\u30CB\u30E5\u30FC\u3092\u8868\u793A",insertTips:"\u30AF\u30EA\u30C3\u30AF\u3057\u3066\u30D6\u30ED\u30C3\u30AF\u3092\u8FFD\u52A0"}}};R.mergeLang({"zh-CN":j$,"en-US":U$,"ja-JP":z$});const jnt="";class V${constructor(){m(this,"dragObject",null)}setData(t){this.dragObject=t}getData(){return this.dragObject}clearData(){this.dragObject=null}destroy(){}}function Nf(n){return n.addCustom("drag-data",()=>new V$)}function e2(n,t){if(!t)return null;const e=Nf(n).getData();return!e||e.editorId!==n.id?null:e}function K7(n,t){const e=e2(n,t);return e?n.findBlockById(e.blockId):null}function W$(n,t,e){if(!t.dataTransfer)return;const r=nt(e),i=at(r),s=it(e),l={type:"block",editorId:n.id,containerId:i,blockId:s};Nf(n).setData(l)}function q$(n,t,e,o,r){if(!t.dataTransfer)return;const s=nt(e),l=at(s),a=it(e),d={type:"custom",customType:o,editorId:n.id,containerId:l,blockId:a,data:r};Nf(n).setData(d)}function G$(n){Nf(n).clearData()}const Z$=S("drop-indicator"),$f=2;class Q${constructor(t){m(this,"indicator");m(this,"target",null);this.editor=t,this.indicator=w("div",["editor-drop-indicator"],this.editor.contentElement)}show(t,e){const o=this.getIndicatorRect(t,e),r=this.editor.rootElement.getBoundingClientRect(),i=o.top-r.top,s=o.left-r.left;this.indicator.style.top=`${i}px`,this.indicator.style.left=`${s}px`,this.indicator.style.width=`${o.width}px`,this.indicator.style.height=`${o.height}px`,this.indicator.style.display="",this.target={block:t,insertPos:e}}hide(){this.indicator.style.display="none",this.target=null}getIndicatorRect(t,e){if(typeof e!="string")return e.rect;if(e==="before"){const s=Ts(t);if(!s){g(Z$,Lo(nt(t)),"block does not in a child container");const d=t.getBoundingClientRect();return new DOMRect(d.x,d.y,d.width,$f)}const l=s.getBoundingClientRect(),a=t.getBoundingClientRect();return new DOMRect(l.x,(l.bottom+a.top)/2,l.width,$f)}const o=Ds(t);if(!o){const s=t.getBoundingClientRect();return new DOMRect(s.x,s.bottom,s.width,$f)}const r=t.getBoundingClientRect(),i=o.getBoundingClientRect();return new DOMRect(r.x,(r.bottom+i.top)/2,r.width,$f)}}const Y$=S("find-drop-target");function J$(n,t){const e=document.elementFromPoint(n,t);if(!e)return null;if(Pr(e)&&Lo(e))return e;const o=e.firstElementChild;return o&&Pr(o)&&Lo(o)?o:null}function K$(n,t){const s=t,l=n;for(let a=0;a<2;a++){const d=l+a*50;for(let h=0;h<5;h++){const p=s+h*8,A=document.elementFromPoint(d,p);if(A){const D=et(A);if(D)return D}if(h===0)continue;const v=s-h*8,B=document.elementFromPoint(d,v);if(B){const D=et(B);if(D)return D}}}return null}function X$(n,t,e){const o=document.elementFromPoint(t,e);if(o){const h=et(o);if(h&&!Mt(n,h))return h}const r=new Set,i=J$(t,e);if(i){const h=i.getBoundingClientRect();e<h.top+h.height/2?r.add(Le(i)):r.add(Qe(i))}const s=K$(t,e);s&&r.add(s);const l=Array.from(r),a=h=>{for(let p=0;p<l.length;p++){const A=l[p];if(h!==A&&Kt(h,A))return!0}return!1},d=l.filter(h=>!a(h));return d.length>0?d[0]:null}function n2(n,t){if(n.readonly)return!1;const e=nt(t);if(Xt(e))return!0;const o=et(e);return g(Y$,o,"no parent block"),n.isBlockWritable(o)?n2(n,o):!1}const tH=S("drop-target");function eH(n,t){let e={};return/image/.test(t.type)?e=n.editorEmbeds.getEmbedClass("image"):/audio/.test(t.type)?e=n.editorEmbeds.getEmbedClass("audio"):/video/.test(t.type)&&(e=n.editorEmbeds.getEmbedClass("video")),g(tH,e,`unSupport file type ${t.type}`),e}async function X7(n,t,e,o){var i,s;let r=o;for(const l of t){const a=eH(n,l);a.getOptions&&await((s=(i=a.getOptions(n)).handleInsertEmptyEmbed)==null?void 0:s.call(i,n,{containerId:e,blockIndex:r,data:{file:l}}))&&(r+=1)}}class nH{constructor(t){m(this,"handleDrop",(t,e,o,r)=>{if(Array.isArray(e)){const i=e;if(i.length>0){const s=at(o);return X7(t,i,s,r),!0}}return!1});this.editor=t}}class Su{constructor(t){m(this,"indicator");m(this,"lastDropOverResult");m(this,"handlers",[]);m(this,"handleDragOver",t=>{if(!this.editor.isWritable())return;const e=i=>{var d,h;const s=e2(this.editor,i.dataTransfer),l=K7(this.editor,i.dataTransfer),a=this.findTargetBlock(l,i.x,i.y);if(a&&Kt(this.editor.rootContainer,a)){const p=this.findInsertPos(l,a,i.x,i.y,(h=s!=null?s:(d=i.dataTransfer)==null?void 0:d.items)!=null?h:null);if(p)return this.indicator.show(a,p),"move"}return this.indicator.hide(),"none"},o=(i,s)=>{i.dataTransfer&&(i.dataTransfer.dropEffect=s),s==="move"&&i.preventDefault()};if(this.lastDropOverResult&&t.x===this.lastDropOverResult.x&&t.y===this.lastDropOverResult.y){const i=this.lastDropOverResult.dropEffect;o(t,i);return}const r=e(t);o(t,r),this.lastDropOverResult={x:t.x,y:t.y,dropEffect:r}});m(this,"handleDrop",t=>{var i,s;t.stopPropagation(),setTimeout(()=>{this.indicator.hide()});const e=e2(this.editor,t.dataTransfer),o=Array.from((s=(i=t.dataTransfer)==null?void 0:i.files)!=null?s:[]);if(!e&&o.length===0){t.dataTransfer&&(t.dataTransfer.dropEffect="none");return}const r=this.indicator.target;if(r){const{block:l,insertPos:a}=r,d=K7(this.editor,t.dataTransfer);this.editor.undoManager.runInGroup(()=>{const h=Qt(this.editor,l);if(h.handleDrop&&h.handleDrop(this.editor,l,e!=null?e:o,a,{isSourceBlock:!1,targetBlock:l})){t.preventDefault(),this.editor.focus();return}if(d){const p=Qt(this.editor,d);if(p.handleDrop&&p.handleDrop(this.editor,d,e!=null?e:o,a,{isSourceBlock:!0,targetBlock:l})){t.preventDefault(),this.editor.focus();return}}if(typeof a=="string"){const p=nt(l);let A=bt(l);a==="after"&&(A+=1),t.preventDefault();for(let v=0;v<this.handlers.length;v++)if(this.handlers[v].handleDrop(this.editor,d!=null?d:o,p,A)){this.editor.focus();return}if(d){const v=this.editor.getBlockData(d),B=Fi(this.editor.editorBlocks,this.editor.doc.toJSON(),v),[D]=this.editor.insertDocAt(p,A,B);this.editor.selection.selectBlock(D,0),Du.get(this.editor).highlightBlock(D),this.editor.deleteBlock(d),this.editor.focus()}}}),G$(this.editor)}});m(this,"handleDragLeave",()=>{this.indicator.hide()});this.editor=t,this.indicator=new Q$(this.editor),this.handlers.push(new nH(this.editor)),this.editor.contentElement.addEventListener("dragover",this.handleDragOver),this.editor.contentElement.addEventListener("dragleave",this.handleDragLeave),this.editor.contentElement.addEventListener("drop",this.handleDrop)}destroy(){this.editor.contentElement.removeEventListener("dragover",this.handleDragOver),this.editor.contentElement.removeEventListener("dragleave",this.handleDragLeave),this.editor.contentElement.removeEventListener("drop",this.handleDrop),this.handlers=[]}addHandler(t){this.handlers.push(t)}static register(t){return t.addCustom("drop-target",()=>new Su(t))}static get(t){return t.getCustom("drop-target")}static find(t){return t.findCustom("drop-target")}canInsertAfter(t,e){return!(this.editor.readonly||Ds(e)===t&&t||!n2(this.editor,e))}canInsertBefore(t,e){return!(this.editor.readonly||Ts(e)===t&&t||!n2(this.editor,e)||Xt(nt(e))&&bt(e)===0)}canDrop(t,e){return t===null||t===e?!0:!Kt(t,e)}findTargetBlock(t,e,o){let r=X$(this.editor,e,o);if(!r||!Kt(this.editor.rootContainer,r))return null;const i=nt(r),s=et(i);return s&&Dt(s)==="code"&&(r=s),this.canDrop(t,r)?r:null}findInsertPos(t,e,o,r,i){let s=e;for(;s;){const a=Qt(this.editor,s);if(a.handleDropOver){const d=a.handleDropOver(this.editor,s,i,o,r);if(d)return d;if(d===!1)return null}s=xs(s)}if(t===e)return"";const l=e.getBoundingClientRect();if(l.top<=r&&r<=l.bottom){if(r<l.top+l.height/2){if(this.canInsertBefore(t,e))return"before";if(this.canInsertAfter(t,e))return"after"}else{if(this.canInsertAfter(t,e))return"after";if(this.canInsertBefore(t,e))return"before"}return""}return r<l.top&&this.canInsertBefore(t,e)?"before":l.bottom<r&&this.canInsertAfter(t,e)?"after":""}}function ty(n,t,e){const o=xe.getImageObject(n,t),r=mt.default(o.getImages());if(r.length===1){n.deleteBlock(t);return}if(e===-1||e>=r.length)return;const i=UN(r);if(r.splice(e,1),r.length===1){const l=r[0],a=100*(l.flex/i);l.flex=1;const d=cn([l],a);n.updateEmbedData(t,d);return}r[0].flex=NaN,ku(r);const s=cn(r,o.getWidthPercent());n.updateEmbedData(t,s)}function oH(n,t,e,o){if(t.length===0||o==="after"||o==="before")return!1;let r=o.data;const i=xe.getImageObject(n,e),s=mt.default(i.getImages()),l=[],a=[];t.forEach(p=>{H7(p.type)&&s.length+l.length<6?l.push(p):a.push(p)}),l.forEach(p=>{try{$7(n,p)}catch{return}const A={src:"",flex:1,width:0,height:0,virtualSize:!0};s.splice(r,0,A);const v=cn(s,i.getWidthPercent());n.updateEmbedData(e,v),i.replaceImage(r,p),r+=1});const d=n.getBlockIndex(e)+1,h=at(nt(e));return X7(n,a,h,d),!0}function rH(n,t,e,o,r){var s,l,a;if(qd(e))return oH(n,e,t,o);if(e.type!=="custom"||e.customType!=="image"||!e.data)return;const i=e.data;if(r.isSourceBlock){const d=r.targetBlock,h=nt(d);let p=bt(d);o==="after"&&(p+=1);const v=100*(i.boundingRect.width/n.rootContainer.getBoundingClientRect().width),B=cn([i.image],v),D={id:K(),type:"embed",embedType:"image",embedData:B},x=(l=(s=n.options.componentsOptions)==null?void 0:s.image)==null?void 0:l.defaultAlign;x&&(D.align=x),n.insertBlock(at(h),p,D),ty(n,t,i.index),(a=n.findCustom("drag-handler"))==null||a.handleDragEnd()}else{if(typeof o=="string")return;const d=t;let h=o.data;const p=xe.getImageObject(n,d),A=mt.default(p.getImages());h>A.length&&(h=A.length),n.undoManager.runInGroup(()=>{var B,D;p.setAutoFix(!0);const v=n.getBlockById(e.blockId);if(v===d){const x=i.index,_=h,M=i.image;if(x===_||_===x+1)return;let H=_;x<_?(A.splice(_,0,M),A.splice(x,1),H-=1):(A.splice(x,1),A.splice(_,0,M));const z=cn(A,p.getWidthPercent());n.updateEmbedData(d,z),p.setSelectedIndex(H),(B=n.findCustom("drag-handler"))==null||B.handleDragEnd()}else{A.splice(h,0,i.image),A[0].flex=NaN,ku(A);const x=cn(A,p.getWidthPercent());n.updateEmbedData(d,x),ty(n,v,i.index),(D=n.findCustom("drag-handler"))==null||D.handleDragEnd(),p.setSelectedIndex(h),n.selection.selectBlock(d,0)}})}return!0}const iH=2;function Hf(n,t,e){const o=Cr(t);if(e<=0){const s=o[0].getBoundingClientRect();return new DOMRect(s.left-4,s.top,2,s.height)}if(e===o.length){const s=o[e-1].getBoundingClientRect();return new DOMRect(s.right+2,s.top,2,s.height)}const r=o[e-1].getBoundingClientRect(),i=o[e].getBoundingClientRect();return new DOMRect((i.left+r.right)/2-1,r.top,iH,r.height)}function sH(n,t,e,o,r){for(let i=0;i<e.length;i++){const l=e[i].getBoundingClientRect();if(o<=l.right)return o<=l.left+l.width/2?{rect:Hf(n,t,i),data:i}:{rect:Hf(n,t,i+1),data:i+1}}return o>e[e.length-1].getBoundingClientRect().right?{rect:Hf(n,t,e.length),data:e.length}:{rect:Hf(n,t,e.length),data:0}}function lH(n,t,e,o,r){const i=Cr(t);if(e instanceof DataTransferItemList){if(!Array.from(e).some(s=>H7(s.type))||i.length>=6)return}else{if((e==null?void 0:e.type)==="block"||i.length>=6&&(e==null?void 0:e.blockId)!==it(t))return;const s=it(t);if(i.length===1&&s===(e==null?void 0:e.blockId))return}return sH(n,t,i,o)}async function cH(n){return await G5.default.toSvg(n)}function o2(n,t){return new DragEvent(t,{bubbles:!0,cancelable:!0,view:window,screenX:n.screenX,screenY:n.screenY,dataTransfer:new DataTransfer,clientX:n.clientX,clientY:n.clientY})}class aH{constructor(t){m(this,"img");m(this,"dragContainer",null);m(this,"autoScroll",null);m(this,"imageContainer",null);m(this,"startPosition",null);m(this,"handleMouseDown",t=>{const e=t.target;if(!e||!(e instanceof HTMLImageElement))return;const o=et(e);if(!o||!Wo(o)||!this.editor.isBlockWritable(o)||this.editor.readonly)return;const r=xe.getImageObject(this.editor,o);if(this.imageContainer=W0(t.target),!this.imageContainer)return;const s=R7(t.target).indexOf(this.imageContainer);if(s===-1)return;const l=r.getImages()[s];if(!l)return;const{x:a,y:d}=t;this.startPosition={x:a,y:d};const h={image:l,index:s,boundingRect:this.imageContainer.getBoundingClientRect()},p=o2(t,"dragstart");q$(this.editor,p,o,"image",h),document.addEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.addEventListener("mousemove",this.handleDrag),t.preventDefault()});m(this,"handleDragStart",async t=>{if(!this.imageContainer)return;const e=et(this.imageContainer);if(!e)return;const{x:o,y:r}=t,{width:i,height:s}=t.target.getBoundingClientRect(),l=te(e),a=w("div",["drag-container"],l);a.style.left=`${o-i/4}px`,a.style.top=`${r-s/4}px`,a.style.width=`${Math.max(i/2,16)}px`,a.style.height=`${s/2}px`,this.dragContainer=a;const d=w("img",["drag-target"],a),p=await cH(this.imageContainer);p&&(d.src=p),W(this.editor.contentElement,"dragging");const A=ro(e);this.autoScroll=new Zd({scrollElement:A,trackMouseEvent:"mousemove",edge:{top:50,bottom:50}}),this.autoScroll.active()});m(this,"handleDrag",t=>{var i;const{x:e,y:o}=t;if(((i=this.startPosition)==null?void 0:i.x)===e&&this.startPosition.y===o)return;if(window.isDragging||(window.isDragging=!0,this.handleDragStart(t)),this.startPosition&&this.dragContainer){const{x:s,y:l}=t;if(s===0&&l===0){this.dragContainer.style.transform="",this.dragContainer.style.opacity="0";return}const{x:a,y:d}=this.startPosition,h=s-a,p=l-d;this.dragContainer.style.transform=`translate(${h}px, ${p}px)`,this.dragContainer.style.opacity="0.5"}const r=o2(t,"dragover");this.editor.contentElement.dispatchEvent(r)});m(this,"handleDragEnd",t=>{var e;if(window.isDragging=!1,this.dragContainer&&this.dragContainer.remove(),this.dragContainer=null,this.startPosition=null,this.imageContainer=null,(e=this.autoScroll)==null||e.inactive(),ot(this.editor.contentElement,"dragging"),document.removeEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.removeEventListener("mousemove",this.handleDrag),t){const o=o2(t,"drop");this.editor.contentElement.dispatchEvent(o)}});this.editor=t,this.editor.rootContainer.addEventListener("mousedown",this.handleMouseDown),this.img=new Image,this.img.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"}destroy(){this.editor.rootContainer.removeEventListener("mousedown",this.handleMouseDown)}}class uH{constructor(t){m(this,"handleFocusBlockChanged",(t,e,o)=>{const i=this.editor.getFocusedBlock();if(i&&Wo(i)){const s=xe.getImageObject(this.editor,i);s.getImages().length>0&&s.getSelectedIndex()===-1&&s.setSelectedIndex(0)}o&&Wo(o)&&xe.getImageObject(this.editor,o).blockResizer.disableResize()});this.editor=t,this.editor.addListener("focusBlockChanged",this.handleFocusBlockChanged)}destroy(){this.editor.removeListener("focusBlockChanged",this.handleFocusBlockChanged)}}class dH{constructor(t){m(this,"currentResizer",null);m(this,"handleHoveringBlockChange",(t,e)=>{e&&this.disable(e),t&&(this.currentResizer=t,this.enable(t))});this.editor=t,Ce.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){Ce.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disable(t){Wo(t)&&xe.getImageObject(this.editor,t).disableResizer()}enable(t){if(Wo(t)){const e=xe.getImageObject(this.editor,t);this.editor.isBlockWritable(t)&&e.tryEnableResizer()}}}const hH={image:{title:"\u56FE\u7247",upload:{failed:'<div class="line-1">\u56FE\u7247\u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <a href="" class="retry-upload">\u91CD\u8BD5</a></div>'},load:{failed:'<div class="line-1">\u56FE\u7247\u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <a href="" class="retry-upload">\u91CD\u8BD5</a></div>',remote:{failed:'<div class="line-1">\u56FE\u7247\u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u8BE5\u56FE\u7247\u6765\u81EA\u5916\u90E8\u94FE\u63A5\uFF0C\u5916\u90E8\u94FE\u63A5\u5DF2\u5931\u6548</div><div class="line-3">\u8BF7\u5C06\u539F\u56FE\u4FDD\u5B58\u5230\u672C\u5730\u540E\u4E0A\u4F20\uFF0C <a href="" class="retry-upload">\u6253\u5F00\u56FE\u7247\u94FE\u63A5</a></div>',tooltip:"\u8BE5\u56FE\u7247\u6765\u81EA\u5916\u90E8\u94FE\u63A5\uFF0C\u5982\u679C\u94FE\u63A5\u5931\u6548\u56FE\u7247\u5C06\u65E0\u6CD5\u67E5\u770B\uFF0C\u5EFA\u8BAE\u4FDD\u5B58\u5230\u672C\u5730\u540E\u6DFB\u52A0\u5230\u9875\u9762\u4E2D"}},abstract:"\u56FE\u7247"}},fH={image:{title:"Image",upload:{failed:'<div class="line-1">Image upload failed</div><div class="line-2">Network error, you can <a href="" class="retry-upload">Retry</a></div>'},load:{failed:'<div class="line-1">Image failed to load</div><div class="line-2">Network error, you can <a href="" class="retry-upload">Retry</a></div>',remote:{failed:'<div class="line-1">Failed to load image</div><div class="line-2">This picture is from an expired external link</div><div class="line-3">Please save the original image to local drives and upload it. <a href="" class="retry-upload">Open image link</a></div>',tooltip:"This picture is from an external link. If the link expires, the picture will not be available. It's recommended to save it to local drives and add it to the page."}},abstract:"Image"}},mH={image:{title:"\u753B\u50CF",upload:{failed:'<div class="line-1">\u753B\u50CF\u3092\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <a href="" class="retry-upload">\u518D\u8A66\u884C</a></div>'},load:{failed:'<div class="line-1">\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <a href="" class="retry-upload">\u518D\u8A66\u884C</a></div>',remote:{failed:'<div class="line-1">\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u3053\u306E\u753B\u50CF\u306B\u30EA\u30F3\u30AF\u3057\u3066\u3044\u308B URL \u304C\u7121\u52B9\u306B\u306A\u3063\u3066\u3044\u307E\u3059\u306E\u3067\u3001\u8868\u793A\u3067\u304D\u307E\u305B\u3093</div><div class="line-3">\u753B\u50CF\u3092\u30ED\u30FC\u30AB\u30EB\u306B\u4FDD\u5B58\u3057\u3066\u30A2\u30C3\u30D7\u30ED\u30FC\u30C0\u3057\u3066\u304F\u3060\u3055\u3044 <a href="" class="retry-upload">\u753B\u50CF\u30EA\u30F3\u30AF\u3092\u958B\u304F</a></div>',tooltip:"\u3053\u306E\u753B\u50CF\u306F\u5916\u90E8\u306B\u30EA\u30F3\u30AF\u3057\u3066\u3044\u308B\u305F\u3081\u3001\u30EA\u30F3\u30AF\u304C\u7121\u52B9\u306B\u306A\u308B\u3068\u3001\u8868\u793A\u3067\u304D\u306A\u304F\u306A\u308A\u307E\u3059\u306E\u3067\u3001\u30ED\u30FC\u30AB\u30EB\u306B\u4FDD\u5B58\u3057\u3001\u30DA\u30FC\u30B8\u306B\u633F\u5165\u3059\u308B\u3053\u3068\u3092\u304A\u52E7\u3081\u3057\u307E\u3059"}},abstract:"\u753B\u50CF"}};R.mergeLang({"zh-CN":hH,"en-US":fH,"ja-JP":mH});function gH(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=In(i,o),l=ie(s);let a=o;if(l.endsWith("![]()"))a-=5;else if(l.endsWith("![]"))a-=3;else return!1;const d=o;return Ul("image/*").then(h=>{n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,a,d-a);let p=e+1;ie(n.getBlockText(r)).trim()?(Ql(n,r,a,{forceInsertAfter:!0}),a===0&&(n.deleteBlock(r),p--)):(n.deleteBlock(r),p--),Wm(n,"image",t,p,{file:h})})}),!0}class pH{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&gH(t,e,o,r))}}function CH(n){const t=n.getFocusedBlock(),e=Ds(t);if(e&&Wo(e)){n.selection.selectBlock(e,0);const o=xe.getImageObject(n,e);return o.getImages().length>0&&o.setSelectedIndex(0),!0}}function AH(n){const t=n.getFocusedBlock(),e=Ts(t);if(e&&Wo(e)){n.selection.selectBlock(e,0);const o=xe.getImageObject(n,e);return o.getImages().length>0&&o.setSelectedIndex(0),!0}}function bH(n){const e=n.getFocusedBlock();if(e&&Wo(e)){const o=xe.getImageObject(n,e),r=o.getImages();if(r.length>0){const i=o.getSelectedIndex();if(i===-1)return o.setSelectedIndex(r.length-1),!0;if(i>0)return o.setSelectedIndex(i-1),!0}}}function vH(n){const e=n.getFocusedBlock();if(e&&Wo(e)){const o=xe.getImageObject(n,e),r=o.getImages();if(r.length>0){const i=o.getSelectedIndex();if(i===-1)return o.setSelectedIndex(0),!0;if(i<r.length-1)return o.setSelectedIndex(i+1),!0}}}function r2(n){const e=n.getFocusedBlock();if(e&&Wo(e)){const o=xe.getImageObject(n,e);if(o.getImages().length>0){const i=o.getSelectedIndex();if(i!==-1)return o.removeImage(i),!0}}}const yH={ArrowLeft:bH,ArrowRight:vH,ArrowUp:AH,ArrowDown:CH,Delete:r2,Backspace:r2},kH=S("copy-image");function wH(n,t,e,o){const r=e.getImages()[o],i=e.getImages().length===1?e.getWidthPercent():r.flex*100,s=cn([r],i),l={id:K(),type:"embed",embedType:"image",embedData:s},a=n.options.componentsOptions.image;a!=null&&a.defaultAlign&&(l.align=a.defaultAlign);const d={blocks:{root:[l]},comments:{},meta:{}},h=document.createElement("canvas");h.width=t.naturalWidth,h.height=t.naturalHeight;const p=h.getContext("2d");if(!p)return;const A={},v={};try{p.drawImage(t,0,0,h.width,h.height);const z=h.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/,""),q=Tm(z),rt=new File([q],`${Date.now()}.png`,{type:"image/png"});A["image/png"]=rt}catch(H){kH.error(H)}Oh(n,d);const D=`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`,x=Rh(D,d),_=Ma(n,d);A["text/plain"]=new Blob([_],{type:"text/plain"}),v["text/plain"]=_;const M=new Blob([x],{type:"text/html"});return A["text/html"]=M,v["text/html"]=x,[A,v]}function BH(n,t,e,o,r){const i=wH(n,t,e,o);if(!i)return;const[s,l]=i;if(s){const a=Object.entries(s).map(([d,h])=>({type:d,data:h}));return Lm(a).then(d=>{if(!d&&r){const h=r.clipboardData;h&&(h.setData("text/plain",l["text/plain"]),h.setData("text/html",l["text/html"]))}}),!0}}function ey(n,t){const e=n.selection.range;if(e.start.blockId!==e.end.blockId)return;const r=n.getFocusedBlock();if(r&&Wo(r)){const i=xe.getImageObject(n,r);if(i.getImages().length>0){const l=i.getSelectedIndex();if(l!==-1){const d=Cr(r)[l].querySelector("img");if(d)return BH(n,d,i,l,t)}}}}class EH{constructor(t){this.editor=t,setTimeout(()=>{this.editor.input.addHandler(this)})}handleBeforeCopy(t,e,o){if(ey(t,e))return!0}handleBeforeCut(t,e){if(ey(t,e))return r2(t),!0}destroy(){}}class i2{constructor(t){this.editor=t,setTimeout(()=>{this.editor.input.addHandler(this)})}async handleAfterPasteDoc(t,e,o){return Object.values(e.blocks).forEach(r=>{r.forEach(i=>{if(i.type==="embed"&&i.embedType==="image"){const s=i.embedData;if(Array.isArray(s.src))return;if(s.src.startsWith("https:")||s.src.startsWith("http:")){const l=o.blockIdMap.get(i.id);l&&Ji(t,l).setAutoFix(!0)}}})}),!1}destroy(){}}const xH=S("image-embed");function IH(n,t,e,o,r,i){xe.create(n,e).createContent(r,i,t),n.addCustom("image-select-handler",()=>new uH(n)),n.addCustom("image-copy-handler",()=>new EH(n)),setTimeout(()=>{n.addCustom("drag-handler",()=>new aH(n));const l=n.addCustom("image-resizer",()=>new dH(n)),a=e.embedData;yc(a)?l.disable(i):l.currentResizer===i&&l.enable(i)})}function TH(n,t,e,o){const r=t.embedData,i=kc(r);return o==="html"?i.map(s=>`<img src="${n.doc.buildResourceUrl(s.src,{withToken:!0})}">`).join(""):o==="markdown"?`${i.map(l=>`})`).join(`
|
|
424
424
|
`)}
|
|
425
425
|
`:i.map(s=>n.doc.buildResourceUrl(s.src,{withToken:!0})).join(`
|
|
426
|
-
`)}class DH{constructor(){m(this,"group","image");m(this,"commands",[])}executeCommand(t,e,o){if(o.id==="replace-image"){const{block:r,image:i}=o.data;xe.getImageObject(t,r).replaceImage(0,i)}}}function SH(){return{blockCommands:{image:new DH},abstract:`${R.t("image.abstract")}`}}function LH(){return{name:"Image",insertEmbedCommandItems:[{id:"insert-image",name:R.t("image.abstract"),icon:LL,group:"common",subText:"/image",order:100}],handleInsertEmptyEmbed:async(n,t)=>{var v;let e;(v=t.data)!=null&&v.file&&(e=t.data.file);const o=N7(n);if(e=e!=null?e:await Ul(o),!e)return null;try{$7(n,e)}catch{return null}let r={width:w7,height:j0};try{r=await u$(e)}catch(B){xH.error(B)}const i=n.rootContainer.clientWidth,s=r.width<i?Math.min(100,r.width/i*100):100,l={src:"",width:r.width,height:r.height,flex:1,virtualSize:!1},a=cn([l],s),d={id:K(),type:"embed",embedType:"image",embedData:a},h=n.options.componentsOptions.image;h!=null&&h.defaultAlign&&(d.align=h.defaultAlign);const p=n.insertBlock(t.containerId,t.blockIndex,d);return xe.getImageObject(n,p).replaceImage(0,e),p}}}function MH(n,t,e){var h;const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="image"||!tt(n,t))return null;const i=r.match(/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/),s=(h=i==null?void 0:i.groups)==null?void 0:h.filename;if(!s)return null;const l={src:s},a={id:K(),type:"embed",embedType:"image",embedData:l};xe.create(n,a).setAutoFix(!0);const d=n.options.componentsOptions.image.defaultAlign;return d&&(a.align=d),{blockData:a}}function RH(n,t){const e=it(t);n.destroyCustom(`image-${e}`)}const ny={embedType:"image",createEmbedContent:IH,convertTo:TH,convertFrom:MH,getBlockProperties:SH,getOptions:LH,handleDrop:rH,handleDropOver:lH,handleDeleteBlock:RH};class OH{constructor(t,e){m(this,"toolbar");m(this,"anchor",null);m(this,"item");m(this,"docs",null);m(this,"checkedId");m(this,"handlePasteSpecial",(t,e)=>{!e.data||(this.checkedId===e.id?this.checkedId=void 0:this.checkedId=e.id,this.onPasteSpecial(e.data),setTimeout(()=>{this.docs&&this.show(this.docs),this.editor.focus()}))});m(this,"handleClose",()=>{this.editor.focus()});m(this,"handleSelectionChange",()=>{this.handleClose()});this.editor=t,this.onPasteSpecial=e,this.item={id:"paste-special",name:"",icon:ML,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",childrenOffset:[-4,4],children:[]},this.toolbar=new ou([this.item],void 0,{id:"paste-special-button",tooltipId:this.editor.clientId,refuseOverflow:!0}),this.toolbar.addListener("click",this.handlePasteSpecial),this.toolbar.addListener("close",this.handleClose),this.editor.addListener("selectionChanged",this.handleSelectionChange)}show(t){this.docs=t;const e=this.editor,o=e.selection.range;if(!o.isCollapsed())return;const r=e.getBlockById(o.start.blockId);if(!tt(e,r))return;const i=Nr(e,r,o)[0];if(!i)return;this.anchor&&this.anchor.remove(),this.anchor=zr(e,r,"paste-special-button-anchor",i);const s=this.getCommandItems(t);this.item.children=s,this.toolbar.manualShow(this.anchor)}hide(){this.toolbar.close("selectionChange")}clearCheckedState(){this.checkedId=void 0}destroy(){this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange)}getCommandItems(t){const e=i=>({id:i,states:this.checkedId===i?["checked"]:void 0,name:R.t("pasteSpecial.originFormats"),data:t[i]}),o=[];let r=!0;return t["text/x-ones-editor-doc"]?o.push(e("text/x-ones-editor-doc")):t["text/office-html"]?o.push(e("text/office-html")):t["text/html"]?o.push(e("text/html")):t["text/plain"]&&(o.push(e("text/plain")),r=!1),t["text/plain"]&&(r&&o.push({id:"text/plain",states:this.checkedId==="text/plain"?["checked"]:void 0,name:R.t("pasteSpecial.plainText"),data:t["text/plain"]}),o.push({id:"text/markdown",states:this.checkedId==="text/markdown"?["checked"]:void 0,name:R.t("pasteSpecial.markdown"),data:t["text/markdown"]})),o}}const _H=S("paste-special");class s2{constructor(t){m(this,"button");m(this,"lastUndoAction",null);m(this,"event",null);m(this,"handlePasteSpecial",t=>{this.editor.undoManager.runInGroup(()=>{this.editor.undoManager.undoTo(this.lastUndoAction),this.editor.pasteDoc(t)})});this.editor=t,this.button=new OH(t,this.handlePasteSpecial)}destroy(){this.event=null,this.button.destroy()}handleChanged(t,e){this.event=null,this.button.hide()}async handleBeforePaste(t,e){return _H.debug("before paste"),this.lastUndoAction=t.undoManager.lastAction(),!1}async handleAfterPaste(t,e,o){if(Object.keys(o).length<=1)return!1;const r=t.selection.range;if(r.isCollapsed()){const i=t.getBlockById(r.start.blockId);if(!tt(t,i))return!1;this.button.clearCheckedState(),this.button.show(o),this.event=e}return!1}}const FH={pasteSpecial:{originFormats:"\u4FDD\u6301\u539F\u6837\u5F0F",plainText:"\u7C98\u8D34\u7EAF\u6587\u672C",markdown:"\u7C98\u8D34\u4E3A Markdown"}},PH={pasteSpecial:{originFormats:"Keep origin formats",plainText:"Paste as plain text",markdown:"Paste as markdown"}},NH={pasteSpecial:{originFormats:"\u5143\u306E\u30B9\u30BF\u30A4\u30EB\u3092\u7DAD\u6301\u3059\u308B",plainText:"\u30D7\u30EC\u30FC\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u8CBC\u308A\u4ED8\u3051\u308B",markdown:"Markdown \u3068\u3057\u3066\u8CBC\u308A\u4ED8\u3051"}};R.mergeLang({"zh-CN":FH,"en-US":PH,"ja-JP":NH});const Unt="",$H=S("html-to-doc");function HH(n){const t=new RegExp('(?<=<div id="ones-editor-doc">)[\\s\\S]*(?=<\\/div>)',"g"),e=n.match(t);if(!e||!e.length)return null;const o=e[0],r=pa(o);return JSON.parse(r)}function jH(n){const t="ones-editor-doc::",e="::ones-editor-doc";let o=n.indexOf(t);if(o!==-1){o+=t.length;const i=n.indexOf(e,o);if(i!==-1){const s=n.substr(o,i-o);try{const l=pa(s);return JSON.parse(l)}catch(l){$H.error(`invalid doc data: ${l}, ${s}`)}}}const r=HH(n);return r||null}const oy="latex-b172fea480b",UH=n=>({name:"latex-block",level:"block",start(t){var e,o;return(o=(e=t.match(/\$\$[^\$]/))==null?void 0:e.index)!=null?o:-1},tokenizer(t,e){const o=/^\$\$([^\$]+)\$\$/.exec(t);return o?{type:"latex-block",raw:o[0],formula:o[1]}:void 0},renderer(t){return n.lazy?`<span class="${oy}" block>${t.formula}</span>`:n.render(t.formula,!0)}}),zH=n=>({name:"latex",level:"inline",start(t){var e,o;return(o=(e=t.match(/\$[^\$]/))==null?void 0:e.index)!=null?o:-1},tokenizer(t,e){const o=/^\$([^\$]+)\$/.exec(t);return o?{type:"latex",raw:o[0],formula:o[1]}:void 0},renderer(t){return n.lazy?`<span class="${oy}">${t.formula}</span>`:n.render(t.formula,!1)}});var VH=(n={})=>(n.lazy&&n.env!=="test"&&new IntersectionObserver((t,e)=>{for(const o of t){if(!o.isIntersecting)continue;const r=o.target;e.unobserve(r),Promise.resolve(n.render(r.innerText,r.hasAttribute("block"))).then(i=>{r.innerHTML=i}),r.classList.add("latex-rendered")}},{threshold:1}),{extensions:[UH(n),zH(n)]});function wc(n){const t=n.type;if(t==="link")return!!n.tokens.some(wc);switch(t){case"code":case"table":case"hr":case"blockquote":case"list":case"list_item":case"image":case"paragraph":return!0;default:return!1}}function WH(n){return!wc(n)}function qH(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=wc(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===wc(i)?e.push(i):(t.push(e),e=[i],o=wc(i))}return t.push(e),t}function GH(n,t,e){const o=n.href;let r=e.tokensToText(n.tokens,t,e);return r.length===0&&(r=Oi(o,t)),r=hh(r,"link",o),r}let Lu;function l2(n){Lu||(Lu=document.createElement("textarea")),Lu.innerHTML=n;const t=Lu.childNodes.length===0?"":Lu.childNodes[0].nodeValue;return t!=null?t:""}function ZH(n,t){const e=l2(n.text);return[co(e,{...t,"style-code":!0})]}function QH(n,t,e){const r=n.tokens;return r?e.tokensToText(r,t,e):lg(l2(n.text),t)}const YH=S("token-to-text");function c2(n,t,e){return n.map(r=>r.type==="text"?QH(r,t,e):r.type==="strong"?e.tokensToText(r.tokens,{...t,"style-bold":!0},e):r.type==="em"?e.tokensToText(r.tokens,{...t,"style-italic":!0},e):r.type==="del"?e.tokensToText(r.tokens,{...t,"style-strikethrough":!0},e):r.type==="link"?GH(r,t,e):r.type==="codespan"?ZH(r,t):r.type==="br"?[{insert:" ",attributes:{id:K(),created:Date.now(),box:!0,type:"br"}}]:r.type==="escape"?lg(l2(r.text),t):r.type==="latex"?[{insert:" ",attributes:{id:K(),created:Date.now(),box:!0,type:"math",tex:r.formula}}]:(YH.warn(`unknown token in text: ${JSON.stringify(r)}`),[])).flat()}function JH(n,t){const e=c2(n.tokens,{},t);return[{id:K(),type:"text",text:e,heading:n.depth}]}function KH(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function XH(n,t){const{text:e,children:o}=t.tokensToTextWithChildren([n],t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function tj(n,t){const e=typeof n.start=="number"?n.start:1,o=n.ordered,r=K(),i=[];return n.items.forEach((l,a)=>{const d={...t,listLevel:t.listLevel+1},{text:h,children:p}=t.tokensToTextWithChildren(l.tokens,d);let A;typeof l.checked=="boolean"&&(A=l.checked?"checked":"unchecked");const v={id:K(),type:"list",groupId:r,ordered:o,checkbox:A,start:e+a,text:h,level:t.listLevel};i.push(v),i.push(...p)}),i}function ej(n,t){const e=t.tokensToBlocks(n.tokens,t);return e.forEach(o=>{o.quoted=!0}),e}const ry=100,nj=20,oj=600;function rj(n,t){const e=t.text;if(e){const o=ie(e);return Math.min(Wd(o,n)+nj,oj)}return ry}function iy(n,t){let e=ry;return t.forEach(o=>{e=Math.max(e,rj(n,o))}),e}function ij(n,t){var l,a;const e=n.header.length,o=n.rows.length+1,r=[],i=Array(e).fill(100);for(let d=0;d<o;d++){let h;d===0?h=n.header:h=n.rows[d-1];for(let p=0;p<e;p++){const A=h[p],v=(l=A==null?void 0:A.tokens)!=null?l:[],B=K();r.push(B);let D;if(v.length===0)D=[mh()];else if(wc(v[0]))D=t.tokensToBlocks(A.tokens,t),D.length===0&&D.push(mh());else{const{text:x,children:_}=t.tokensToTextWithChildren(A.tokens,t);D=[{id:K(),type:"text",text:x},..._]}t.doc.blocks[B]=D,i[p]=Math.max(i[p],iy((a=t.font)!=null?a:"",D))}}return[{id:K(),type:"table",cols:e,rows:o,colsWidth:i,children:r}]}function sj(n){return[{id:K(),type:"embed",embedType:"hr",embedData:{}}]}function lj(n,t){var a;const e=n.text;if(!e)return[];try{const d=n.text,h=pa(d),p=JSON.parse(h);if(p){const{root:A,...v}=p.blocks;return t.doc.blocks={...t.doc.blocks,...v},A}}catch{}const o=(a=n.lang)!=null?a:"Plain Text";if(o==="mermaid")return[{id:K(),type:"embed",embedType:"mermaid",embedData:{mermaidText:e}}];if(o==="plantuml")return[{id:K(),type:"embed",embedType:"plantuml",embedData:{plantumlText:e}}];if(o==="flow"||o==="flowchart")return[{id:K(),type:"embed",embedType:"flowchart",embedData:{flowchartText:e}}];const i=e.split(`
|
|
426
|
+
`)}class DH{constructor(){m(this,"group","image");m(this,"commands",[])}executeCommand(t,e,o){if(o.id==="replace-image"){const{block:r,image:i}=o.data;xe.getImageObject(t,r).replaceImage(0,i)}}}function SH(){return{blockCommands:{image:new DH},abstract:`${R.t("image.abstract")}`}}function LH(){return{name:"Image",insertEmbedCommandItems:[{id:"insert-image",name:R.t("image.abstract"),icon:LL,group:"common",subText:"/image",order:100}],handleInsertEmptyEmbed:async(n,t)=>{var v;let e;(v=t.data)!=null&&v.file&&(e=t.data.file);const o=N7(n);if(e=e!=null?e:await Ul(o),!e)return null;try{$7(n,e)}catch{return null}let r={width:w7,height:j0};try{r=await u$(e)}catch(B){xH.error(B)}const i=n.rootContainer.clientWidth,s=r.width<i?Math.min(100,r.width/i*100):100,l={src:"",width:r.width,height:r.height,flex:1,virtualSize:!1},a=cn([l],s),d={id:K(),type:"embed",embedType:"image",embedData:a},h=n.options.componentsOptions.image;h!=null&&h.defaultAlign&&(d.align=h.defaultAlign);const p=n.insertBlock(t.containerId,t.blockIndex,d);return xe.getImageObject(n,p).replaceImage(0,e),p}}}function MH(n,t,e){var h;const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="image"||!tt(n,t))return null;const i=r.match(/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/),s=(h=i==null?void 0:i.groups)==null?void 0:h.filename;if(!s)return null;const l={src:s},a={id:K(),type:"embed",embedType:"image",embedData:l};xe.create(n,a).setAutoFix(!0);const d=n.options.componentsOptions.image.defaultAlign;return d&&(a.align=d),{blockData:a}}function RH(n,t){const e=it(t);n.destroyCustom(`image-${e}`)}const ny={embedType:"image",createEmbedContent:IH,convertTo:TH,convertFrom:MH,getBlockProperties:SH,getOptions:LH,handleDrop:rH,handleDropOver:lH,handleDeleteBlock:RH};class OH{constructor(t,e){m(this,"toolbar");m(this,"anchor",null);m(this,"item");m(this,"docs",null);m(this,"checkedId");m(this,"handlePasteSpecial",(t,e)=>{!e.data||(this.checkedId===e.id?this.checkedId=void 0:this.checkedId=e.id,this.onPasteSpecial(e.data),setTimeout(()=>{this.docs&&this.show(this.docs),this.editor.focus()}))});m(this,"handleClose",()=>{this.editor.focus()});m(this,"handleSelectionChange",()=>{this.handleClose()});this.editor=t,this.onPasteSpecial=e,this.item={id:"paste-special",name:"",icon:ML,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",childrenOffset:[-4,4],children:[]},this.toolbar=new ou([this.item],void 0,{id:"paste-special-button",tooltipId:this.editor.clientId,refuseOverflow:!0}),this.toolbar.addListener("click",this.handlePasteSpecial),this.toolbar.addListener("close",this.handleClose),this.editor.addListener("selectionChanged",this.handleSelectionChange)}show(t){this.docs=t;const e=this.editor,o=e.selection.range;if(!o.isCollapsed())return;const r=e.getBlockById(o.start.blockId);if(!tt(e,r))return;const i=Nr(e,r,o)[0];if(!i)return;this.anchor&&this.anchor.remove(),this.anchor=zr(e,r,"paste-special-button-anchor",i);const s=this.getCommandItems(t);this.item.children=s,this.toolbar.manualShow(this.anchor)}hide(){this.toolbar.close("selectionChange")}clearCheckedState(){this.checkedId=void 0}destroy(){this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange)}getCommandItems(t){const e=i=>({id:i,states:this.checkedId===i?["checked"]:void 0,name:R.t("pasteSpecial.originFormats"),data:t[i]}),o=[];let r=!0;return t["text/x-ones-editor-doc"]?o.push(e("text/x-ones-editor-doc")):t["text/office-html"]?o.push(e("text/office-html")):t["text/html"]?o.push(e("text/html")):t["text/plain"]&&(o.push(e("text/plain")),r=!1),t["text/plain"]&&(r&&o.push({id:"text/plain",states:this.checkedId==="text/plain"?["checked"]:void 0,name:R.t("pasteSpecial.plainText"),data:t["text/plain"]}),o.push({id:"text/markdown",states:this.checkedId==="text/markdown"?["checked"]:void 0,name:R.t("pasteSpecial.markdown"),data:t["text/markdown"]})),o}}const _H=S("paste-special");class s2{constructor(t){m(this,"button");m(this,"lastUndoAction",null);m(this,"event",null);m(this,"handlePasteSpecial",t=>{this.editor.undoManager.runInGroup(()=>{this.editor.undoManager.undoTo(this.lastUndoAction),this.editor.pasteDoc(t)})});this.editor=t,this.button=new OH(t,this.handlePasteSpecial)}destroy(){this.event=null,this.button.destroy()}handleChanged(t,e){this.event=null,this.button.hide()}async handleBeforePaste(t,e){return _H.debug("before paste"),this.lastUndoAction=t.undoManager.lastAction(),!1}async handleAfterPaste(t,e,o){if(Object.keys(o).length<=1)return!1;const r=t.selection.range;if(r.isCollapsed()){const i=t.getBlockById(r.start.blockId);if(!tt(t,i))return!1;this.button.clearCheckedState(),this.button.show(o),this.event=e}return!1}}const FH={pasteSpecial:{originFormats:"\u4FDD\u6301\u539F\u6837\u5F0F",plainText:"\u7C98\u8D34\u7EAF\u6587\u672C",markdown:"\u7C98\u8D34\u4E3A Markdown"}},PH={pasteSpecial:{originFormats:"Keep origin formats",plainText:"Paste as plain text",markdown:"Paste as markdown"}},NH={pasteSpecial:{originFormats:"\u5143\u306E\u30B9\u30BF\u30A4\u30EB\u3092\u7DAD\u6301\u3059\u308B",plainText:"\u30D7\u30EC\u30FC\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u8CBC\u308A\u4ED8\u3051\u308B",markdown:"Markdown \u3068\u3057\u3066\u8CBC\u308A\u4ED8\u3051"}};R.mergeLang({"zh-CN":FH,"en-US":PH,"ja-JP":NH});const Unt="",$H=S("html-to-doc");function HH(n){const t=new RegExp('(?<=<canvas data-editor-doc=")[\\s\\S]*(?=" id="ones-editor-doc">)',"g"),e=n.match(t);if(!e||!e.length)return null;const o=e[0],r=pa(o);return JSON.parse(r)}function jH(n){const t="ones-editor-doc::",e="::ones-editor-doc";let o=n.indexOf(t);if(o!==-1){o+=t.length;const i=n.indexOf(e,o);if(i!==-1){const s=n.substr(o,i-o);try{const l=pa(s);return JSON.parse(l)}catch(l){$H.error(`invalid doc data: ${l}, ${s}`)}}}const r=HH(n);return r||null}const oy="latex-b172fea480b",UH=n=>({name:"latex-block",level:"block",start(t){var e,o;return(o=(e=t.match(/\$\$[^\$]/))==null?void 0:e.index)!=null?o:-1},tokenizer(t,e){const o=/^\$\$([^\$]+)\$\$/.exec(t);return o?{type:"latex-block",raw:o[0],formula:o[1]}:void 0},renderer(t){return n.lazy?`<span class="${oy}" block>${t.formula}</span>`:n.render(t.formula,!0)}}),zH=n=>({name:"latex",level:"inline",start(t){var e,o;return(o=(e=t.match(/\$[^\$]/))==null?void 0:e.index)!=null?o:-1},tokenizer(t,e){const o=/^\$([^\$]+)\$/.exec(t);return o?{type:"latex",raw:o[0],formula:o[1]}:void 0},renderer(t){return n.lazy?`<span class="${oy}">${t.formula}</span>`:n.render(t.formula,!1)}});var VH=(n={})=>(n.lazy&&n.env!=="test"&&new IntersectionObserver((t,e)=>{for(const o of t){if(!o.isIntersecting)continue;const r=o.target;e.unobserve(r),Promise.resolve(n.render(r.innerText,r.hasAttribute("block"))).then(i=>{r.innerHTML=i}),r.classList.add("latex-rendered")}},{threshold:1}),{extensions:[UH(n),zH(n)]});function wc(n){const t=n.type;if(t==="link")return!!n.tokens.some(wc);switch(t){case"code":case"table":case"hr":case"blockquote":case"list":case"list_item":case"image":case"paragraph":return!0;default:return!1}}function WH(n){return!wc(n)}function qH(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=wc(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===wc(i)?e.push(i):(t.push(e),e=[i],o=wc(i))}return t.push(e),t}function GH(n,t,e){const o=n.href;let r=e.tokensToText(n.tokens,t,e);return r.length===0&&(r=Oi(o,t)),r=hh(r,"link",o),r}let Lu;function l2(n){Lu||(Lu=document.createElement("textarea")),Lu.innerHTML=n;const t=Lu.childNodes.length===0?"":Lu.childNodes[0].nodeValue;return t!=null?t:""}function ZH(n,t){const e=l2(n.text);return[co(e,{...t,"style-code":!0})]}function QH(n,t,e){const r=n.tokens;return r?e.tokensToText(r,t,e):lg(l2(n.text),t)}const YH=S("token-to-text");function c2(n,t,e){return n.map(r=>r.type==="text"?QH(r,t,e):r.type==="strong"?e.tokensToText(r.tokens,{...t,"style-bold":!0},e):r.type==="em"?e.tokensToText(r.tokens,{...t,"style-italic":!0},e):r.type==="del"?e.tokensToText(r.tokens,{...t,"style-strikethrough":!0},e):r.type==="link"?GH(r,t,e):r.type==="codespan"?ZH(r,t):r.type==="br"?[{insert:" ",attributes:{id:K(),created:Date.now(),box:!0,type:"br"}}]:r.type==="escape"?lg(l2(r.text),t):r.type==="latex"?[{insert:" ",attributes:{id:K(),created:Date.now(),box:!0,type:"math",tex:r.formula}}]:(YH.warn(`unknown token in text: ${JSON.stringify(r)}`),[])).flat()}function JH(n,t){const e=c2(n.tokens,{},t);return[{id:K(),type:"text",text:e,heading:n.depth}]}function KH(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function XH(n,t){const{text:e,children:o}=t.tokensToTextWithChildren([n],t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function tj(n,t){const e=typeof n.start=="number"?n.start:1,o=n.ordered,r=K(),i=[];return n.items.forEach((l,a)=>{const d={...t,listLevel:t.listLevel+1},{text:h,children:p}=t.tokensToTextWithChildren(l.tokens,d);let A;typeof l.checked=="boolean"&&(A=l.checked?"checked":"unchecked");const v={id:K(),type:"list",groupId:r,ordered:o,checkbox:A,start:e+a,text:h,level:t.listLevel};i.push(v),i.push(...p)}),i}function ej(n,t){const e=t.tokensToBlocks(n.tokens,t);return e.forEach(o=>{o.quoted=!0}),e}const ry=100,nj=20,oj=600;function rj(n,t){const e=t.text;if(e){const o=ie(e);return Math.min(Wd(o,n)+nj,oj)}return ry}function iy(n,t){let e=ry;return t.forEach(o=>{e=Math.max(e,rj(n,o))}),e}function ij(n,t){var l,a;const e=n.header.length,o=n.rows.length+1,r=[],i=Array(e).fill(100);for(let d=0;d<o;d++){let h;d===0?h=n.header:h=n.rows[d-1];for(let p=0;p<e;p++){const A=h[p],v=(l=A==null?void 0:A.tokens)!=null?l:[],B=K();r.push(B);let D;if(v.length===0)D=[mh()];else if(wc(v[0]))D=t.tokensToBlocks(A.tokens,t),D.length===0&&D.push(mh());else{const{text:x,children:_}=t.tokensToTextWithChildren(A.tokens,t);D=[{id:K(),type:"text",text:x},..._]}t.doc.blocks[B]=D,i[p]=Math.max(i[p],iy((a=t.font)!=null?a:"",D))}}return[{id:K(),type:"table",cols:e,rows:o,colsWidth:i,children:r}]}function sj(n){return[{id:K(),type:"embed",embedType:"hr",embedData:{}}]}function lj(n,t){var a;const e=n.text;if(!e)return[];try{const d=n.text,h=pa(d),p=JSON.parse(h);if(p){const{root:A,...v}=p.blocks;return t.doc.blocks={...t.doc.blocks,...v},A}}catch{}const o=(a=n.lang)!=null?a:"Plain Text";if(o==="mermaid")return[{id:K(),type:"embed",embedType:"mermaid",embedData:{mermaidText:e}}];if(o==="plantuml")return[{id:K(),type:"embed",embedType:"plantuml",embedData:{plantumlText:e}}];if(o==="flow"||o==="flowchart")return[{id:K(),type:"embed",embedType:"flowchart",embedData:{flowchartText:e}}];const i=e.split(`
|
|
427
427
|
`).map(d=>({id:K(),type:"text",text:Oi(d)})),s=t.doc,l=K();return s.blocks[l]=i,[{id:K(),type:"code",language:o,children:[l]}]}function cj(n){return[{id:K(),type:"embed",embedType:"image",embedData:{src:n.href,title:n.title}}]}function aj(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function uj(n){const t=n.formula;return t?[{id:K(),type:"embed",embedType:"math",embedData:{mathjaxText:t}}]:[]}const sy=S("markdown-to-doc");function dj(n,t){var e;if(n.type==="heading")return JH(n,t);if(n.type==="paragraph")return KH(n,t);if(n.type==="list")return tj(n,t);if(n.type==="blockquote")return ej(n,t);if(n.type==="table")return ij(n,t);if(n.type==="hr")return sj();if(n.type==="code")return lj(n,t);if(n.type==="image")return cj(n);if(n.type==="link")return aj(n,t);if(n.type==="latex-block")return uj(n);if(n.type==="text")return XH(n,t);if(n.type==="space"){const o=n.raw.replaceAll(" ",""),r=Math.floor(o.split(`
|
|
428
428
|
`).length/2)-1;return r>0?new Array(r).fill("").map(()=>({type:"text",id:K(),text:[]})):[]}if(n.type==="html"){const o=(e=t.htmlToDoc)==null?void 0:e.call(t,n.text);if(!o)return sy.warn(`failed to convert html to doc: ${JSON.stringify(n)}`),[];const{root:r,...i}=o.blocks;return t.doc.blocks={...t.doc.blocks,...i},r}return sy.warn(`unknown block token: ${JSON.stringify(n)}`),[]}function a2(n,t){const e=[];return n.forEach(o=>{const r=dj(o,t);e.push(...r)}),e}S("markdown-to-doc");function hj(n,t){const e={text:[],children:[]};return qH(n).forEach((r,i)=>{const s=r[0];if(i===0&&WH(s)){e.text=c2(r,{},t);return}e.children.push(...a2(r,t))}),e}const fj={render:(n,t)=>""};W5.marked.use(VH(fj));function ly(n,t){const o=new W5.marked.Lexer().lex(n),r={blocks:{root:[]},meta:{},comments:{}},i={font:t==null?void 0:t.font,doc:r,tokensToText:c2,tokensToBlocks:a2,tokensToTextWithChildren:hj,htmlToDoc:t==null?void 0:t.htmlToDoc,listLevel:1},s=a2(o,i);return s.length===0?null:(r.blocks.root.push(...s),r)}function mj(n){if(n.nodeName!=="DIV")return!1;const t=n;return Array.from(t.childNodes).every(e=>e.nodeName==="SPAN"||e instanceof Text)?!!t.querySelector(":scope > .hljs-function, :scope > .hljs-params, :scope > .hljs-string, :scope > .hljs-keyword, :scope > .hljs-attr"):!1}function cy(n){if(mj(n)){const t=n,e=t.parentNode,o=document.createElement("pre");Array.from(t.childNodes).forEach(r=>o.appendChild(r)),e==null||e.insertBefore(o,t);return}n.childNodes.forEach(t=>cy(t))}function jf(n){var t;if(n instanceof HTMLBRElement){const e=document.createTextNode(`
|
|
429
429
|
`);(t=n.parentNode)==null||t.insertBefore(e,n),n.remove();return}n.childNodes.forEach(jf)}function gj(n){n.addRule("preOnlyBlockToCode",{filter:t=>t.nodeName!=="PRE"?!1:Array.from(t.childNodes).every(e=>e.nodeName==="SPAN"||e instanceof Text||e.nodeName==="BR"),replacement:(t,e,o)=>{var r;return jf(e),`
|