@ones-editor/editor 1.1.4-bate.30 → 1.1.4-bate.31
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
|
@@ -28,7 +28,7 @@ Available method signatures are:
|
|
|
28
28
|
${t}
|
|
29
29
|
\`\`\`
|
|
30
30
|
`:""}function Ap(n){if(!window.isSecureContext||n.selection.range.isCollapsed())return!1;const t=Ra(n);Sa(n,t);const e=ba(n,t),r=wa(e,t);let i="";if(tT(n)){const s=n.selection.range.getSelectedBlocks()[0],l=rt(s.block);et(l)&&(i=eT(n,no(n,t)))}else{const s=[];t.blocks.root.forEach((l,c)=>{s.push(Eh(n,l,t,[{containerId:"root",blockIndex:c}]))}),s[s.length-1]=s[s.length-1].trimEnd(),i=s.join(`
|
|
31
|
-
`)}const o=new Blob([r],{type:"text/html"});return fa([{type:"text/plain",data:new Blob([i],{type:"text/plain"})},{type:"text/html",data:o}]),!0}const IU=Object.freeze(Object.defineProperty({__proto__:null,editorHandleEnter:X5,editorHandleDelete:Y5,editorHandleBackspace:Q5,editorHandleInsertBr:J5,editorHandlePastePlainText:Z5,isSelectedCodeTextBlock:tT,getSelectedCodeBlockMarkdown:eT,editorHandleCopyMarkdown:Ap},Symbol.toStringTag,{value:"Module"})),Ih={ArrowDown:g5,ArrowUp:m5,ArrowLeft:d5,ArrowRight:h5,"Shift+ArrowDown":p5,"Shift+ArrowUp":A5,"Shift+ArrowLeft":C5,"Shift+ArrowRight":E5,"CtrlOrCmd+ArrowLeft":b5,"CtrlOrCmd+ArrowRight":v5,"CtrlOrCmd+Shift+ArrowLeft":B5,"CtrlOrCmd+Shift+ArrowRight":T5,"CtrlOrCmd+ArrowUp":y5,"CtrlOrCmd+ArrowDown":fp,"CtrlOrCmd+Shift+ArrowUp":k5,"CtrlOrCmd+Shift+ArrowDown":dp,"CtrlOrCmd+A":mp,Home:D5,End:_5,"Shift+Home":L5,"Shift+End":I5,PageUp:P5,PageDown:F5,"Shift+PageUp":K5,"Shift+PageDown":V5,"CtrlOrCmd+Z":AU,"CtrlOrCmd+Shift+Z":xU,Enter:X5,Delete:Y5,Backspace:Q5,"Shift+Enter":J5,"CtrlOrCmd+Shift+V":Z5,"CtrlOrCmd+Shift+C":Ap};function nT(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function rT(n,t,e){if(t.type==="embed"){const o=t.embedData,s=o.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)o.src=l;else{let c="";s.split("|").forEach(h=>{const C=e.get(h);C&&(c+=c?`|${C}`:`${C}`)}),c&&(o.src=c)}}return}const r=t.text;r&&r.forEach(o=>{if(o.attributes&&o.attributes.src&&typeof o.attributes.src=="string"){const s=e.get(o.attributes.src);s&&(o.attributes.src=s)}});const i=t.children;i&&i.forEach(o=>{n.blocks[o].forEach(l=>{rT(n,l,e)})})}function iT(n,t,e){if(e.size===0)return;t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);o.replaceResources?o.replaceResources(i,e):rT(t,i,e)})}async function DU(n,t){let e=t.filter(s=>s.indexOf(":")===-1);const r=[];e.forEach(s=>{const l=s.split("|");r.push(...l)}),e=Array.from(new Set(r)),e=r;const i=await n.doc.addResources(e),o=new Map;if(e.length!==i.length)return o;for(let s=0;s<e.length;s++)o.set(e[s],i[s]);return o}function _U(n,t){var l,c,d,h;const r=t.meta.serverId;if(!r||typeof r!="string")return!1;const i=(c=(l=n.doc).getServerMeta)==null?void 0:c.call(l);if(!i)return!1;const o=/.*(?=\/)/;return((d=(i.serverId||"").match(o))==null?void 0:d[0])===((h=r.match(o))==null?void 0:h[0])}async function xp(n,t){const r=t.meta.resources;if(!r||Object.keys(r).length===0)return;let i=new Map;if(_U(n,t)){const s=Array.from(Object.keys(r));i=await DU(n,s),iT(n,t,i)}const o=new Map;Object.entries(r).forEach(([s,l])=>{i.get(s)===void 0&&s!==l&&o.set(s,l)}),o.size!==0&&iT(n,t,o)}async function MU(n,t,e){await xp(n,t),n.undoManager.runInGroup(()=>{const{start:r,end:i}=n.selection.range,o=n.getBlockById(r.blockId);if(r.blockId===i.blockId&&pe(o)){const s=rt(o),l=n.getBlockIndex(o),[c]=n.insertDocAt(s,l+1,t,e);c&&n.selection.selectBlock(c,dt(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=va(n);n.insertDoc(s,l,t,e)}})}const UU=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function OU(n){let t;for(const e of UU)if(t=n[e],t)break;return t||null}class NU{constructor(t){g(this,"editor");g(this,"handlers",[]);g(this,"hookExecutionAttempt",(t,e,r)=>{for(let i=0;i<this.handlers.length;i++){const o=this.handlers[i];if(o.handleBeforeCopy){const s=o.handleBeforeCopy(this.editor,e,r);if(s===!0)return!0;if(typeof s=="object"&&s!=null)return s}}});g(this,"onPasteText",async(t,e)=>{const r=new DataTransfer;r.setData("text/plain",t);const i=await this.editor.dataConverter.fromData(this.editor,r,e);if(i){const o=[];this.pasteDocs(i,null,o)}});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:r,blockIndex:i,offset:o}=va(this.editor);this.handleBeforeInsertText(r,i,o,e)||(this.defaultInsertText(this.editor,r,i,o,e),this.handleAfterInsertText(r,i,o,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 r=this.handlers[e];r.handleChanged&&r.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleRemoteChanged&&r.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:r,offset:i}=va(this.editor);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,r,i)}}onUpdateCompositionText(t,e,r){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,r),this.editor.selection.caret.update();const{containerId:i,blockIndex:o,offset:s}=va(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,i,o,s,r)}this.editor.selection.updateLastCaretRect()}onCopy(t){wU(this.editor,t,this.hookExecutionAttempt)}onCopyWithoutEvent(){SU(this.editor,this.hookExecutionAttempt)}onCut(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeCut&&i.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const r=this.editor.selection.focusedBlock;pe(r)&&this.editor.deleteBlock(r)}else Bh(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),r=Array.from(t.clipboardData.files);e.then(async i=>{i&&this.pasteDocs(i,t,r)})}onFocus(){z(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,r)=>{var s,l;const i=(s=e.order)!=null?s:1;return((l=r.order)!=null?l:1)-i})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,r,i))return!0}return!1}handleAfterInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,r,i))return!0}return!1}handleBeforeKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,r,i,o){X1(this.editor,o)}defaultHandleKeydown(t,e){return nT(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePasteDoc&&await i.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await MU(this.editor,t,e);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPasteDoc&&await i.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e,r){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,r))return}const i=OU(t);if(!!i){await this.pasteDoc(i);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}forEach(t){this.handlers.forEach(t)}}function PU(n,t,e){const r=ji(t,e);return r.remove(),r}I("copy-dom-attributes");const oT=["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 FU(n,t){for(let l=0;l<oT.length;l++){const c=oT[l];t[c]=n[c]}const e=n.attributes,r=t.attributes,i=[],o=[];for(let l=0;l<e.length;l++){const c=e[l],d=r.getNamedItem(c.name);d?d.value!==c.value&&(d.value=c.value,o.push(c)):i.push(c)}const s=[];for(let l=0;l<r.length;l++){const c=r[l];e.getNamedItem(c.name)||s.push(c)}i.forEach(l=>{t.setAttribute(l.name,l.value)}),o.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function sT(n){const t=Array.from(n.childNodes).filter(e=>!vv(e));return t.forEach(e=>{e.remove()}),t}function lT(n,t,e){var d;const r=n.getContainerById(t),i=ji(r,e),o=Ko(i),s=n.doc.getBlockData(t,e),l=Qt(n,i);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,i,s))n.editorBlockRenders.updateBlock(n,o,i,s);else{const h=n.editorBlocks.createBlock(o,r,s),C=sT(h);sT(i),C.forEach(x=>{i.appendChild(x)});const E=Hd(h);if(E){const x=Hd(i);x&&x.remove(),i.appendChild(E)}FU(h,i)}Pv(n,i,s),n.blockHooks.forEach(h=>{var C;(C=h.update)==null||C.call(h,n,o,r,i,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const KU=I("transform-selection");function aT(n,t,e,r){const{range:i}=n.selection,{anchor:o,focus:s}=i;if(o.blockId!==t&&s.blockId!==t)return i;p(KU,o.isSimple()&&s.isSimple(),"invalid text pos type");let l=o;if(o.blockId===t){const d=fn.transformCursor(o.offset,e,r);l=lt(t,d,"normal")}let c=s;if(s.blockId===t){const d=fn.transformCursor(s.offset,e,r);c=lt(t,d,"normal")}return Xe(n,{anchor:l,focus:c})}const VU=I("handle-block-text-changed");function $U(n,t,e,r,i){const o=n.getContainerById(t),s=ji(o,e),l=n.doc.getBlockData(t,e);if(p(VU,l.text,"no block text"),Ev(n,s).setBlockText(n,s,l.text),!i){const c=aT(n,l.id,r,i);n.selection.setRange(c,{noScroll:!0})}}function HU(n,t){const e=gt.default(n);return t.delete.forEach(i=>{delete e[i]}),{...e,...t.insert}}function cT(n,t,e,r){const i=Qt(n,t);i.handleDeleteBlock&&i.handleDeleteBlock(n,t,e,r),n.emit("blockDeleted",n,t,e,r)}function jU(n,t,e,r){const i=n.getBlockByIndex(t,e);i.querySelectorAll('[data-type="editor-block"]').forEach(o=>{cT(n,o,r,{child:!0})}),cT(n,i,r,{child:!1})}const Or=I("editor-doc");class zU extends oa{constructor(e,r,i){super();g(this,"localEvents",[]);this.editor=e,this.externalDoc=r,this.externalDoc.registerCallback(this),this.registerLocalEvents(i)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var r,i;return(i=(r=this.externalDoc).getVersionHelper)==null?void 0:i.call(r)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,r){return this.externalDoc.getBlockData(e,r)}verifyBlockWritable(e,r){const i=this.editor.getBlockByIndex(e,r);p(Or,this.editor.isBlockWritable(i),`block is not writable, ${e}, ${r}`)}localUpdateBlockText(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const s=this.getBlockData(e,r),l=s.text;p(Or,l,`no text, ${e}, ${r}`);const c=aT(this.editor,s.id,i,!0),d=fn.apply(l,i);this.localEvents.forEach(C=>C.onBeforeUpdateBlockText(e,s.id,l,d,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,r,i);return this.editor.selection.setRange(c,o),h}localUpdateBlockData(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,r);if(!this.editor.isBlockWritable(s)){const h=Array.from(i.delete).filter(E=>E!=="comments"),C=Object.keys(i.insert).filter(E=>E!=="comments");(h.length>0||C.length>0)&&p(Or,!1,`block is not writable, comment supported only, ${JSON.stringify(i)}}`)}const l=gt.default(this.getBlockData(e,r)),c=gt.default(HU(l,i));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,c,o));const d=this.externalDoc.localUpdateBlockData(e,r,i,o);return this.editor.selection.setRange(Vo(this.editor,o)),d}localInsertBlock(e,r,i,o,s){p(Or,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,r,i,o));const l=this.externalDoc.localInsertBlock(e,r,i,o);return s!=null&&s.noFocus||this.editor.selection.setRange(Vo(this.editor,o),s),l}localDeleteBlock(e,r,i){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const o=gt.default(this.getBlockData(e,r));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,r,o,i));const s=this.externalDoc.localDeleteBlock(e,r,i);return this.editor.selection.setRange(Vo(this.editor,i)),s}localDeleteChildContainers(e){return p(Or,!this.editor.readonly,"editor is readonly"),e.forEach(r=>{const i=gt.default(this.getContainerBlocks(r));this.localEvents.forEach(o=>o.onBeforeDeleteChildContainer(r,i))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){p(Or,!this.editor.readonly,"editor is readonly");const r=gt.default(e);r.forEach(i=>{this.localEvents.forEach(o=>o.onBeforeInsertChildContainer(i.containerId,i.blocks))}),this.externalDoc.localInsertChildContainers(r)}onRequestReload(e){Or.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(i=>{var o;return(o=i.onRequestReload)==null?void 0:o.call(i,e)});const r=!1;this.editor.emit("docChanged",this.editor,r)}onUpdateBlockText(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,r,i,o)}),$U(this.editor,e,r,i,o),this.editor.emit("docChanged",this.editor,o)}onUpdateBlockData(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,o)}),lT(this.editor,e,r),this.editor.emit("docChanged",this.editor,o)}onInsertBlock(e,r,i,o){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,r,i,o)});const s=this.editor.getContainerById(e);TI(this.editor,s,r,i),this.editor.emit("docChanged",this.editor,o)}onDeleteBlock(e,r,i){jU(this.editor,e,r,i),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,i)});const o=this.editor.getContainerById(e);PU(this.editor,o,r),this.editor.emit("docChanged",this.editor,i)}onInsertChildContainer(e,r,i){this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,e,r,i)})}onDeleteChildContainer(e,r){this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,e)})}onStatusChanged(e){this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)})}onError(e){this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}uploadResource(e,r){return this.externalDoc.uploadResource(e,r)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,r){return this.externalDoc.buildResourceUrl(e,r)}request(e,r){return this.externalDoc.request(e,r)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}triggerReAuth(){var e,r;return(r=(e=this.externalDoc).triggerReAuth)==null?void 0:r.call(e)}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,r,i;return(i=(r=(e=this.externalDoc).getServerMeta)==null?void 0:r.call(e))!=null?i:{}}reset(e){Or.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function uT(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 Dh=I("undo-action");class La{constructor(t,e,r){g(this,"beforeRange");g(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=r}undo(t){return!1}redo(t){return!1}combinable(t){return p(Dh,t,"no other action"),!1}combine(t){p(Dh,!1,"no other")}setAfterRange(t){this.afterRange&&Dh.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const r=t.doc.findContainerBlocks(this.containerId);return r?r.some(i=>i.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const r=t.doc.toJSON();for(let i=0;i<e.children.length;i++){const o=e.children[i];if(!r.blocks[o])return Dh.warn(`container (${o}) not found, deleted by others?`),!1}}return!0}}const Ia=I("block-action");class fT extends La{constructor(e,r,i,o,s){super(e,r,s);g(this,"blockData");g(this,"blockIndex");this.blockData=gt.default(o),this.blockIndex=i}deleteBlock(e,r){if(!this.findContainerById(e,this.containerId))return Ia.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return Ia.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const o=e.getBlockById(this.blockData.id);if(!o)return!1;try{p(Ia,this.blockIndex===bt(o),"invalid block index"),bh(e,o,Vo(e,r))}catch(s){Ia.warn(s.message),e.selection.selectBlock(o,0)}return!0}insertBlock(e,r){if(!this.findContainerById(e,this.containerId))return Ia.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{Ta(e,this.containerId,this.blockIndex,gt.default(this.blockData),r)}catch(i){Ia.warn(i.message);const o=e.doc.getContainerBlocks(this.containerId),s=Math.min(o.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}I("insert-block-action");class GU extends fT{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class WU extends fT{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class qU extends La{constructor(e){super(e,ft(e.rootContainer),e.selection.range.toDocRange());g(this,"actions",[])}addAction(e){uT(this.actions,e),this.afterRange=e.afterRange}undo(e){let r=!1;return this.actions.concat().reverse().forEach(i=>{i.undo(e)&&(r=!0)}),r}redo(e){let r=!1;return this.actions.forEach(i=>{i.redo(e)&&(r=!0)}),r}setAfterRange(e){this.afterRange=e;const r=this.actions[this.actions.length-1];!r||r instanceof La&&(r.afterRange||r.setAfterRange(e))}}const qo=I("update-block-data-action");class _h extends La{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeBlockData");g(this,"afterBlockData");g(this,"blockId");this.blockId=i,p(qo,this.blockId===o.id,"invalid block id"),p(qo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=gt.default(o),this.afterBlockData=gt.default(s),p(qo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return qo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(qo,i,"no container"),yh(e,r,_h.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return qo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;p(qo,e,"no editor");const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(qo,i,"no container"),yh(e,r,_h.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const r=gt.default(e);return delete r.id,delete r.type,r}}const tl=I("update-block-text-action");class bu extends La{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeRichTextData");g(this,"afterRichTextData");g(this,"blockId");g(this,"type");this.blockId=i,this.beforeRichTextData=gt.default(o),this.afterRichTextData=gt.default(s),this.type=bu.calType(o,s)}static calType(e,r){p(tl,e,"no old data"),p(tl,r,"no new data");const o=fn.diff(e,r),s=new Set;let l=!1;const c=h=>qb(h)?`cjk_${h}`:Gb(h)?"number":Md(h)?"space":Wb(h)?"letter":"unknown";let d=!1;return o.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_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Th(e,i,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Th(e,i,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof bu)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const r=e.beforeRange,i=r.anchor;if(!i.isSimple())return!1;const o=this.afterRange;if(!o)return!1;const s=o.anchor;return!(!s.isSimple()||s.blockId!==r.anchor.blockId||s.offset!==i.offset)}combine(e){p(tl,e instanceof bu,"invalid action type");const r=e;this.afterRichTextData=r.afterRichTextData,this.afterRange=e.afterRange}}const dT=I("child-container-action");class hT extends La{constructor(t,e,r){super(t,e,t.selection.range.toDocRange()),this.blocks=r}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(dT.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(dT.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:gt.default(this.blocks)}]),!0)}}class XU extends hT{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class YU extends hT{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Nr=I("undo");class QU{constructor(t){g(this,"editor");g(this,"actions",[]);g(this,"undoCursor");g(this,"currentGroup",null);g(this,"groupCounter",0);g(this,"undoRedoing",!1);g(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):(uT(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(p(Nr,!this.currentGroup,"current group already exists"),this.currentGroup=new qU(this.editor),this.groupCounter=1):(p(Nr,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){p(Nr,this.currentGroup,"current group not exists"),p(Nr,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Nr.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 Nr.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(Vo(this.editor,t.beforeRange))}catch(e){Nr.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(Vo(this.editor,e)):Nr.warn("no after range")}catch(e){Nr.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,r,i,o){this.undoRedoing||(this.prepareSaveUndoState(),fn.diff(r,i).length!==0&&this.addAction(new bu(this.editor,t,e,r,i,o)))}onBeforeUpdateBlockData(t,e,r,i,o){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new _h(this.editor,t,e,r,i,o);this.addAction(s)}onBeforeInsertBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),p(Nr,e>=0,"invalid block index"),p(Nr,r,"no block data"),this.addAction(new GU(this.editor,t,e,r,i)))}onBeforeDeleteBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new WU(this.editor,t,e,r,i)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new XU(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new YU(this.editor,t,e)))}}class JU{async fromData(t,e){const r=e.getData("text/x-ones-editor-doc");if(r)return{"text/x-ones-editor-doc":JSON.parse(r)}}}class ZU{constructor(){g(this,"converters",[]);g(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new JU)}prepareData(t){const e=new DataTransfer;for(let r=0;r<this.converterTypes.length;r++)e.setData(this.converterTypes[r],t.getData(this.converterTypes[r]));return e}async fromData(t,e,r){let i={};const o=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,o,r);l&&(i={...i,...l})}return i}addConverter(t){this.converters.push(t)}}function tO(n){n.editorBlocks.registerBlockClass(Un),n.editorBlocks.registerBlockClass(n3),n.editorBoxes.registerBoxClass(BB),n.editorBoxes.registerBoxClass(TB),n.editorBoxes.registerBoxClass(RB),n.editorBoxes.registerBoxClass(wB),n.editorInsertions.registerInsertionClass(SB),n.editorBlockRenders.registerRender(new bv)}function eO(n,t){tO(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 Mh=I("range-commands");function mT(n,t){n.forEach(e=>{e.source=t,e.children&&mT(e.children,t)})}function gT(n,t,e){const r=st(t);p(Mh,r===e.start.blockId,"invalid start range"),p(Mh,r===e.end.blockId,"invalid end range");const i=n.editorCommandProviders.getCommandProviders();let o=[];if(i.forEach(s=>{const l=s.getAvailableCommands(n,t,e);mT(l,s.id),o.push(...l)}),i.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,o);l&&(o=l)}}),_t(n,t)){if(!ha(e.start))return o;p(Mh,!e.start.isSimple(),"invalid start pos"),p(Mh,!e.end.isSimple(),"invalid end pos");const s=e.start.childContainerId,l=ai(n,s),d=ce(l)[0];if(d){const h=dt(n,d),C=Xe(n,{anchor:lt(d,0,"home"),focus:lt(d,h,"end")}),E=gT(n,d,C);o.push(...E)}}return o}function pT(n){const t=n.getEditor(),e=n.getSelectedBlocks(),r=[],i=n.isReverse()?e[0]:e[e.length-1],o=Xe(t,{anchor:i.start,focus:i.end});return gT(t,i.block,o).forEach(l=>{r.push(l)}),r}function CT(n,t,e,r,i,o){var h;const s=n.editorCommandProviders.getCommandProviders();for(let C=0;C<s.length;C++){const E=s[C];if(E.beforeExecuteCommand&&E.beforeExecuteCommand(n,t,e,r,i))return!1}const l=n.editorCommandProviders.getCommandProvider(r.source),c={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,r,i,{}))return o[st(t)]=c,!0;let d=!1;return _t(n,t)&&ma(n,t,e.start,e.end).forEach(E=>{ce(E).forEach(v=>{const R=dt(n,v),L=Xe(n,{anchor:lt(v,0,"home"),focus:lt(v,R,"end")});CT(n,v,L,r,i,o)&&(d=!0)})}),s.forEach(C=>{C.afterExecuteCommand&&C.afterExecuteCommand(n,t,e,r,i,o)}),d}function ET(n,t,e){const r=n.getEditor(),i={},o=r.editorCommandProviders.getCommandProvider(t.source);return o.executeRangeCommand&&o.executeRangeCommand(r,n,t,e,i)||(n.getSelectedBlocks().forEach(l=>{const c=Xe(r,{anchor:l.start,focus:l.end});CT(r,l.block,c,t,e,i)}),r.focus()),i}const nO=I("command-providers");class AT{constructor(t){g(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(r=>r.id===t);return p(nO,e,`no command provider, id=${t}`),e}getCommands(t){return pT(t)}executeCommand(t,e,r){return this.editor.undoManager.runInGroup(()=>ET(t,e,r))}getEmptyBlockTextAttributes(t,e){let r={};if(this.providers.forEach(i=>{var s;const o=(s=i.getEmptyBlockTextAttributes)==null?void 0:s.call(i,t,e);o&&(r={...r,...o})}),Object.keys(r).length!==0)return r}}function rO(n,t){const e=rt(t),r=ft(e),i=bt(t);lT(n,r,i)}const iO=I("table-scroll");class xT{constructor(t,e,r,i,o){g(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=r,this.handler=i,this.data=o,e.addEventListener(r,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class oO{constructor(t){g(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(r=>r.destroy()),this.handlers.delete(t)})}addEventListener(t,e,r,i){const o=this.handlers.get(t);if(o){if(o.find(s=>s.handler===r&&s.name===e)){iO.warn(`event has already registered: ${e}`);return}o.push(new xT(this.editor,t,e,r,i))}else{const s=new xT(this.editor,t,e,r,i);this.handlers.set(t,[s])}}removeEventListener(t,e,r){if(!t){for(const[o,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&r===c.handler&&s.splice(l,1);else if(r===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(o);continue}}return}const i=this.handlers.get(t);if(i){const o=i.findIndex(s=>s.handler===r&&s.name===e);if(o!==-1){const s=i[o];i.splice(o,1),s.destroy(),i.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const r=this.handlers.get(t);if(r)if(e)for(let i=0;i<r.length;i++){const o=r[i];o.name===e&&(r.splice(i,1),o.destroy())}else r.forEach(i=>{i.destroy()}),this.handlers.delete(t)}}const bT=I("update-block-text");function sO(n,t){const e=n.getBoxById(t.id),r=et(e);p(bT,r,"no parent block"),p(bT,nt(n,r),"not a text block");const i=n.getBlockText(r),o=mB(i,"id",t.id,t);QB(n,r,o)}function lO(n,t){for(const e of n.blockHooks)if(e.writable){const r=e.writable(n,t);if(typeof r=="boolean")return r}return!0}function aO(n){if(n.readonly)return!1;const t=di(n);return!!n.isBlockWritable(t.map(e=>e.block))}class cO{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 uO{constructor(){g(this,"shortcuts",[])}handleKeyboardEvents(t,e){const r=this.shortcuts;for(const i of r){const o=Object.entries(i);for(const[s,l]of o)if(si(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const ro=I("editor");class fO extends Be.TypedEmitter{constructor(e,r,i){var o,s,l,c,d,h,C,E;super();g(this,"parent");g(this,"rootElement");g(this,"contentElement");g(this,"rootContainerObject");g(this,"rootContainer");g(this,"input");g(this,"selection");g(this,"selectionHandler");g(this,"doc");g(this,"id");g(this,"clientId");g(this,"compositingText","");g(this,"undoManager");g(this,"shortcuts",new uO);g(this,"dataConverter",new ZU);g(this,"editorBlocks",new Jv(this));g(this,"editorBoxes",new kB(this));g(this,"editorInsertions",new IB(this));g(this,"editorEmbeds",new t3(this));g(this,"editorDecorators",new DB(this));g(this,"editorCommandProviders",new AT(this));g(this,"editorBlockRenders",new mI(this));g(this,"blockHooks",[]);g(this,"domEvents",new oO(this));g(this,"customs",new Map);g(this,"options");g(this,"inputHandlers",new NU(this));g(this,"settingsProvider");g(this,"_readonly",!1);g(this,"getColor",e=>{const r=this.options.colors;return r.length===0?"#FF1A75":r[e%r.length]});ro.debug("create editor"),this.setMaxListeners(100),this.options={colors:(o=i==null?void 0:i.colors)!=null?o:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"],componentsOptions:(l=(s=i==null?void 0:i.components)==null?void 0:s.options)!=null?l:{},scrollContainer:i==null?void 0:i.scrollContainer,enableComments:(c=i==null?void 0:i.enableComments)!=null?c:!0},this.settingsProvider=(d=i==null?void 0:i.settingsProvider)!=null?d:new cO(this),eO(this,i==null?void 0:i.components),this.blockHooks.push(...(C=(h=i==null?void 0:i.components)==null?void 0:h.blockHooks)!=null?C:[]),this.id=(E=i==null?void 0:i.id)!=null?E:Z(),this.clientId=Z(),this.undoManager=new QU(this),this.doc=new zU(this,r,this.undoManager),this.parent=e,this.rootElement=B("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=B("div",["editor-content"],this.rootElement),this.rootContainerObject=Xv(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new yM(this,this.inputHandlers),this.selection=new gU(this),this.selectionHandler=new EU(this),i!=null&&i.shortcuts&&this.shortcuts.shortcuts.push(...i.shortcuts),me.isMobile&&z(this.rootElement,"mobile"),me.isSafari&&z(this.rootElement,"safari"),this._readonly&&z(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?z(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:An(this.rootContainer)}addCustom(e,r){const i=this.customs.get(e);if(i)return i;const o=r(this);return this.customs.set(e,o),o}getCustom(e){const r=this.customs.get(e);return p(ro,r,`${e} does not exists`),r}replaceCustom(e,r){const i=this.customs.get(e);return i&&i.destroy(),this.customs.set(e,r),r}findCustom(e){return this.customs.get(e)}findCustomByType(e){const r=this.customs.values();for(const i of r)if(i instanceof e)return i;return null}destroyCustom(e){const r=this.customs.get(e);r&&(this.customs.delete(e),r.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,r,i){return this.editorBlocks.createBlock(e,r,i)}createBox(e,r){return this.editorBoxes.createBox(e,r)}createInsertion(e,r){return this.editorInsertions.createInsertion(e,r)}destroy(){ro.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()}focusToBlock(e,r){ep(this,e,r)}isWritable(){return aO(this)}isBlockWritable(e){return lO(this,e)}getChildContainerData(e){const r=this.doc.getContainerBlocks(e);return(!r||!Array.isArray(r))&&(p(ro,r,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),p(ro,Array.isArray(r),`container data is not an array: ${JSON.stringify(r)}`)),r}createChildContainer(e,r,i){return Yv(this,e,r,i)}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 r=this.rootContainer.querySelector(`#${e}`);return r&&p(ro,Fs(r),"not an valid block element"),r!=null?r:null}findBoxById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(ro,jd(r),"not an valid box element"),r!=null?r:null}getBlockById(e){const r=this.findBlockById(e);return p(ro,r,`no block, id=${e}`),r}getBoxById(e){const r=this.findBoxById(e);return p(ro,r,`no box, id=${e}`),r}getBlockByIndex(e,r){const i=this.getContainerById(e);return ji(i,r)}findBlockByIndex(e,r){const i=this.getContainerById(e);return pv(i,r)}getBlockIndex(e){if(typeof e=="string"){const r=this.getBlockById(e);return bt(r)}return bt(e)}getContainerById(e){return ai(this,e)}getParentContainer(e){return rt(e)}reloadBlock(e){rO(this,e)}contains(e){const r=e instanceof Element?e:e.parentElement;return r?r.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,r,i,o,s){const l={blockId:i.id,offset:0},c={anchor:l,focus:l};return Ta(this,e,r,i,o!=null?o:c,s)}insertEmbed(e,r,i,o,s){const l={id:Z(),type:"embed",embedType:i,embedData:o};return this.insertBlock(e,r,l,s)}deleteBlock(e,r){Z1(this,e,r)}mergeTextBlock(e,r){return qB(this,e,r)}breakTextBlock(e,r,i){return ya(this,e,r,i).newBlock}getTextPosition(){return va(this)}getBlockString(e,r){const i=this.getBlockText(e);return fe(i,r)}getBlockData(e){return zo(this,e)}getBoxData(e){return bB(this,e)}getBlockText(e){return vn(this,e)}setBlockText(e,r){QB(this,e,r)}deleteTextFromBlock(e,r,i,o){return Q1(this,e,r,i,o)}insertTextToBlock(e,r,i,o){return $B(this,e,r,i,o)}insertBoxToBlock(e,r,i){return HB(this,e,r,i)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,r,i,o){t5(this,e,r,i,o)}insertDocAt(e,r,i,o){return ip(this,e,r,i,o)}deleteChildContainers(e){WB(this,e)}replaceBlockText(e,r){return Th(this,e,r)}updateBlockData(e,r,i){const o={...this.getBlockData(e),...r},{id:s,type:l,...c}=o;return yh(this,e,c,(i!=null?i:this.selection.range).toDocRange())}updateEmbedData(e,r,i){return JB(this,e,r,i)}updateBoxData(e){sO(this,e)}getSelectedText(){const e=Ra(this);return no(this,e)}clearSelectedContents(){Bh(this)}insertTextBlock(e,r,i,o){const s=gi(e!=null?e:"");return GB(this,s,r,i,o==null?void 0:o.newRange,o==null?void 0:o.insertBlockOptions)}updateCompositionText(e,r){if(e&&!r&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!r){Y1(this);return}r?(this.compositingText="",qc()?e||Y1(this):X1(this,e)):(this.compositingText=e,jB(this))}}function vu(n,t,e){return new fO(n,t,e)}function dO(n){const t=(r,i)=>{const o=r.findIndex(l=>l.id===i.id);if(o===-1){r.push(i);return}const s=r[o];if(s.value!==i.value){r.splice(o,1);return}if(!!s.states){if(!i.states){s.states=[];return}s.states=bg.default(s.states,i.states)}},e=[];return n.forEach(r=>{r.forEach(i=>{t(e,i)})}),e}const hO=["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"];class Bu extends Be.TypedEmitter{constructor(e){super();g(this,"users",new Map);g(this,"cursors",new Map);g(this,"addingUser",!1);g(this,"colors");this.colors=e&&e.length>0?e:hO}setCursor(e){this.addUser(e.user);const r=this.cursors.get(e.user.userId);if(r&&jc.default(r,e))return;this.cursors.set(e.user.userId,e);const i=new Set([e.range.anchor.blockId,e.range.focus.blockId]),o=new Set(i);r&&new Set([r.range.anchor.blockId,r.range.focus.blockId]).forEach(l=>{i.has(l)||o.add(l)}),this.emit("remote-carets-change",[...o])}addUsers(e){this.addingUser=!0,e.forEach(r=>this.addUser(r)),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 r;return(r=this.users.get(e))!=null?r:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const r=this.cursors.get(e);if(r){const i=new Set(new Set([r==null?void 0:r.range.anchor.blockId,r==null?void 0:r.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...i])}}updateUsers(e){this.users.forEach(r=>{e.find(i=>i.userId===r.userId)||this.removeUser(r.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(r=>{this.addUser(r)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const r=new Map;return Array.from(this.cursors.values()).filter(i=>i.range.anchor.blockId===e&&fh(i.range)).forEach(i=>{const o=i.range.focus.offset;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}),r}getCursors(e){return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e||r.range.focus.blockId===e)}onUpdateBlockText(e,r,i){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(fh(l.range)){const{anchor:c,focus:d}=l.range;c.blockId===e.id&&(c.offset=fn.transformCursor(c.offset,r,i)),d.blockId===e.id&&(d.offset=fn.transformCursor(d.offset,r,i))}})}getFixedUserColor(e,r){let i=0;Array.from(e).forEach(s=>{i+=s.charCodeAt(0)});const o=i%this.colors.length;return this.colors[o]}destroy(){this.removeAllListeners()}}const rn=I("local-doc");class bp extends oa{constructor(e,r){super();g(this,"doc");g(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[gi("")]}},this.serviceUrl=(r==null?void 0:r.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return gt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}findContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,r){const i=this.getContainerBlocks(e);p(rn,i,`no container data: ${e}`);const o=i[r];return p(rn,o,`no block data: ${r}`),o}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(rn,o.text,"no text for data");const s=fn.apply(o.text,i);return o.text=s,p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,r,i,!0)}),s}localUpdateBlockData(e,r,i){const o=this.getBlockData(e,r);return i.delete.forEach(s=>delete o[s]),Object.entries(i.insert).forEach(([s,l])=>{o[s]=l}),p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,!0)}),o}localInsertBlock(e,r,i){const o=this.getContainerBlocks(e);return p(rn,o,`no container data: ${e}`),p(rn,r>=0&&r<=o.length,`invalid block index: ${r}, ${o.length}`),o.splice(r,0,i),p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,r,i,!0)}),i}localDeleteBlock(e,r){const i=this.getContainerBlocks(e);p(rn,i,`no container data: ${e}`),p(rn,r>=0&&r<=i.length,`invalid block index: ${r}, ${i.length}`);const o=i[r];return i.splice(r,1),p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,!0)}),o}localInsertChildContainers(e){e.forEach(({containerId:r,blocks:i})=>{this.doc.blocks[r]=i,p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,r,i,!0)})})}localDeleteChildContainers(e){rn.debug(`delete child containers: ${e}`),e.forEach(r=>{p(rn,this.doc.blocks[r],`no child container: ${r}`),delete this.doc.blocks[r]}),e.forEach(r=>{p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,r,!0)})})}uploadResource(e,r){p(rn,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,r){p(rn,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Bu}setDoc(e){this.doc=gt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,"change doc")})}destroy(){this.clearCallbacks()}}class mO{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function vp(n,t,e){n.addCustom(t,()=>{var o;const r=(o=e())!=null?o:void 0;return new mO(r)})}const vT=I("find-block");function BT(n,t){const e=$s(t);if(!e){if(fr(t))return null;const r=Ks(t);return p(vT,r,"no parent block"),BT(n,r)}return _t(n,e)?ga(n,e,{visibleOnly:!0}):e}function TT(n,t){const e=Hs(t);if(!e){if(fr(t))return null;const r=Ks(t);return p(vT,r,"no parent block"),TT(n,r)}return _t(n,e)?s1(n,e,{visibleOnly:!0}):e}const gO=I("remote-cursor");class pO{constructor(){g(this,"remoteUsers",new Bu)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const r=e;this.handleUpdateUsers(r.users)}else e.type==="caret"?this.handleUpdateCaret(e):gO.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 CO(n){const{blocks:t,meta:e,comments:r,...i}=n;return{rootBlocks:t,meta:e,comments:r,childBlocks:i}}function EO(n){const{blocks:t,meta:e,comments:r}=n,{root:i,...o}=t;return{blocks:i,meta:e,comments:r,...o}}function io(n){const{childBlocks:t,meta:e,comments:r,rootBlocks:i}=CO(gt.default(n));return{blocks:{root:i,...t},meta:e,comments:r}}function oo(n){return n==="root"?"blocks":n}function Da(n){return n==="blocks"?"root":n}const AO={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new cn.default(n)},apply(n,t){const e=new cn.default(n),r=new cn.default(t);return e.compose(r).ops},compose(n,t){const e=new cn.default(n),r=new cn.default(t);return e.compose(r).ops},diff(n,t){const e=new cn.default(n),r=new cn.default(t);return e.diff(r).ops},transform(n,t,e){const r=new cn.default(n);return new cn.default(t).transform(r,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 r=new cn.default(t),i=this.transformCursor(n.index,r,e),o=this.transformCursor(n.index+n.length,r,e);return{...n,index:i,length:o-i}}}};var Xo={},Bp=Eb.default.EventEmitter;Xo.EventEmitter=Bp,Xo.mixin=xO;function xO(n){for(var t in Bp.prototype)n.prototype[t]=Bp.prototype[t]}var yT=["info","warn","error"];function kT(){var n={};yT.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var bO=kT;kT.prototype.setMethods=function(n){n=n||{};var t=this;yT.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var vO=bO,BO=new vO,RT=BO;function el(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,el):this.stack=new Error().stack}el.prototype=Object.create(Error.prototype),el.prototype.constructor=el,el.prototype.name="ShareDBError",el.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 Uh=el,Tu={},wT=TO;function TO(n,t,e,r){var i=function(s,l,c,d){t(c,s,l,"left"),t(d,l,s,"right")},o=n.transformX=function(s,l){e(s),e(l);for(var c=[],d=0;d<l.length;d++){for(var h=l[d],C=[],E=0;E<s.length;){var x=[];if(i(s[E],h,C,x),E++,x.length===1)h=x[0];else if(x.length===0){for(var v=E;v<s.length;v++)r(C,s[v]);h=null;break}else{for(var R=o(s.slice(E),x),L=0;L<R[0].length;L++)r(C,R[0][L]);for(var M=0;M<R[1].length;M++)r(c,R[1][M]);h=null;break}}h!=null&&r(c,h),s=C}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?o(s,l)[0]:o(l,s)[1]}}var ST={exports:{}},Yo=ST.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||""}},Tp=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},yp=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")},Oh=function(n){for(var t=0;t<n.length;t++)yp(n[t])};Yo.apply=function(n,t){var e;Oh(t);for(var r=0;r<t.length;r++){var i=t[r];if(i.i!=null)n=Tp(n,i.p,i.i);else{if(e=n.slice(i.p,i.p+i.d.length),i.d!==e)throw new Error("Delete component '"+i.d+"' does not match deleted text '"+e+"'");n=n.slice(0,i.p)+n.slice(i.p+i.d.length)}}return n};var so=Yo._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:Tp(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:Tp(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Yo.compose=function(n,t){Oh(n),Oh(t);for(var e=n.slice(),r=0;r<t.length;r++)so(e,t[r]);return e},Yo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=0),so(t,r)}return t};var kp=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};Yo.transformCursor=function(n,t,e){for(var r=e==="right",i=0;i<t.length;i++)n=kp(n,t[i],r);return n};var yO=Yo._tc=function(n,t,e,r){if(yp(t),yp(e),t.i!=null)so(n,{i:t.i,p:kp(t.p,e,r==="right")});else if(e.i!=null){var i=t.d;t.p<e.p&&(so(n,{d:i.slice(0,e.p-t.p),p:t.p}),i=i.slice(e.p-t.p)),i!==""&&so(n,{d:i,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)so(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)so(n,t);else{var o={d:"",p:t.p};t.p<e.p&&(o.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(o.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),c=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(c!==d)throw new Error("Delete ops delete different text in the same region of the document");o.d!==""&&(o.p=kp(o.p,e),so(n,o))}return n},kO=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Yo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=kO(n[t]);return n},wT(Yo,yO,Oh,so);var Nh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},RO=function(n){return!!n&&n.constructor===Object},Pr=function(n){return JSON.parse(JSON.stringify(n))},Lt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},lo={};Lt.registerSubtype=function(n){lo[n.name]=n},Lt.create=function(n){return n===void 0?null:Pr(n)},Lt.invertComponent=function(n){var t={p:n.p};return n.t&&lo[n.t]&&(t.t=n.t,t.o=lo[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},Lt.invert=function(n){for(var t=n.slice().reverse(),e=[],r=0;r<t.length;r++)e.push(Lt.invertComponent(t[r]));return e},Lt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Nh(n[t].p))throw new Error("Missing path")},Lt.checkList=function(n){if(!Nh(n))throw new Error("Referenced element not a list")},Lt.checkObj=function(n){if(!RO(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function yu(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 ku(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}Lt.apply=function(n,t){Lt.checkValidOp(t),t=Pr(t);for(var e={data:n},r=0;r<t.length;r++){var i=t[r];(i.si!=null||i.sd!=null)&&yu(i);for(var o=null,s=e,l="data",c=0;c<i.p.length;c++){var d=i.p[c];if(o=s,s=s[l],l=d,o==null)throw new Error("Path invalid")}if(i.t&&i.o!==void 0&&lo[i.t])s[l]=lo[i.t].apply(s[l],i.o);else if(i.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=i.na}else if(i.li!==void 0&&i.ld!==void 0)Lt.checkList(s),s[l]=i.li;else if(i.li!==void 0)Lt.checkList(s),s.splice(l,0,i.li);else if(i.ld!==void 0)Lt.checkList(s),s.splice(l,1);else if(i.lm!==void 0){if(Lt.checkList(s),i.lm!=l){var h=s[l];s.splice(l,1),s.splice(i.lm,0,h)}}else if(i.oi!==void 0)Lt.checkObj(s),s[l]=i.oi;else if(i.od!==void 0)Lt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},Lt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},Lt.incrementalApply=function(n,t,e){for(var r=0;r<t.length;r++){var i=[t[r]];n=Lt.apply(n,i),e(i,n)}return n};var wO=Lt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var r=0;r<n.length;r++)if(n[r]!==t[r]&&(!e||r!==n.length-1))return!1;return!0};Lt.append=function(n,t){if(t=Pr(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)&&(yu(t),yu(e)),wO(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&lo[t.t]){if(e.o=lo[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var r=t.p,i=0;i<e.o.length-1;i++)t.o=[e.o.pop()],t.p=r.slice(),ku(t),n.push(t);ku(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)&&(ku(t),ku(e)),n.push(t)},Lt.compose=function(n,t){Lt.checkValidOp(n),Lt.checkValidOp(t);for(var e=Pr(n),r=0;r<t.length;r++)Lt.append(e,t[r]);return e},Lt.normalize=function(n){var t=[];n=Nh(n)?n:[n];for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=[]),Lt.append(t,r)}return t},Lt.commonLengthForOps=function(n,t){var e=n.p.length,r=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&r++,e===0)return-1;if(r===0)return null;e--,r--;for(var i=0;i<e;i++){var o=n.p[i];if(i>=r||o!==t.p[i])return null}return e},Lt.canOpAffectPath=function(n,t){return Lt.commonLengthForOps({p:t},n)!=null},Lt.transformComponent=function(n,t,e,r){t=Pr(t);var i=Lt.commonLengthForOps(e,t),o=Lt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,o!=null&&l>s&&t.p[o]==e.p[o]){if(t.ld!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.ld=Lt.apply(Pr(t.ld),[c])}else if(t.od!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.od=Lt.apply(Pr(t.od),[c])}}if(i!=null){var d=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(yu(t),c=Pr(e),yu(c)),c.t&&lo[c.t]){if(t.t&&t.t===c.t){var h=lo[t.t].transform(t.o,c.o,r);if(t.si!=null||t.sd!=null)for(var C=t.p,E=0;E<h.length;E++)t.o=[h[E]],t.p=C.slice(),ku(t),Lt.append(n,t);else(!Nh(h)||h.length>0)&&(t.o=h,Lt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[i]===t.p[i])if(d){if(t.ld!==void 0)if(t.li!==void 0&&r==="left")t.ld=Pr(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[i]===e.p[i]?r==="right"&&t.p[i]++:e.p[i]<=t.p[i]&&t.p[i]++,t.lm!==void 0&&d&&e.p[i]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[i]===t.p[i])return n;var C=e.p[i],x=t.p[i],v=t.lm;(C<v||C===v&&x<v)&&t.lm--}if(e.p[i]<t.p[i])t.p[i]--;else if(e.p[i]===t.p[i]){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 x=t.p[i],v=t.lm,R=e.p[i],L=e.lm;if(R!==L)if(x===R)if(r==="left")t.p[i]=L,x===v&&(t.lm=L);else return n;else x>R&&t.p[i]--,x>L?t.p[i]++:x===L&&R>L&&(t.p[i]++,x===v&&t.lm++),(v>R||v===R&&v>x)&&t.lm--,v>L?t.lm++:v===L&&(L>R&&v>x||L<R&&v<x?r==="right"&&t.lm++:v>x?t.lm++:v===R&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var x=e.p[i],v=e.lm;C=t.p[i],C>x&&t.p[i]--,C>v&&t.p[i]++}else{var x=e.p[i],v=e.lm;C=t.p[i],C===x?t.p[i]=v:(C>x&&t.p[i]--,(C>v||C===v&&x>v)&&t.p[i]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[i]===e.p[i])if(t.oi!==void 0&&d){if(r==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[i]===e.p[i])if(r==="left")Lt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[i]==e.p[i]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return Lt.append(n,t),n},wT(Lt,Lt.transformComponent,Lt.checkValidOp,Lt.append);var SO=ST.exports;Lt.registerSubtype(SO);var LO=Lt,IO={type:LO};(function(n){n.defaultType=IO.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)})(Tu);var Fr={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var r 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],r=1;r<arguments.length;r++){var i=arguments[r];e=e[i]||(r===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],r=arguments[arguments.length-1],i=1;i<arguments.length-1;i++){var o=arguments[i];e=e[o]||(e[o]=i===arguments.length-2?r():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],r=[e],i=1;i<arguments.length-1;i++){var o=arguments[i];if(!e.hasOwnProperty(o))break;e=e[o],r.push(e)}for(var i=r.length-1;i>=0;i--){var s=r[i],o=arguments[i+1],l=s[o];(i===r.length-1||!n.hasKeys(l))&&delete s[o]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,r){var i=!1;return e.forEach(function(o){o&&(o(r),i=!0)}),i},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];setTimeout(function(){e.apply(null,r)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(Fr);var LT=Array.isArray,IT=Object.keys,DO=Object.prototype.hasOwnProperty,_O=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=LT(t),i=LT(e),o,s,l;if(r&&i){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!n(t[o],e[o]))return!1;return!0}if(r!=i)return!1;var c=t instanceof Date,d=e instanceof Date;if(c!=d)return!1;if(c&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,C=e instanceof RegExp;if(h!=C)return!1;if(h&&C)return t.toString()==e.toString();var E=IT(t);if(s=E.length,s!==IT(e).length)return!1;for(o=s;o--!==0;)if(!DO.call(e,E[o]))return!1;for(o=s;o--!==0;)if(l=E[o],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},DT=Xo,MO=RT,Jn=Uh,Ph=Tu,Kr=Fr,UO=Kr.clone,OO=_O,On=Jn.CODES,NO=Ft;function Ft(n,t,e){DT.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}DT.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=Ph.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Jn(On.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 Jn(On.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 Jn(On.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 r=n.type===void 0?Ph.defaultType:n.type;this._setType(r),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;Kr.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===On.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 r=this.inflightFetch.shift();if(r&&e.push(r),e.length&&(r=function(i){Kr.callEach(e,i)}),n)return this._emitResponseError(n,r);this.ingestSnapshot(t,r),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var r=this.pendingFetch;this.pendingFetch=[],e.callback&&r.push(e.callback);var i;if(r.length&&(i=function(o){Kr.callEach(r,o)}),n)return this._emitResponseError(n,i);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,i):i&&i(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===On.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=Fh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var r=0;r<this.pendingOps.length;r++){var e=Fh(this.pendingOps[r],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}}},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);PO(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,r=e&&e.wantSubscribe===n;if(r){e.callback=FO([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;Kr.nextTick(function(){n._handleSubscribe()})}}};function PO(n,t,e){if(t){var r=n.pop();n.push(function(i){r&&r(i),e&&e(i)})}else n.push(e)}function FO(n){return n=n.filter(Kr.truthy),n.length?function(t){Kr.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function KO(n){delete n.op,delete n.create,delete n.del}function Fh(n,t){if(n.del)return KO(t);if(t.del)return new Jn(On.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Jn(On.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Jn(On.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 r=n.type.transform(n.op,t.op,"left"),i=n.type.transform(t.op,n.op,"right");n.op=r,t.op=i}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Jn(On.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===Ph.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,r=0;r<n.op.length;r++){var i=n.op[r],o={op:[i]};this.emit("before op",o.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Fh(this.applyStack[s],o);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,o.op)),this.emit("op",o.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 c=this.data;this._setType(null),this.emit("del",c,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 Jn(On.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>=Kr.MAX_SAFE_INTEGER)return this.emit("error",new Jn(On.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 r=new Jn(On.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(r):this.emit("error",r)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(o){return this._hardRollback(o)}var i=this;Kr.nextTick(function(){i.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var r=this._tryCompose(n);if(r){r.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 r=this.pendingOps.splice(e),e=0;e<r.length;e++){var t=r[e],i=this._tryCompose(t);i?i.callbacks=i.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&&!OO(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 r={op:n},i=t&&t.source;this._submit(r,i,e)},Ft.prototype.create=function(n,t,e,r){if(typeof t=="function"?(r=t,e=null,t=null):typeof e=="function"&&(r=e,e=null),t||(t=Ph.defaultType.uri),this.type){var i=new Jn(On.ERR_DOC_ALREADY_CREATED,"Document already exists");return r?r(i):this.emit("error",i)}var o={create:{type:t,data:n}},s=e&&e.source;this._submit(o,s,r)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Jn(On.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var r={del:!0},i=n&&n.source;this._submit(r,i,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:UO(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 MO.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 r=Fh(this.pendingOps[e],t);if(r)return this._hardRollback(r)}try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}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 r=!!t.length,i=0;i<t.length;i++)r=Kr.callEach(t[i].callbacks,n)&&r;if(n&&!r)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Kr.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var nl={};nl.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 _T=Xo,MT=nl.ACTIONS,VO=Fr,$O=Nn;function Nn(n,t,e,r,i,o,s){_T.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=r,this.query=i,this.results=null,o&&o.results&&(this.results=o.results,delete o.results),this.extra=void 0,this.options=o,this.callback=s,this.ready=!1,this.sent=!1}_T.mixin(Nn),Nn.prototype.hasPending=function(){return!this.ready},Nn.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 r=this.results[e];t.push([r.id,r.version])}n.r=t}this.connection.send(n),this.sent=!0}},Nn.prototype.destroy=function(n){this.connection.canSend&&this.action===MT.querySubscribe&&this.connection.send({a:MT.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&VO.nextTick(n)},Nn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Nn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Nn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Nn.prototype._handleResponse=function(n,t,e){var r=this.callback;if(this.callback=null,n)return this._finishResponse(n,r);if(!t)return this._finishResponse(null,r);var i=this,o=1,s=function(h){if(h)return i._finishResponse(h,r);--o||i._finishResponse(null,r)};if(Array.isArray(t))o+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){o++;var c=t[l],d=this.connection.get(c.c||this.collection,l);d.ingestSnapshot(c,s)}s()},Nn.prototype._ingestSnapshots=function(n,t){for(var e=[],r=0;r<n.length;r++){var i=n[r],o=this.connection.get(i.c||this.collection,i.d);o.ingestSnapshot(i,t),e.push(o)}return e},Nn.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)},Nn.prototype._handleError=function(n){this.emit("error",n)},Nn.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 r=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(r)),this.emit("insert",r,e.index);break;case"remove":var o=e.howMany||1,i=this.results.splice(e.index,o);this.emit("remove",i,e.index);break;case"move":var o=e.howMany||1,s=this.results.splice(e.from,o);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)},Nn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var UT=Xo,HO=nl.ACTIONS,jO=Fr,OT=Ci;function Ci(n,t){if(UT.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={}}UT.mixin(Ci),Ci.prototype.submit=function(n,t){this.value=n,this.send(t)},Ci.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},Ci.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()})},Ci.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},Ci.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},Ci.prototype._message=function(){return{a:HO.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},Ci.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},Ci.prototype._callbackOrEmit=function(n,t){if(t)return jO.nextTick(t,n);n&&this.emit("error",n)};var zO=Fr,NT=Rp;function Rp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Rp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Rp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&zO.nextTick(n)};var wp={exports:{}};(function(n,t){(function(e,r){r(t)})(_n,function(e){function r(y,S){S=S|0;for(var _=Math.max(y.length-S,0),N=Array(_),H=0;H<_;H++)N[H]=y[S+H];return N}var i=function(y){var S=r(arguments,1);return function(){var _=r(arguments);return y.apply(null,S.concat(_))}},o=function(y){return function(){var S=r(arguments),_=S.pop();y.call(this,S,_)}};function s(y){var S=typeof y;return y!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function d(y){setTimeout(y,0)}function h(y){return function(S){var _=r(arguments,1);y(function(){S.apply(null,_)})}}var C;l?C=setImmediate:c?C=process.nextTick:C=d;var E=h(C);function x(y){return o(function(S,_){var N;try{N=y.apply(this,S)}catch(H){return _(H)}s(N)&&typeof N.then=="function"?N.then(function(H){v(_,null,H)},function(H){v(_,H.message?H:new Error(H))}):_(null,N)})}function v(y,S,_){try{y(S,_)}catch(N){E(R,N)}}function R(y){throw y}var L=typeof Symbol=="function";function M(y){return L&&y[Symbol.toStringTag]==="AsyncFunction"}function U(y){return M(y)?x(y):y}function F(y){return function(S){var _=r(arguments,1),N=o(function(H,$){var X=this;return y(S,function(J,ct){U(J).apply(X,H.concat(ct))},$)});return _.length?N.apply(this,_):N}}var G=typeof _n=="object"&&_n&&_n.Object===Object&&_n,W=typeof self=="object"&&self&&self.Object===Object&&self,it=G||W||Function("return this")(),at=it.Symbol,At=Object.prototype,Mt=At.hasOwnProperty,Bt=At.toString,se=at?at.toStringTag:void 0;function te(y){var S=Mt.call(y,se),_=y[se];try{y[se]=void 0;var N=!0}catch{}var H=Bt.call(y);return N&&(S?y[se]=_:delete y[se]),H}var yn=Object.prototype,be=yn.toString;function Fn(y){return be.call(y)}var Li="[object Null]",kn="[object Undefined]",gn=at?at.toStringTag:void 0;function Ii(y){return y==null?y===void 0?kn:Li:gn&&gn in Object(y)?te(y):Fn(y)}var mo="[object AsyncFunction]",Ar="[object Function]",yA="[object GeneratorFunction]",kA="[object Proxy]";function RA(y){if(!s(y))return!1;var S=Ii(y);return S==Ar||S==yA||S==mo||S==kA}var ms=9007199254740991;function xl(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=ms}function bl(y){return y!=null&&xl(y.length)&&!RA(y)}var go={};function Ht(){}function Di(y){return function(){if(y!==null){var S=y;y=null,S.apply(this,arguments)}}}var gs=typeof Symbol=="function"&&Symbol.iterator,Cc=function(y){return gs&&y[gs]&&y[gs]()};function hm(y,S){for(var _=-1,N=Array(y);++_<y;)N[_]=S(_);return N}function pn(y){return y!=null&&typeof y=="object"}var vl="[object Arguments]";function mm(y){return pn(y)&&Ii(y)==vl}var xr=Object.prototype,gm=xr.hasOwnProperty,wA=xr.propertyIsEnumerable,Bl=mm(function(){return arguments}())?mm:function(y){return pn(y)&&gm.call(y,"callee")&&!wA.call(y,"callee")},ke=Array.isArray;function Tl(){return!1}var yl=typeof e=="object"&&e&&!e.nodeType&&e,pm=yl&&!0&&n&&!n.nodeType&&n,kl=pm&&pm.exports===yl,Cm=kl?it.Buffer:void 0,Rl=Cm?Cm.isBuffer:void 0,ps=Rl||Tl,wf=9007199254740991,Sf=/^(?:0|[1-9]\d*)$/;function Lf(y,S){var _=typeof y;return S=S==null?wf:S,!!S&&(_=="number"||_!="symbol"&&Sf.test(y))&&y>-1&&y%1==0&&y<S}var If="[object Arguments]",Df="[object Array]",_f="[object Boolean]",Mf="[object Date]",Uf="[object Error]",Of="[object Function]",SA="[object Map]",LA="[object Number]",IA="[object Object]",Em="[object RegExp]",Am="[object Set]",DA="[object String]",_A="[object WeakMap]",MA="[object ArrayBuffer]",UA="[object DataView]",xm="[object Float32Array]",OA="[object Float64Array]",NA="[object Int8Array]",PA="[object Int16Array]",Nf="[object Int32Array]",FA="[object Uint8Array]",Pf="[object Uint8ClampedArray]",KA="[object Uint16Array]",VA="[object Uint32Array]",de={};de[xm]=de[OA]=de[NA]=de[PA]=de[Nf]=de[FA]=de[Pf]=de[KA]=de[VA]=!0,de[If]=de[Df]=de[MA]=de[_f]=de[UA]=de[Mf]=de[Uf]=de[Of]=de[SA]=de[LA]=de[IA]=de[Em]=de[Am]=de[DA]=de[_A]=!1;function $A(y){return pn(y)&&xl(y.length)&&!!de[Ii(y)]}function HA(y){return function(S){return y(S)}}var bm=typeof e=="object"&&e&&!e.nodeType&&e,wl=bm&&!0&&n&&!n.nodeType&&n,jA=wl&&wl.exports===bm,Ec=jA&&G.process,vm=function(){try{var y=wl&&wl.require&&wl.require("util").types;return y||Ec&&Ec.binding&&Ec.binding("util")}catch{}}(),Bm=vm&&vm.isTypedArray,zA=Bm?HA(Bm):$A,GA=Object.prototype,WA=GA.hasOwnProperty;function qA(y,S){var _=ke(y),N=!_&&Bl(y),H=!_&&!N&&ps(y),$=!_&&!N&&!H&&zA(y),X=_||N||H||$,J=X?hm(y.length,String):[],ct=J.length;for(var Ct in y)(S||WA.call(y,Ct))&&!(X&&(Ct=="length"||H&&(Ct=="offset"||Ct=="parent")||$&&(Ct=="buffer"||Ct=="byteLength"||Ct=="byteOffset")||Lf(Ct,ct)))&&J.push(Ct);return J}var Ac=Object.prototype;function XA(y){var S=y&&y.constructor,_=typeof S=="function"&&S.prototype||Ac;return y===_}function xc(y,S){return function(_){return y(S(_))}}var YA=xc(Object.keys,Object),QA=Object.prototype,JA=QA.hasOwnProperty;function Tm(y){if(!XA(y))return YA(y);var S=[];for(var _ in Object(y))JA.call(y,_)&&_!="constructor"&&S.push(_);return S}function bc(y){return bl(y)?qA(y):Tm(y)}function ym(y){var S=-1,_=y.length;return function(){return++S<_?{value:y[S],key:S}:null}}function ZA(y){var S=-1;return function(){var N=y.next();return N.done?null:(S++,{value:N.value,key:S})}}function tx(y){var S=bc(y),_=-1,N=S.length;return function H(){var $=S[++_];return $==="__proto__"?H():_<N?{value:y[$],key:$}:null}}function ex(y){if(bl(y))return ym(y);var S=Cc(y);return S?ZA(S):tx(y)}function br(y){return function(){if(y===null)throw new Error("Callback was already called.");var S=y;y=null,S.apply(this,arguments)}}function Sl(y){return function(S,_,N){if(N=Di(N||Ht),y<=0||!S)return N(null);var H=ex(S),$=!1,X=0,J=!1;function ct(ut,xt){if(X-=1,ut)$=!0,N(ut);else{if(xt===go||$&&X<=0)return $=!0,N(null);J||Ct()}}function Ct(){for(J=!0;X<y&&!$;){var ut=H();if(ut===null){$=!0,X<=0&&N(null);return}X+=1,_(ut.value,ut.key,br(ct))}J=!1}Ct()}}function _i(y,S,_,N){Sl(S)(y,U(_),N)}function ze(y,S){return function(_,N,H){return y(_,S,N,H)}}function Ff(y,S,_){_=Di(_||Ht);var N=0,H=0,$=y.length;$===0&&_(null);function X(J,ct){J?_(J):(++H===$||ct===go)&&_(null)}for(;N<$;N++)S(y[N],N,br(X))}var nx=ze(_i,1/0),Yr=function(y,S,_){var N=bl(y)?Ff:nx;N(y,U(S),_)};function Qr(y){return function(S,_,N){return y(Yr,S,U(_),N)}}function Kf(y,S,_,N){N=N||Ht,S=S||[];var H=[],$=0,X=U(_);y(S,function(J,ct,Ct){var ut=$++;X(J,function(xt,Jt){H[ut]=Jt,Ct(xt)})},function(J){N(J,H)})}var vc=Qr(Kf),Vf=F(vc);function po(y){return function(S,_,N,H){return y(Sl(_),S,U(N),H)}}var Mi=po(Kf),$f=ze(Mi,1),Hf=F($f);function Cs(y,S){for(var _=-1,N=y==null?0:y.length;++_<N&&S(y[_],_,y)!==!1;);return y}function jf(y){return function(S,_,N){for(var H=-1,$=Object(S),X=N(S),J=X.length;J--;){var ct=X[y?J:++H];if(_($[ct],ct,$)===!1)break}return S}}var Es=jf();function As(y,S){return y&&Es(y,S,bc)}function km(y,S,_,N){for(var H=y.length,$=_+(N?1:-1);N?$--:++$<H;)if(S(y[$],$,y))return $;return-1}function rx(y){return y!==y}function Rm(y,S,_){for(var N=_-1,H=y.length;++N<H;)if(y[N]===S)return N;return-1}function Ll(y,S,_){return S===S?Rm(y,S,_):km(y,rx,_)}var Bc=function(y,S,_){typeof S=="function"&&(_=S,S=null),_=Di(_||Ht);var N=bc(y),H=N.length;if(!H)return _(null);S||(S=H);var $={},X=0,J=!1,ct=Object.create(null),Ct=[],ut=[],xt={};As(y,function(Ee,ae){if(!ke(Ee)){Jt(ae,[Ee]),ut.push(ae);return}var ve=Ee.slice(0,Ee.length-1),Br=ve.length;if(Br===0){Jt(ae,Ee),ut.push(ae);return}xt[ae]=Br,Cs(ve,function(k){if(!y[k])throw new Error("async.auto task `"+ae+"` has a non-existent dependency `"+k+"` in "+ve.join(", "));ln(k,function(){Br--,Br===0&&Jt(ae,Ee)})})}),yx(),Pe();function Jt(Ee,ae){Ct.push(function(){vr(Ee,ae)})}function Pe(){if(Ct.length===0&&X===0)return _(null,$);for(;Ct.length&&X<S;){var Ee=Ct.shift();Ee()}}function ln(Ee,ae){var ve=ct[Ee];ve||(ve=ct[Ee]=[]),ve.push(ae)}function $n(Ee){var ae=ct[Ee]||[];Cs(ae,function(ve){ve()}),Pe()}function vr(Ee,ae){if(!J){var ve=br(function(k,Ni){if(X--,arguments.length>2&&(Ni=r(arguments,1)),k){var Bs={};As($,function(Hn,Vt){Bs[Vt]=Hn}),Bs[Ee]=Ni,J=!0,ct=Object.create(null),_(k,Bs)}else $[Ee]=Ni,$n(Ee)});X++;var Br=U(ae[ae.length-1]);ae.length>1?Br($,ve):Br(ve)}}function yx(){for(var Ee,ae=0;ut.length;)Ee=ut.pop(),ae++,Cs(kx(Ee),function(ve){--xt[ve]===0&&ut.push(ve)});if(ae!==H)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function kx(Ee){var ae=[];return As(y,function(ve,Br){ke(ve)&&Ll(ve,Ee,0)>=0&&ae.push(Br)}),ae}};function Co(y,S){for(var _=-1,N=y==null?0:y.length,H=Array(N);++_<N;)H[_]=S(y[_],_,y);return H}var ix="[object Symbol]";function ox(y){return typeof y=="symbol"||pn(y)&&Ii(y)==ix}var sx=1/0,zf=at?at.prototype:void 0,wm=zf?zf.toString:void 0;function Gf(y){if(typeof y=="string")return y;if(ke(y))return Co(y,Gf)+"";if(ox(y))return wm?wm.call(y):"";var S=y+"";return S=="0"&&1/y==-sx?"-0":S}function lx(y,S,_){var N=-1,H=y.length;S<0&&(S=-S>H?0:H+S),_=_>H?H:_,_<0&&(_+=H),H=S>_?0:_-S>>>0,S>>>=0;for(var $=Array(H);++N<H;)$[N]=y[N+S];return $}function ax(y,S,_){var N=y.length;return _=_===void 0?N:_,!S&&_>=N?y:lx(y,S,_)}function Wf(y,S){for(var _=y.length;_--&&Ll(S,y[_],0)>-1;);return _}function cx(y,S){for(var _=-1,N=y.length;++_<N&&Ll(S,y[_],0)>-1;);return _}function ux(y){return y.split("")}var fx="\\ud800-\\udfff",dx="\\u0300-\\u036f",hx="\\ufe20-\\ufe2f",he="\\u20d0-\\u20ff",le=dx+hx+he,mx="\\ufe0e\\ufe0f",gx="\\u200d",px=RegExp("["+gx+fx+le+mx+"]");function Cx(y){return px.test(y)}var Sm="\\ud800-\\udfff",Ex="\\u0300-\\u036f",Lm="\\ufe20-\\ufe2f",Ax="\\u20d0-\\u20ff",Ze=Ex+Lm+Ax,qf="\\ufe0e\\ufe0f",Eo="["+Sm+"]",Tc="["+Ze+"]",Il="\\ud83c[\\udffb-\\udfff]",Kn="(?:"+Tc+"|"+Il+")",Xf="[^"+Sm+"]",Yf="(?:\\ud83c[\\udde6-\\uddff]){2}",Qf="[\\ud800-\\udbff][\\udc00-\\udfff]",Im="\\u200d",Jf=Kn+"?",Zf="["+qf+"]?",Rn="(?:"+Im+"(?:"+[Xf,Yf,Qf].join("|")+")"+Zf+Jf+")*",xx=Zf+Jf+Rn,Vn="(?:"+[Xf+Tc+"?",Tc,Yf,Qf,Eo].join("|")+")",bx=RegExp(Il+"(?="+Il+")|"+Vn+xx,"g");function Dm(y){return y.match(bx)||[]}function Jr(y){return Cx(y)?Dm(y):ux(y)}function yc(y){return y==null?"":Gf(y)}var td=/^\s+|\s+$/g;function Ce(y,S,_){if(y=yc(y),y&&(_||S===void 0))return y.replace(td,"");if(!y||!(S=Gf(S)))return y;var N=Jr(y),H=Jr(S),$=cx(N,H),X=Wf(N,H)+1;return ax(N,$,X).join("")}var Ui=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,ed=/,/,vx=/(=.+)?(\s*)$/,nd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Bx(y){return y=y.toString().replace(nd,""),y=y.match(Ui)[2].replace(" ",""),y=y?y.split(ed):[],y=y.map(function(S){return Ce(S.replace(vx,""))}),y}function _m(y,S){var _={};As(y,function(N,H){var $,X=M(N),J=!X&&N.length===1||X&&N.length===0;if(ke(N))$=N.slice(0,-1),N=N[N.length-1],_[H]=$.concat($.length>0?ct:N);else if(J)_[H]=N;else{if($=Bx(N),N.length===0&&!X&&$.length===0)throw new Error("autoInject task functions require explicit parameters.");X||$.pop(),_[H]=$.concat(ct)}function ct(Ct,ut){var xt=Co($,function(Jt){return Ct[Jt]});xt.push(ut),U(N).apply(null,xt)}}),Bc(_,S)}function rr(){this.head=this.tail=null,this.length=0}function rd(y,S){y.length=1,y.head=y.tail=S}rr.prototype.removeLink=function(y){return y.prev?y.prev.next=y.next:this.head=y.next,y.next?y.next.prev=y.prev:this.tail=y.prev,y.prev=y.next=null,this.length-=1,y},rr.prototype.empty=function(){for(;this.head;)this.shift();return this},rr.prototype.insertAfter=function(y,S){S.prev=y,S.next=y.next,y.next?y.next.prev=S:this.tail=S,y.next=S,this.length+=1},rr.prototype.insertBefore=function(y,S){S.prev=y.prev,S.next=y,y.prev?y.prev.next=S:this.head=S,y.prev=S,this.length+=1},rr.prototype.unshift=function(y){this.head?this.insertBefore(this.head,y):rd(this,y)},rr.prototype.push=function(y){this.tail?this.insertAfter(this.tail,y):rd(this,y)},rr.prototype.shift=function(){return this.head&&this.removeLink(this.head)},rr.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},rr.prototype.toArray=function(){for(var y=Array(this.length),S=this.head,_=0;_<this.length;_++)y[_]=S.data,S=S.next;return y},rr.prototype.remove=function(y){for(var S=this.head;S;){var _=S.next;y(S)&&this.removeLink(S),S=_}return this};function Dl(y,S,_){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var N=U(y),H=0,$=[],X=!1;function J(xt,Jt,Pe){if(Pe!=null&&typeof Pe!="function")throw new Error("task callback must be a function");if(ut.started=!0,ke(xt)||(xt=[xt]),xt.length===0&&ut.idle())return E(function(){ut.drain()});for(var ln=0,$n=xt.length;ln<$n;ln++){var vr={data:xt[ln],callback:Pe||Ht};Jt?ut._tasks.unshift(vr):ut._tasks.push(vr)}X||(X=!0,E(function(){X=!1,ut.process()}))}function ct(xt){return function(Jt){H-=1;for(var Pe=0,ln=xt.length;Pe<ln;Pe++){var $n=xt[Pe],vr=Ll($,$n,0);vr===0?$.shift():vr>0&&$.splice(vr,1),$n.callback.apply($n,arguments),Jt!=null&&ut.error(Jt,$n.data)}H<=ut.concurrency-ut.buffer&&ut.unsaturated(),ut.idle()&&ut.drain(),ut.process()}}var Ct=!1,ut={_tasks:new rr,concurrency:S,payload:_,saturated:Ht,unsaturated:Ht,buffer:S/4,empty:Ht,drain:Ht,error:Ht,started:!1,paused:!1,push:function(xt,Jt){J(xt,!1,Jt)},kill:function(){ut.drain=Ht,ut._tasks.empty()},unshift:function(xt,Jt){J(xt,!0,Jt)},remove:function(xt){ut._tasks.remove(xt)},process:function(){if(!Ct){for(Ct=!0;!ut.paused&&H<ut.concurrency&&ut._tasks.length;){var xt=[],Jt=[],Pe=ut._tasks.length;ut.payload&&(Pe=Math.min(Pe,ut.payload));for(var ln=0;ln<Pe;ln++){var $n=ut._tasks.shift();xt.push($n),$.push($n),Jt.push($n.data)}H+=1,ut._tasks.length===0&&ut.empty(),H===ut.concurrency&&ut.saturated();var vr=br(ct(xt));N(Jt,vr)}Ct=!1}},length:function(){return ut._tasks.length},running:function(){return H},workersList:function(){return $},idle:function(){return ut._tasks.length+H===0},pause:function(){ut.paused=!0},resume:function(){ut.paused!==!1&&(ut.paused=!1,E(ut.process))}};return ut}function Ao(y,S){return Dl(y,1,S)}var xs=ze(_i,1);function Zr(y,S,_,N){N=Di(N||Ht);var H=U(_);xs(y,function($,X,J){H(S,$,function(ct,Ct){S=Ct,J(ct)})},function($){N($,S)})}function kc(){var y=Co(arguments,U);return function(){var S=r(arguments),_=this,N=S[S.length-1];typeof N=="function"?S.pop():N=Ht,Zr(y,S,function(H,$,X){$.apply(_,H.concat(function(J){var ct=r(arguments,1);X(J,ct)}))},function(H,$){N.apply(_,[H].concat($))})}}var Rc=function(){return kc.apply(null,r(arguments).reverse())},id=Array.prototype.concat,_l=function(y,S,_,N){N=N||Ht;var H=U(_);Mi(y,S,function($,X){H($,function(J){return J?X(J):X(null,r(arguments,1))})},function($,X){for(var J=[],ct=0;ct<X.length;ct++)X[ct]&&(J=id.apply(J,X[ct]));return N($,J)})},Mm=ze(_l,1/0),wc=ze(_l,1),Sc=function(){var y=r(arguments),S=[null].concat(y);return function(){var _=arguments[arguments.length-1];return _.apply(this,S)}};function Ml(y){return y}function xo(y,S){return function(_,N,H,$){$=$||Ht;var X=!1,J;_(N,function(ct,Ct,ut){H(ct,function(xt,Jt){xt?ut(xt):y(Jt)&&!J?(X=!0,J=S(!0,ct),ut(null,go)):ut()})},function(ct){ct?$(ct):$(null,X?J:S(!1))})}}function Cn(y,S){return S}var bs=Qr(xo(Ml,Cn)),ti=po(xo(Ml,Cn)),Ul=ze(ti,1);function od(y){return function(S){var _=r(arguments,1);_.push(function(N){var H=r(arguments,1);typeof console=="object"&&(N?console.error&&console.error(N):console[y]&&Cs(H,function($){console[y]($)}))}),U(S).apply(null,_)}}var Um=od("dir");function Om(y,S,_){_=br(_||Ht);var N=U(y),H=U(S);function $(J){if(J)return _(J);var ct=r(arguments,1);ct.push(X),H.apply(this,ct)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}X(null,!0)}function sd(y,S,_){_=br(_||Ht);var N=U(y),H=function($){if($)return _($);var X=r(arguments,1);if(S.apply(this,X))return N(H);_.apply(null,[null].concat(X))};N(H)}function Nm(y,S,_){sd(y,function(){return!S.apply(this,arguments)},_)}function Pm(y,S,_){_=br(_||Ht);var N=U(S),H=U(y);function $(J){if(J)return _(J);H(X)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}H(X)}function bo(y){return function(S,_,N){return y(S,N)}}function Lc(y,S,_){Yr(y,bo(U(S)),_)}function Ol(y,S,_,N){Sl(S)(y,bo(U(_)),N)}var vo=ze(Ol,1);function Ic(y){return M(y)?y:o(function(S,_){var N=!0;S.push(function(){var H=arguments;N?E(function(){_.apply(null,H)}):_.apply(null,H)}),y.apply(this,S),N=!1})}function ir(y){return!y}var Bo=Qr(xo(ir,ir)),Nl=po(xo(ir,ir)),Dc=ze(Nl,1);function Fm(y){return function(S){return S==null?void 0:S[y]}}function vs(y,S,_,N){var H=new Array(S.length);y(S,function($,X,J){_($,function(ct,Ct){H[X]=!!Ct,J(ct)})},function($){if($)return N($);for(var X=[],J=0;J<S.length;J++)H[J]&&X.push(S[J]);N(null,X)})}function or(y,S,_,N){var H=[];y(S,function($,X,J){_($,function(ct,Ct){ct?J(ct):(Ct&&H.push({index:X,value:$}),J())})},function($){$?N($):N(null,Co(H.sort(function(X,J){return X.index-J.index}),Fm("value")))})}function _c(y,S,_,N){var H=bl(S)?vs:or;H(y,S,U(_),N||Ht)}var Mc=Qr(_c),Pl=po(_c),Uc=ze(Pl,1);function Km(y,S){var _=br(S||Ht),N=U(Ic(y));function H($){if($)return _($);N(H)}H()}var Oc=function(y,S,_,N){N=N||Ht;var H=U(_);Mi(y,S,function($,X){H($,function(J,ct){return J?X(J):X(null,{key:ct,val:$})})},function($,X){for(var J={},ct=Object.prototype.hasOwnProperty,Ct=0;Ct<X.length;Ct++)if(X[Ct]){var ut=X[Ct].key,xt=X[Ct].val;ct.call(J,ut)?J[ut].push(xt):J[ut]=[xt]}return N($,J)})},To=ze(Oc,1/0),K=ze(Oc,1),q=od("log");function j(y,S,_,N){N=Di(N||Ht);var H={},$=U(_);_i(y,S,function(X,J,ct){$(X,J,function(Ct,ut){if(Ct)return ct(Ct);H[J]=ut,ct()})},function(X){N(X,H)})}var mt=ze(j,1/0),wt=ze(j,1);function Gt(y,S){return S in y}function Ie(y,S){var _=Object.create(null),N=Object.create(null);S=S||Ml;var H=U(y),$=o(function(J,ct){var Ct=S.apply(null,J);Gt(_,Ct)?E(function(){ct.apply(null,_[Ct])}):Gt(N,Ct)?N[Ct].push(ct):(N[Ct]=[ct],H.apply(null,J.concat(function(){var ut=r(arguments);_[Ct]=ut;var xt=N[Ct];delete N[Ct];for(var Jt=0,Pe=xt.length;Jt<Pe;Jt++)xt[Jt].apply(null,ut)})))});return $.memo=_,$.unmemoized=y,$}var Yt;c?Yt=process.nextTick:l?Yt=setImmediate:Yt=d;var Nc=h(Yt);function ld(y,S,_){_=_||Ht;var N=bl(S)?[]:{};y(S,function(H,$,X){U(H)(function(J,ct){arguments.length>2&&(ct=r(arguments,1)),N[$]=ct,X(J)})},function(H){_(H,N)})}function wn(y,S){ld(Yr,y,S)}function Fl(y,S,_){ld(Sl(S),y,_)}var ad=function(y,S){var _=U(y);return Dl(function(N,H){_(N[0],H)},S,1)},yo=function(y,S){var _=ad(y,S);return _.push=function(N,H,$){if($==null&&($=Ht),typeof $!="function")throw new Error("task callback must be a function");if(_.started=!0,ke(N)||(N=[N]),N.length===0)return E(function(){_.drain()});H=H||0;for(var X=_._tasks.head;X&&H>=X.priority;)X=X.next;for(var J=0,ct=N.length;J<ct;J++){var Ct={data:N[J],priority:H,callback:$};X?_._tasks.insertBefore(X,Ct):_._tasks.push(Ct)}E(_.process)},delete _.unshift,_};function Kl(y,S){if(S=Di(S||Ht),!ke(y))return S(new TypeError("First argument to race must be an array of functions"));if(!y.length)return S();for(var _=0,N=y.length;_<N;_++)U(y[_])(S)}function ko(y,S,_,N){var H=r(y).reverse();Zr(H,S,_,N)}function Wt(y){var S=U(y);return o(function(N,H){return N.push(function(X,J){if(X)H(null,{error:X});else{var ct;arguments.length<=2?ct=J:ct=r(arguments,1),H(null,{value:ct})}}),S.apply(this,N)})}function Vm(y){var S;return ke(y)?S=Co(y,Wt):(S={},As(y,function(_,N){S[N]=Wt.call(this,_)})),S}function cd(y,S,_,N){_c(y,S,function(H,$){_(H,function(X,J){$(X,!J)})},N)}var Vl=Qr(cd),ud=po(cd),$m=ze(ud,1);function Hm(y){return function(){return y}}function Ro(y,S,_){var N=5,H=0,$={times:N,intervalFunc:Hm(H)};function X(ut,xt){if(typeof xt=="object")ut.times=+xt.times||N,ut.intervalFunc=typeof xt.interval=="function"?xt.interval:Hm(+xt.interval||H),ut.errorFilter=xt.errorFilter;else if(typeof xt=="number"||typeof xt=="string")ut.times=+xt||N;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof y=="function"?(_=S||Ht,S=y):(X($,y),_=_||Ht),typeof S!="function")throw new Error("Invalid arguments for async.retry");var J=U(S),ct=1;function Ct(){J(function(ut){ut&&ct++<$.times&&(typeof $.errorFilter!="function"||$.errorFilter(ut))?setTimeout(Ct,$.intervalFunc(ct)):_.apply(null,arguments)})}Ct()}var ei=function(y,S){S||(S=y,y=null);var _=U(S);return o(function(N,H){function $(X){_.apply(null,N.concat(X))}y?Ro(y,$,H):Ro($,H)})};function $l(y,S){ld(xs,y,S)}var Hl=Qr(xo(Boolean,Ml)),Oi=po(xo(Boolean,Ml)),jl=ze(Oi,1);function fd(y,S,_){var N=U(S);vc(y,function($,X){N($,function(J,ct){if(J)return X(J);X(null,{value:$,criteria:ct})})},function($,X){if($)return _($);_(null,Co(X.sort(H),Fm("value")))});function H($,X){var J=$.criteria,ct=X.criteria;return J<ct?-1:J>ct?1:0}}function zl(y,S,_){var N=U(y);return o(function(H,$){var X=!1,J;function ct(){var Ct=y.name||"anonymous",ut=new Error('Callback function "'+Ct+'" timed out.');ut.code="ETIMEDOUT",_&&(ut.info=_),X=!0,$(ut)}H.push(function(){X||($.apply(null,arguments),clearTimeout(J))}),J=setTimeout(ct,S),N.apply(null,H)})}var jm=Math.ceil,Gl=Math.max;function wo(y,S,_,N){for(var H=-1,$=Gl(jm((S-y)/(_||1)),0),X=Array($);$--;)X[N?$:++H]=y,y+=_;return X}function So(y,S,_,N){var H=U(_);Mi(wo(0,y,1),S,H,N)}var zm=ze(So,1/0),Gm=ze(So,1);function Wm(y,S,_,N){arguments.length<=3&&(N=_,_=S,S=ke(y)?[]:{}),N=Di(N||Ht);var H=U(_);Yr(y,function($,X,J){H(S,$,X,J)},function($){N($,S)})}function Wl(y,S){var _=null,N;S=S||Ht,vo(y,function(H,$){U(H)(function(X,J){arguments.length>2?N=r(arguments,1):N=J,_=X,$(!X)})},function(){S(_,N)})}function ql(y){return function(){return(y.unmemoized||y).apply(null,arguments)}}function Xl(y,S,_){_=br(_||Ht);var N=U(S);if(!y())return _(null);var H=function($){if($)return _($);if(y())return N(H);var X=r(arguments,1);_.apply(null,[null].concat(X))};N(H)}function qm(y,S,_){Xl(function(){return!y.apply(this,arguments)},S,_)}var dd=function(y,S){if(S=Di(S||Ht),!ke(y))return S(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return S();var _=0;function N($){var X=U(y[_++]);$.push(br(H)),X.apply(null,$)}function H($){if($||_===y.length)return S.apply(null,arguments);N(r(arguments,1))}N([])},Tx={apply:i,applyEach:Vf,applyEachSeries:Hf,asyncify:x,auto:Bc,autoInject:_m,cargo:Ao,compose:Rc,concat:Mm,concatLimit:_l,concatSeries:wc,constant:Sc,detect:bs,detectLimit:ti,detectSeries:Ul,dir:Um,doDuring:Om,doUntil:Nm,doWhilst:sd,during:Pm,each:Lc,eachLimit:Ol,eachOf:Yr,eachOfLimit:_i,eachOfSeries:xs,eachSeries:vo,ensureAsync:Ic,every:Bo,everyLimit:Nl,everySeries:Dc,filter:Mc,filterLimit:Pl,filterSeries:Uc,forever:Km,groupBy:To,groupByLimit:Oc,groupBySeries:K,log:q,map:vc,mapLimit:Mi,mapSeries:$f,mapValues:mt,mapValuesLimit:j,mapValuesSeries:wt,memoize:Ie,nextTick:Nc,parallel:wn,parallelLimit:Fl,priorityQueue:yo,queue:ad,race:Kl,reduce:Zr,reduceRight:ko,reflect:Wt,reflectAll:Vm,reject:Vl,rejectLimit:ud,rejectSeries:$m,retry:Ro,retryable:ei,seq:kc,series:$l,setImmediate:E,some:Hl,someLimit:Oi,someSeries:jl,sortBy:fd,timeout:zl,times:zm,timesLimit:So,timesSeries:Gm,transform:Wm,tryEach:Wl,unmemoize:ql,until:qm,waterfall:dd,whilst:Xl,all:Bo,allLimit:Nl,allSeries:Dc,any:Hl,anyLimit:Oi,anySeries:jl,find:bs,findLimit:ti,findSeries:Ul,forEach:Lc,forEachSeries:vo,forEachLimit:Ol,forEachOf:Yr,forEachOfSeries:xs,forEachOfLimit:_i,inject:Zr,foldl:Zr,foldr:ko,select:Mc,selectLimit:Pl,selectSeries:Uc,wrapSync:x};e.default=Tx,e.apply=i,e.applyEach=Vf,e.applyEachSeries=Hf,e.asyncify=x,e.auto=Bc,e.autoInject=_m,e.cargo=Ao,e.compose=Rc,e.concat=Mm,e.concatLimit=_l,e.concatSeries=wc,e.constant=Sc,e.detect=bs,e.detectLimit=ti,e.detectSeries=Ul,e.dir=Um,e.doDuring=Om,e.doUntil=Nm,e.doWhilst=sd,e.during=Pm,e.each=Lc,e.eachLimit=Ol,e.eachOf=Yr,e.eachOfLimit=_i,e.eachOfSeries=xs,e.eachSeries=vo,e.ensureAsync=Ic,e.every=Bo,e.everyLimit=Nl,e.everySeries=Dc,e.filter=Mc,e.filterLimit=Pl,e.filterSeries=Uc,e.forever=Km,e.groupBy=To,e.groupByLimit=Oc,e.groupBySeries=K,e.log=q,e.map=vc,e.mapLimit=Mi,e.mapSeries=$f,e.mapValues=mt,e.mapValuesLimit=j,e.mapValuesSeries=wt,e.memoize=Ie,e.nextTick=Nc,e.parallel=wn,e.parallelLimit=Fl,e.priorityQueue=yo,e.queue=ad,e.race=Kl,e.reduce=Zr,e.reduceRight=ko,e.reflect=Wt,e.reflectAll=Vm,e.reject=Vl,e.rejectLimit=ud,e.rejectSeries=$m,e.retry=Ro,e.retryable=ei,e.seq=kc,e.series=$l,e.setImmediate=E,e.some=Hl,e.someLimit=Oi,e.someSeries=jl,e.sortBy=fd,e.timeout=zl,e.times=zm,e.timesLimit=So,e.timesSeries=Gm,e.transform=Wm,e.tryEach=Wl,e.unmemoize=ql,e.until=qm,e.waterfall=dd,e.whilst=Xl,e.all=Bo,e.allLimit=Nl,e.allSeries=Dc,e.any=Hl,e.anyLimit=Oi,e.anySeries=jl,e.find=bs,e.findLimit=ti,e.findSeries=Ul,e.forEach=Lc,e.forEachSeries=vo,e.forEachLimit=Ol,e.forEachOf=Yr,e.forEachOfSeries=xs,e.forEachOfLimit=_i,e.inject=Zr,e.foldl=Zr,e.foldr=ko,e.select=Mc,e.selectLimit=Pl,e.selectSeries=Uc,e.wrapSync=x,Object.defineProperty(e,"__esModule",{value:!0})})})(wp,wp.exports);var PT={exports:{}},Sp=PT.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),r=2;e===1/0;r*=2)e=Math.log(Math.pow(2,n/r))/Math.log(t)*r;for(var i=e-Math.floor(e),o="",r=0;r<Math.floor(e);r++){var s=Math.floor(Math.random()*t).toString(t);o=s+o}if(i){var l=Math.pow(t,i),s=Math.floor(Math.random()*l).toString(t);o=s+o}var c=parseInt(o,t);return c!==1/0&&c>=Math.pow(2,n)?Sp(n,t):o};Sp.rack=function(n,t,e){var r=function(o){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Sp(n,t)}while(Object.hasOwnProperty.call(i,l));return i[l]=o,l},i=r.hats={};return r.get=function(o){return r.hats[o]},r.set=function(o,s){return r.hats[o]=s,r},r.bits=n||128,r.base=t||16,r};var FT=Xo,GO=OT,WO=NT,Kh=Fr,Lp=wp.exports,qO=PT.exports,KT=nl.ACTIONS,VT=Ve;function Ve(n,t){if(FT.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}FT.mixin(Ve),Ve.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Ve.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Ve.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||qO();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Ve.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(r){if(r)return t._callbackOrEmit(r,n);var i=Object.keys(t._remotePresenceInstances);Lp.parallel([function(o){Lp.each(e,function(s,l){t.localPresences[s].destroy(l)},o)},function(o){if(!t._wantsDestroy)return o();Lp.each(i,function(s,l){t._remotePresenceInstances[s].destroy(l)},o)}],function(o){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(o,n)})})},Ve.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?KT.presenceSubscribe:KT.presenceUnsubscribe,r=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[r]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,r,this)},Ve.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._receiveUpdate=function(n,t){var e=Kh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var r=this,i=Kh.digOrCreate(this._remotePresenceInstances,t.id,function(){return r._createRemotePresence(t.id)});i.receiveUpdate(t)},Ve.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Ve.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()}},Ve.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Ve.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Ve.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 r=this;this.subscribe(function(i){r._callEachOrEmit(n,i)})},Ve.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Ve.prototype._callbackOrEmit=function(n,t){if(t)return Kh.nextTick(t,n);n&&this.emit("error",n)},Ve.prototype._createLocalPresence=function(n){return new GO(this,n)},Ve.prototype._createRemotePresence=function(n){return new WO(this,n)},Ve.prototype._callEachOrEmit=function(n,t){var e=Kh.callEach(n,t);!e&&t&&this.emit("error",t)};var Ru=OT,$T=Uh,XO=Fr,HT=$T.CODES,YO=Vr;function Vr(n,t){Ru.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()}Vr.prototype=Object.create(Ru.prototype),Vr.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:HT.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,Ru.prototype.submit.call(this,n,t)},Vr.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),Ru.prototype.destroy.call(this,n)},Vr.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={})})}},Vr.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)},Vr.prototype._transformAgainstOp=function(n,t){var e=this,r=this._doc._dataStateVersion;this._pendingMessages.forEach(function(i){var o=e._docDataVersionByPresenceVersion[i.pv];if(!(o>=r))try{i.p=e._transformPresence(i.p,n,t),e._docDataVersionByPresenceVersion[i.pv]=r}catch(l){var s=e._getCallback(i.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(i){this.emit("error",i)}},Vr.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Vr.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Vr.prototype._message=function(){var n=Ru.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Vr.prototype._transformPresence=function(n,t,e){var r=this._doc.type;if(!XO.supportsPresence(r))throw new $T(HT.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+r.name);return r.transformPresence(n,t,e)};var jT={};(function(n){var t=Tu,e=Uh,r=Fr,i=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[c];if(d==null||typeof d!="object")return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(i.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(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(i.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,c){if(typeof l!="object")return new e(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(i.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=c.create,h=t.map[d.type];if(!h)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(E){return E}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var C=o(l,c.op);if(C)return C;l.v++}else l.v++};function o(l,c){if(!l.type)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,c)}catch(h){return new e(i.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,c,d){if(c.v!=null&&c.v!==d.v)return new e(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(c.create||"op"in c)return new e(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in c||c.create||c.del)||"op"in d&&c.create)return new e(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in c){if(!l)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,d.op,"left")}catch(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,d){d=d||{};for(var h=0;h<c.length;h++){var C=c[h];if(d._normalizeLegacyJson0Ops)try{s(l,C)}catch{return new e(i.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=C.v;var E=n.apply(l,C);if(E)return E}},n.transformPresence=function(l,c,d){var h=this.checkOp(c);if(h)return h;var C=l.t;if(typeof C=="string"&&(C=t.map[C]),!C)return{code:i.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!r.supportsPresence(C))return{code:i.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:C.transformPresence(l.p,c.op,d)}catch(E){return{code:i.ERR_PRESENCE_TRANSFORM_FAILED,message:E.message||E}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var d=c.op;if(!!d){var h=l.data;d.length>1&&(h=r.clone(h));for(var C=0;C<d.length;C++){var E=d[C];typeof E.lm=="string"&&(E.lm=+E.lm);for(var x=E.p,v=h,R=0;R<x.length;R++){var L=x[R];Object.prototype.toString.call(v)=="[object Array]"?x[R]=+L:v.constructor===Object&&(x[R]=L.toString()),v=v[L]}C<d.length-1&&(h=t.defaultType.apply(h,[E]))}}}}})(jT);var wu=NT,QO=jT,JO=gr;function gr(n,t){wu.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()}gr.prototype=Object.create(wu.prototype),gr.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},gr.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),wu.prototype.destroy.call(this,n)},gr.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)},gr.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))}})}},gr.prototype._handleOp=function(n,t,e){var r=e===this.src;this._transformAgainstOp(n,r),this._cacheOp(n,r),this._setPendingPresence()},wu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},wu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},gr.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)}},gr.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++):QO.transformPresence(this._pending,t,e)}var r=this._pending.v>=this._doc.version;return r&&this._stopCachingOps(),r},gr.prototype._startCachingOps=function(){this._opCache=[]},gr.prototype._stopCachingOps=function(){this._opCache=null},gr.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var zT=VT,ZO=YO,tN=JO;function _a(n,t,e){var r=_a.channel(t,e);zT.call(this,n,r),this.collection=t,this.id=e}var eN=_a;_a.prototype=Object.create(zT.prototype),_a.channel=function(n,t){return n+"."+t},_a.prototype._createLocalPresence=function(n){return new ZO(this,n)},_a.prototype._createRemotePresence=function(n){return new tN(this,n)};var nN=rN;function rN(n,t,e,r,i){this.id=n,this.v=t,this.type=e,this.data=r,this.m=i}var iN=nN,GT=Xo,WT=Su;function Su(n,t,e,r,i){if(GT.EventEmitter.call(this),typeof i!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=r,this.collection=e,this.callback=i,this.sent=!1}GT.mixin(Su),Su.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Su.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Su.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,r=new iN(this.id,t.v,t.type,t.data,e);this.callback(null,r)};var qT=WT,oN=Fr,sN=nl.ACTIONS,lN=Ip;function Ip(n,t,e,r,i,o){if(qT.call(this,n,t,e,r,o),!oN.isValidVersion(i))throw new Error("Snapshot version must be a positive integer or null");this.version=i}Ip.prototype=Object.create(qT.prototype),Ip.prototype._message=function(){return{a:sN.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var XT=WT,aN=Fr,cN=nl.ACTIONS,uN=Dp;function Dp(n,t,e,r,i,o){if(XT.call(this,n,t,e,r,o),!aN.isValidTimestamp(i))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=i}Dp.prototype=Object.create(XT.prototype),Dp.prototype._message=function(){return{a:cN.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var fN=NO,dN=$O,hN=VT,YT=eN,mN=lN,gN=uN,QT=Xo,Ma=Uh,ie=nl.ACTIONS,JT=Tu,$r=Fr,Lu=RT,Iu=Ma.CODES;function ZT(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var pN=kt;function kt(n){QT.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=ZT(n),this.bindToSocket(n)}QT.mixin(kt),kt.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=ZT(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(r){try{var i=typeof r.data=="string"?JSON.parse(r.data):r.data}catch{Lu.warn("Failed to parse message",r);return}e.debug&&Lu.info("RECV",JSON.stringify(i));var o={data:i};if(e.emit("receive",o),!!o.data)try{e.handleMessage(o.data)}catch(s){$r.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(r){e.emit("connection error",r)},n.onclose=function(r){r==="closed"||r==="Closed"?e._setState("closed",r):r==="stopped"||r==="Stopped by server"?e._setState("stopped",r):e._setState("disconnected",r)}},kt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=t2(n.error,n),delete n.error),n.a){case ie.initLegacy:return this._handleLegacyInit(n);case ie.handshake:return this._handleHandshake(t,n);case ie.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ie.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ie.queryUnsubscribe:return;case ie.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 ie.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ie.bulkSubscribe:case ie.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ie.snapshotFetch:case ie.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ie.fetch:var r=this.getExisting(n.c,n.d);r&&r._handleFetch(t,n.data);return;case ie.subscribe:case ie.unsubscribe:var r=this.getExisting(n.c,n.d);r&&r._handleSubscribe(t,n.data);return;case ie.op:var r=this.getExisting(n.c,n.d);r&&r._handleOp(t,n);return;case ie.presence:return this._handlePresence(t,n);case ie.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ie.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ie.presenceRequest:return this._handlePresenceRequest(t,n);case ie.pingPong:return this._handlePingPong(t);default:Lu.warn("Ignoring unrecognized message",n)}};function t2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}kt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var r in t.data){var i=t.data[r],o=this.getExisting(t.c,r);o&&(n?o[e](n):i.error?o[e](t2(i.error)):o[e](null,i))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var r=t.b[s],o=this.getExisting(t.c,r);o&&o[e](n)}else if(t.b)for(var r in t.b){var o=this.getExisting(t.c,r);o&&o[e](n)}else Lu.error("Invalid bulk message",t)},kt.prototype._reset=function(){this.agent=null},kt.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 Ma(Iu.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 r in this.queries){var i=this.queries[r];i._onConnectionStateChanged()}for(var o in this.collections){var s=this.collections[o];for(var r in s)s[r]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var r in this._snapshotRequests){var c=this._snapshotRequests[r];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},kt.prototype.startBulk=function(){this.bulk||(this.bulk={})},kt.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},kt.prototype._sendBulk=function(n,t,e){if(!!e){var r=[],i={},o=0,s;for(var l in e){var c=e[l];c==null?r.push(l):(i[l]=c,s=l,o++)}if(r.length===1){var l=r[0];this.send({a:n,c:t,d:l})}else r.length&&this.send({a:"b"+n,c:t,b:r});if(o===1){var d=i[s];this.send({a:n,c:t,d:s,v:d})}else o&&this.send({a:"b"+n,c:t,b:i})}},kt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var r=this.bulk[t.collection]||(this.bulk[t.collection]={}),i=r[n]||(r[n]={}),o=i.hasOwnProperty(t.id);return i[t.id]=e,o}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},kt.prototype.sendFetch=function(n){return this._sendActions(ie.fetch,n,n.version)},kt.prototype.sendSubscribe=function(n){return this._sendActions(ie.subscribe,n,n.version)},kt.prototype.sendUnsubscribe=function(n){return this._sendActions(ie.unsubscribe,n)},kt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ie.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)},kt.prototype.send=function(n){this.debug&&Lu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},kt.prototype.ping=function(){if(!this.canSend)throw new Ma(Iu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ie.pingPong};this.send(n)},kt.prototype.close=function(){this.socket.close()},kt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},kt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),r=e[t];return r||(r=e[t]=new fN(this,n,t),this.emit("doc",r)),r._wantsDestroy=!1,r},kt.prototype._destroyDoc=function(n){!n._wantsDestroy||($r.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},kt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},kt.prototype._createQuery=function(n,t,e,r,i){var o=this.nextQueryId++,s=new dN(n,this,o,t,e,r,i);return this.queries[o]=s,s.send(),s},kt.prototype._destroyQuery=function(n){delete this.queries[n.id]},kt.prototype.createFetchQuery=function(n,t,e,r){return this._createQuery(ie.queryFetch,n,t,e,r)},kt.prototype.createSubscribeQuery=function(n,t,e,r){return this._createQuery(ie.querySubscribe,n,t,e,r)},kt.prototype.hasPending=function(){return!!(this._firstDoc(Vh)||this._firstQuery(Vh)||this._firstSnapshotRequest())};function Vh(n){return n.hasPending()}kt.prototype.hasWritePending=function(){return!!this._firstDoc(CN)};function CN(n){return n.hasWritePending()}kt.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 r=this._firstSnapshotRequest();if(r){r.once("ready",this._nothingPendingRetry(n));return}$r.nextTick(n)},kt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$r.nextTick(function(){t.whenNothingPending(n)})}},kt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var r in e){var i=e[r];if(n(i))return i}}},kt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},kt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},kt.prototype.fetchSnapshot=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new mN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},kt.prototype.fetchSnapshotByTimestamp=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new gN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},kt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},kt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},kt.prototype._initializeHandshake=function(){this.send({a:ie.handshake,id:this.id})},kt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},kt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},kt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Ma(Iu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(JT.map[n.type]!==JT.defaultType)return this.emit("error",new Ma(Iu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Ma(Iu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},kt.prototype.getPresence=function(n){var t=this,e=$r.digOrCreate(this._presences,n,function(){return new hN(t,n)});return e._wantsDestroy=!1,e},kt.prototype.getDocPresence=function(n,t){var e=YT.channel(n,t),r=this,i=$r.digOrCreate(this._presences,e,function(){return new YT(r,n,t)});return i._wantsDestroy=!1,i},kt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var r={a:n,ch:e.channel,seq:t};return this.send(r),r.seq},kt.prototype._addPresence=function(n){$r.digOrCreate(this._presences,n.channel,function(){return n})},kt.prototype._handlePresenceSubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},kt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},kt.prototype._handlePresence=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},kt.prototype._handlePresenceRequest=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var e2=pN,EN=Tu;const Du={err:1001,msg:"user auth error",name:"AuthError"},$h={err:1002,msg:"you don't have required permission",name:"PermissionError"},_p={err:1003,msg:"Too many user connected",name:"MaxUserError"},_u={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},AN={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},xN={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},rl="x-live-editor-token",Ua="x-live-editor-base-url",dn=I("auth-connection");function bN(n){try{n()}catch(t){dn.error(t)}}class vN{constructor(t,e){g(this,"enabled",!0);g(this,"connection");g(this,"ws");g(this,"retryCount");g(this,"events",new Cb.EventEmitter);g(this,"token",null);g(this,"resourceToken",null);g(this,"reAuth",async()=>{if(this.connection&&this.reauthFunc){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}});this.url=t,this.reauthFunc=e,this.retryCount=0,window.addEventListener("offline",()=>{var r;this.token="fake",(r=this.connection)==null||r.close()})}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async auth(t){p(dn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,r=await window.fetch(e,{method:"GET",headers:{[rl]:t.token,[Ua]:this.getBase64BaseURL()},credentials:"include"});return r.status,this.enabled?(this.token=t.token,await r.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Ua]:li(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new G6.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(e2.prototype),p(dn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const r=this.connection.handleMessage.bind(this.connection);let i=0;this.connection.handleMessage=o=>{var l;const s=o;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in s||s.a==="pong")this.handleMessage(s);else{Object.prototype.hasOwnProperty.call(s,"a")&&s.a==="hs"?this.retryCount>0&&(i+=1):i!==0&&(dn.info("retrying re-auth success"),i=0,this.emitAuthRecover()),Object.prototype.hasOwnProperty.call(s,"a")&&s.a!=="init"&&s.a!=="hs"&&(this.retryCount=0);try{r(s)}catch(c){if((c==null?void 0:c.type)==="writeConflict"){this.emitWriteConflictError(c,s);return}if((l=c==null?void 0:c.message)!=null&&l.startsWith("Cannot invert subtype")){this.emitWriteConflictError(c,s);return}throw c}}},e2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc){this.retryCount>=5&&(dn.warn("retry auth times exceed 5, broadcast auth error"),this.emitAuthError()),this.retryCount+=1,dn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){dn.error(t),setTimeout(()=>this.handleAuthError(),0)}}}emitPermissionError(){const t=new Error($h.msg);t.code=$h.err,this.events.emit("error",t)}emitAuthRecover(){this.events.emit("authRecover")}emitAuthError(){const t=new Error(Du.msg);t.code=Du.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(_u.msg);t.code=_u.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 r=e.err;if(r===Du.err)dn.warn("auth error"),this.handleAuthError();else if(r===_p.err)dn.warn(_p.msg),this.emitMaxUsersError();else if(r===_u.err){dn.warn(_u.msg);try{this.emitRequestReloadError()}catch(i){dn.error(`error occurred while process reload error: ${JSON.stringify(i)}`)}finally{this.end(!1)}}else r===$h.err?this.emitPermissionError():(dn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError())}get(t,e){return p(dn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(p(dn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onAuthError(t){this.events.addListener("error",t)}onAuthRecover(t){this.events.addListener("authRecover",t)}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){p(dn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){p(dn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),bN(()=>{var r;return(r=this.connection)==null?void 0:r.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}I("utils/file");function BN(){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}BN();async function TN(n){const e=n.size,r=Math.floor((e+102400-1)/102400),i=new W6.Hash;for(let s=0;s<r;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();i.update(new Uint8Array(h))}const o=i.digest();return li(o)}const Ei=I("sharedb-doc/client"),yN=Ab.default.create();class kN{constructor(t,e,r){g(this,"connection");g(this,"auth");g(this,"doc",null);g(this,"reauthFunc");g(this,"clientId",Z());g(this,"getDoc",async()=>{const t=r=>new Promise((i,o)=>{r.fetch(s=>{s?o(s):i()})});p(Ei,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth),window.addEventListener("online",async()=>{await this.connection.init({...this.auth,token:"fake"})});const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),Ei.debug(e),e});this.auth=t;const i=`${e}/${this.auth.appId}/${this.auth.docId}`;EN.register(Bd.type),this.connection=new vN(i,r),this.reauthFunc=r}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Ei,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,r=>{(t==="error"||this.doc)&&e(r)})}onAuthError(t){this.connection.onAuthError(t)}onAuthRecover(t){this.connection.onAuthRecover(t)}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,r,i,o){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...o},data:{name:r,size:i}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const r=`${this.apiServer()}/resources`;try{const i=`${r}/hash`,o=await this.request(i,{method:"post",headers:{[rl]:this.connection.token},data:{resources:t}});return o.data&&Array.isArray(o.data)?o.data:[]}catch{return[]}}async uploadFile(t,e,r,i,o){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=x=>{Ei.info(`on progress: ${x.loaded}`);let v=x.loaded*100/s;v>100&&(v=100),i(v)},c=await TN(e),d=await this.getFileUrlByHash(t,c,e.name,e.size,r);if(d)return i(-1),d;let h=t;o!=null&&o.thumbnail&&(h+="/thumbnail");const C=new FormData;C.append("file-size",`${e.size}`),C.append("file-hash",c),C.append("file",e,e.name);const E=await this.request(h,{method:"post",data:C,withCredentials:!0,headers:{...r},onUploadProgress:l});return Ei.info(E),i(100),Array.isArray(E.data)?E.data[0]:E.data}async uploadResource(t,e=()=>{},r){const o=`${this.apiServer()}/resources`;p(Ei,this.connection.token,"no connection token");const s=await this.uploadFile(o,t,{[rl]:this.connection.token},e,r);return p(Ei,s,"no result"),s}async request(t,e){var o,s;let r=this.connection.token,i;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),p(Ei,r,"no token"),c.headers={...c.headers,[rl]:r,[Ua]:this.connection.getBase64BaseURL()};try{return await yN(t,c)}catch(d){if(i=d,((o=d==null?void 0:d.response)==null?void 0:o.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;r=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw p(Ei,i,"no error"),i}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=xb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Ei,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const r=`${this.apiServer()}/resources/external/${li(t)}`;return(await this.request(r)).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 i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken&&o.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}reAuth(){this.connection.reAuth()}}function RN(){return{blocks:[{id:Z(),type:"text",text:[]}],comments:{},meta:{}}}const Mp=I("block-ids");class wN{constructor(){g(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((i,o)=>o-i);for(let i=0;i<e.length;i++){const o=e[i];if(o>=t){const s=this.ids.get(o);p(Mp,s!==void 0,"old id is not exists"),this.ids.delete(o),this.ids.set(o+1,s)}}const r=Z();this.ids.set(t,r)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((r,i)=>r-i);for(let r=0;r<e.length;r++){const i=e[r];if(i>t){const o=this.ids.get(i);p(Mp,o!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i-1,o)}}}getId(t){let e=this.ids.get(t);return e||(e=Z(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class SN{constructor(){g(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new wN,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 r=0;r<e.length;r++){const i=e[r],o=i[1].getById(t);if(o)return{containerId:i[0],blockIndex:o[0]}}return p(Mp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class n2{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,r)=>{t[r]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Up=I("op-parse-handler");class LN{constructor(t,e){g(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const r={...t,containerId:(i=>i==="blocks"?"root":i)(t.containerId)};this.actions.push(r)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,r){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:r})}onDeleteBlockData(t,e,r){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:r})}onInsertBlockData(t,e,r,i){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:r,value:i})}onUpdateBlockText(t,e,r){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:r})}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,r=new Map,i=new SN,o=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of o)if(s.type==="deleteBlock"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);i.onDeleteBlock(l.containerId,l.blockIndex);const d=r.get(c);d&&(Up.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),r.delete(c));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,c=`${l.containerId}-${l.blockIndex}`;if(e.has(c)){Up.warn("delete block data after delete block, ignore it");continue}const d=i.getBlockId(l.containerId,l.blockIndex);let h=r.get(d);h||(h=new n2,r.set(d,h)),h.delete(l.key)}else p(Up,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);let d=r.get(c);d||(d=new n2,r.set(c,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(r.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:d}=i.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(c,d,l.toDocBlockDelta(),this.local)})}}const $e=I("op-parser");class r2{}class Op{constructor(t){g(this,"key");this.key=t}}function IN(n,t,e){const r=t.concat(),i=r[0];if(typeof i!="number"||(r.shift(),r.length===1))return!1;const o=r[0];if(typeof o!="object"||!o.i||Object.keys(o).length!==1)return!1;for(let l=1;l<r.length;l++){const c=r[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=o.i;p($e,s.id,"block id is required"),p($e,s.type,"block type is required");for(let l=1;l<r.length;l++){const c=r[l],d=c[0],h=c[1];s[d]=h.i}return e.onInsertBlock(n,i,s),!0}function Np(n,t,e,r){if(e==="upsert"&&IN(n,t,r))return;p($e,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const i=t.concat(),o=i[0];i.shift();const s=[];for(;i.length>0;){const l=i[0];if(l==="text"){const c=i[1];if(p($e,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),p($e,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),i.splice(0,2),e==="upsert"){const h=c.e;r.onUpdateBlockText(n,o,h)}p($e,i.length===0,`invalid block ops.length !== 0, ${JSON.stringify(i)}`)}else if(Array.isArray(l)){p($e,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];p($e,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const d=l[1];if(c==="text"){if(p($e,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&r.onInsertBlockData(n,o,c,d.i),d.r&&e==="remove"&&r.onDeleteBlockData(n,o,c),d.et==="rich-text"&&e==="upsert"){const C=d.e;r.onUpdateBlockText(n,o,C)}}else e==="remove"&&d.r&&s.push(new Op(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i);i.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new r2),e==="upsert"&&c.i&&r.onInsertBlock(n,o,c.i),i.shift()}else{p($e,typeof l=="string","data is not string"),p($e,l!=="text","data !== 'text'"),p($e,i.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(i)}`);const c=l,d=i[1];e==="remove"&&d.r&&s.push(new Op(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i),i.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof r2?r.onDeleteBlock(n,o):l instanceof Op?r.onDeleteBlockData(n,o,l.key):p($e,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function DN(n,t,e){$e.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function _N(n,t,e){const r=n[1],i=n[2];p($e,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),p($e,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?$e.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&e.onUpdateComment(r):i.i?t==="upsert"&&e.onCreateComment(r):i.r?t==="remove"&&e.onDeleteComment(r):$e.error(`unknown comment op, ${JSON.stringify(n)}`)}function Pp(n,t,e){const r=n[0];if(Array.isArray(r)){r.forEach(s=>{Pp(s,t,e)});return}const i=r;if(p($e,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){DN(n);return}if(i==="comments"){_N(n,t,e);return}const o=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Np(o,s,t,e)}):n.slice(1).forEach(s=>{Np(o,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(o),s.i&&t==="upsert"&&e.onCreateContainer(o,s.i)}else p($e,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Np(o,n.slice(1),t,e)}function Fp(n,t,e){const r=new LN(t,e);for(let i=0;i<2;i++){const o=i===0?"remove":"upsert",s=gt.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Pp(c,o,r)}):Pp(s,o,r)}r.end()}const MN=I("sharedb-comments");function Kp(n){const t=n.blocks;p(MN,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([r,i])=>{Array.isArray(i)&&(e.blocks[r]=i)}),gt.default(e)}function i2(n){const{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}}function Vp(n,t){const e=EO(t),{comments:r,meta:i,blocks:o,...s}=e,l={...n,blocks:o,...s},c=gt.default(l);return delete c.children,c}const oe=I("sharedb-doc/doc-container"),o2="ot-json1";Bd.type.registerSubtype(AO.type),Bd.type.name=o2,Bd.type.invert=null;class Mu extends oa{constructor(e,r,i=!0){super();g(this,"doc");g(this,"client");g(this,"localPresence");g(this,"remoteCaretHandler",new pO);g(this,"batching",0);g(this,"status","clean");g(this,"disableLogout");g(this,"destroyed",!1);g(this,"handleNothingPending",()=>{this.setStatus("clean")});g(this,"handleCreate",()=>{this.handleReload("doc created")});g(this,"handleDel",()=>{});g(this,"handleReload",e=>{this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)})});g(this,"handleReset",async e=>{const r=new Error(`reset doc: ${e}`);r.code="ResetDoc",this.callbacks.forEach(i=>{var o;return(o=i.onError)==null?void 0:o.call(i,r)}),this.destroy()});g(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});g(this,"insertObject",async(e,r,i)=>{const o=[e,r,{i}];return this.submitOp(o)});g(this,"deleteObject",async(e,r)=>{const i=[e,r,{r:!0}];return this.submitOp(i)});g(this,"replaceObject",async(e,r,i)=>{const o=[e,r,{r:!0,i}];return this.submitOp(o)});g(this,"updateObject",async(e,r,i)=>{const o=this.data()[e][r],s=[e,r];return Object.entries(i).forEach(([l,c])=>{if(!jc.default(o[l],c))if(o[l]===void 0){if(c!=null){const d={i:c};s.push([l,d])}}else if(c==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:c};s.push([l,d])}}),Object.entries(o).forEach(([l,c])=>{if((i[l]===void 0||i[l]===null)&&c!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});g(this,"broadcastMessage",async e=>{const r={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(r)});g(this,"data",()=>this.doc.data);g(this,"submitOp",async e=>new Promise((r,i)=>{if(this.destroyed){oe.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},o=>{o?(oe.error(`invalid op, ${o.message}, ${JSON.stringify(e)}`),i(o),oe.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):r()}),this.doc.data||(oe.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));g(this,"createDoc",async e=>new Promise((r,i)=>{this.doc.create(e,o2,o=>{o?i(o):r()})}));g(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const r=e.map(({containerId:i,blocks:o})=>[oo(i),{i:o}]);return this.submitOp([r])});g(this,"submitDeleteChildContainer",async e=>{const r=[oo(e),{r:!0}];return this.submitOp(r)});g(this,"submitInsertBlock",async(e,r,i)=>{const o=[oo(e),r,{i}];return this.submitOp(o)});g(this,"submitDeleteBlock",async(e,r)=>{const i=[oo(e),r,{r:!0}];return this.submitOp(i)});g(this,"submitUpdateBlockData",async(e,r,i)=>{if(i.delete.length===0&&Object.keys(i.insert).length===0)return Promise.resolve();const o=[oo(e),r],s=new Set(i.delete);Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c)){const h={r:!0,i:d};o.push([c,h])}});const l=new Set(Object.keys(i.insert));return i.delete.forEach(c=>{if(l.has(c))return;const d={r:!0};o.push([c,d])}),Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c))return;const h={i:d};o.push([c,h])}),this.submitOp(o)});g(this,"submitUpdateRichText",async(e,r,i)=>{const o=[oo(e),r,"text",{e:i,et:"rich-text"}];return this.submitOp(o)});g(this,"handleOp",(e,r,i)=>{if(this.destroyed){oe.warn("handleOp: destroyed");return}try{Fp(e,this,!!r)}catch(o){throw oe.error(o),o}});this.client=e,this.doc=r,this.doc.preventCompose=!0,this.disableLogout=i,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,p(oe,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const r=new kN(e.auth,e.serverUrl,e.reauthFunc),i=await r.getDoc(),o=new Mu(r,i,e.disableLogout);if(i.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await o.createDoc(e.templateData||RN())}return await o.initPresence(),await o.subscribe(),o.initEvents(),o}catch(r){throw oe.error(r),oe.error(`failed to load doc: ${JSON.stringify(r)}`),r}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onAuthError(e=>{this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}),this.client.onAuthRecover(()=>{this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}),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,r)=>{if(this.localPresence)e();else{const i=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);i.on("receive",(o,s)=>{this.onCustomMessage(s)}),i.subscribe(o=>{o?r(o):(this.localPresence=i.create(Z()),e())})}})}subscribe(){return new Promise((e,r)=>{this.doc.subscribe(i=>{i?r(i):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return io(this.data())}getContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[oo(e)];return p(oe,i,`no container data: ${e}`),gt.default(i)}findContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[oo(e)];return i!=null?i:null}getBlockData(e,r){const i=this.data();p(oe,i,"no doc data");const o=i[oo(e)];p(oe,o,`no container data: ${e}`);const s=o[r];return p(oe,s,`no block data: ${r}`),gt.default(s)}localInsertBlock(e,r,i){return this.submitInsertBlock(e,r,i),this.getBlockData(e,r)}localDeleteBlock(e,r){const i=this.getBlockData(e,r);return this.submitDeleteBlock(e,r),i}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(oe,o.text,"no block text");const s=gt.default(o.text);this.submitUpdateRichText(e,r,i);const l=fn.apply(s,i);return p(oe,l,"no block text"),l}localUpdateBlockData(e,r,i){const o=gt.default(this.getBlockData(e,r));return this.submitUpdateBlockData(e,r,i),o}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(r=>{this.submitDeleteChildContainer(r)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(r=>i2(r))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const r=this.data().comments[e];return Kp(r)}localCreateComment(e,r){const i=Vp(e,r),s=["comments",i.id,{i}];return this.submitOp(s)}localDeleteComment(e){const r=["comments",e,{r:!0}];return this.submitOp(r)}localUpdateComment(e,r){const i=Vp(e,r),o=["comments",e.id,{r:!0,i}];return this.submitOp(o)}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,r,i){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onDeleteBlock)==null?void 0:s.call(o,Da(e),r,i)})}onInsertBlock(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Da(e),r,i,o)})}onUpdateBlockData(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Da(e),r,i,o)})}onUpdateBlockText(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Da(e),r,i,o)})}onDeleteContainer(e,r){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not delete root container in doc"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,Da(e),r)})}onCreateContainer(e,r,i){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not create root container in doc"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,Da(e),r,i)})}onDeleteComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteComment)==null?void 0:o.call(i,e,r)})}onCreateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onCreateComment)==null?void 0:o.call(i,e,r)})}onUpdateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onUpdateComment)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){const r=e;(r==null?void 0:r.type)==="custom"&&(r==null?void 0:r.clientId)!==this.client.clientId?this.callbacks.forEach(i=>{var o;return(o=i.onCustomMessage)==null?void 0:o.call(i,r.data)}):(r==null?void 0:r.type)==="onlineUsers"&&setTimeout(()=>{const i={type:"custom",data:e,clientId:"-"};this.onCustomMessage(i)})}onAuthRecover(){this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}async addResources(e){let r=[];return e.forEach(o=>{const s=o.split("|");r.push(...s)}),r=Array.from(new Set(r)),await this.client.getFileUrlsByHashes(r)}async uploadResource(e,r){var o;return{resourceId:await this.client.uploadResource(e,(o=r==null?void 0:r.onProgress)!=null?o:()=>{})}}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}request(e,r){return this.client.request(e,r)}getUser(){const e=this.client.clientId,{permission:r,userId:i,displayName:o,avatarUrl:s}=this.client.auth;return{permission:r,clientId:e,userId:i,displayName:o,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return io(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return io(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:io(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:io(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,r){Fp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}triggerReAuth(){this.client.reAuth()}}I("remote-cursor");class s2{constructor(t){g(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});g(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));g(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const r=this.editor.findBlockById(e);r&&this.editor.reloadBlock(r)})});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 l2=I("remote-cursor-decorator");class $p{decorateText(t,e,r){const i=t.doc.getRemoteUsers();if(!i)return{};const o=new Map,{containerId:s,blockIndex:l}=e[e.length-1];p(l2,typeof s=="string","invalid path containerId"),p(l2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),d=un(r);return i.getSimpleCursors(c.id).forEach((C,E)=>{E>d&&(E=d);const x=C.map(R=>({id:Z(),type:"remote-cursor",name:R.user.displayName,time:R.time,rainbowIndex:R.user.rainbowIndex})),v=o.get(E);v?v.push(...x):o.set(E,x)}),{insertions:o}}}const Hp=I("sharedb-doc/share-db-server"),UN=Ab.default.create();class ON{constructor(t,e){g(this,"auth");g(this,"clientId",Z());this.serverUrl=e,this.auth=t}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Hp,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}apiServer(){const t=`${this.serverUrl}/${this.auth.appId}/${this.auth.docId}`;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}`)}getBaseURL(){const t=new URL(this.apiServer());return`${t.protocol}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async request(t,e){var o;const r=this.auth.token,i=e||{};i.url=t,i.headers||(i.headers={}),p(Hp,r,"no token"),i.headers={...i.headers,[rl]:r,[Ua]:this.getBase64BaseURL()};try{return await UN(t,i)}catch(s){throw(o=s.response)!=null&&o.data&&(s.responseData=s.response.data),s}}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=xb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Hp,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).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 i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken,e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}}const NN=I("sharedb-doc/share-db-server");function a2(n){const t=new URL(n);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}function PN(n){return li(a2(n))}class Hh extends oa{constructor(e){super();g(this,"remoteUsers",new Bu);g(this,"client");this.options=e,this.client=new ON(e.auth,e.serverUrl)}destroy(){}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}getRemoteUsers(){return this.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return io(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return io(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:io(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:io(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}parseHistoryData(e,r){Fp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}static async auth(e,r){p(NN,e.token,"no auth token");const i=`${a2(r)}/auth`,o=await window.fetch(i,{method:"GET",headers:{[rl]:e.token,[Ua]:PN(r)},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return await o.json()}static async load(e){const r=`${e.serverUrl}/${e.auth.appId}/${e.auth.docId}`;return await this.auth(e.auth,r),new Hh(e)}}class c2 extends Be.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,r){if(Xt(ai(this.editor,t)))return;const i=this.editor.getBlockByIndex(t,e),o=et(this.editor.getContainerById(t));o&&this.emit("change",this.editor,o,i,r)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}onInsertBlock(t,e){setTimeout(()=>{this.handleChild(t,e,"insert")})}onDeleteBlock(t,e){this.handleChild(t,e,"remove")}destroy(){this.editor.doc.unregisterCallback(this)}}function u2(n,t){n.addCustom("child-block-tracker",()=>new c2(n)).addListener("change",t)}function f2(n,t){n.addCustom("child-block-tracker",()=>new c2(n)).removeListener("change",t)}const zat="",FN={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"}},KN={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},VN={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"}};D.mergeLang({"zh-CN":FN,"en-US":KN,"ja-JP":VN});const Gat="";I("button");function pr(n,t,e,r,i){const o=B("button",["editor-button"],null);return o.setAttribute("data-button-id",n),i&&o.setAttribute(`data-editor-tooltip-${i}`,t),e?typeof e=="string"?e.startsWith("<")?o.innerHTML=e:o.innerText=e:o.appendChild(e):o.innerText=t,r&&(r.indexOf("checked")!==-1&&z(o,"checked"),r.indexOf("disabled")!==-1&&(o.disabled=!0),r.indexOf("primary")!==-1&&z(o,"primary")),o}const Wat="",jh=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
31
|
+
`)}const o=new Blob([r],{type:"text/html"});return fa([{type:"text/plain",data:new Blob([i],{type:"text/plain"})},{type:"text/html",data:o}]),!0}const IU=Object.freeze(Object.defineProperty({__proto__:null,editorHandleEnter:X5,editorHandleDelete:Y5,editorHandleBackspace:Q5,editorHandleInsertBr:J5,editorHandlePastePlainText:Z5,isSelectedCodeTextBlock:tT,getSelectedCodeBlockMarkdown:eT,editorHandleCopyMarkdown:Ap},Symbol.toStringTag,{value:"Module"})),Ih={ArrowDown:g5,ArrowUp:m5,ArrowLeft:d5,ArrowRight:h5,"Shift+ArrowDown":p5,"Shift+ArrowUp":A5,"Shift+ArrowLeft":C5,"Shift+ArrowRight":E5,"CtrlOrCmd+ArrowLeft":b5,"CtrlOrCmd+ArrowRight":v5,"CtrlOrCmd+Shift+ArrowLeft":B5,"CtrlOrCmd+Shift+ArrowRight":T5,"CtrlOrCmd+ArrowUp":y5,"CtrlOrCmd+ArrowDown":fp,"CtrlOrCmd+Shift+ArrowUp":k5,"CtrlOrCmd+Shift+ArrowDown":dp,"CtrlOrCmd+A":mp,Home:D5,End:_5,"Shift+Home":L5,"Shift+End":I5,PageUp:P5,PageDown:F5,"Shift+PageUp":K5,"Shift+PageDown":V5,"CtrlOrCmd+Z":AU,"CtrlOrCmd+Shift+Z":xU,Enter:X5,Delete:Y5,Backspace:Q5,"Shift+Enter":J5,"CtrlOrCmd+Shift+V":Z5,"CtrlOrCmd+Shift+C":Ap};function nT(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function rT(n,t,e){if(t.type==="embed"){const o=t.embedData,s=o.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)o.src=l;else{let c="";s.split("|").forEach(h=>{const C=e.get(h);C&&(c+=c?`|${C}`:`${C}`)}),c&&(o.src=c)}}return}const r=t.text;r&&r.forEach(o=>{if(o.attributes&&o.attributes.src&&typeof o.attributes.src=="string"){const s=e.get(o.attributes.src);s&&(o.attributes.src=s)}});const i=t.children;i&&i.forEach(o=>{n.blocks[o].forEach(l=>{rT(n,l,e)})})}function iT(n,t,e){if(e.size===0)return;t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);o.replaceResources?o.replaceResources(i,e):rT(t,i,e)})}async function DU(n,t){let e=t.filter(s=>s.indexOf(":")===-1);const r=[];e.forEach(s=>{const l=s.split("|");r.push(...l)}),e=Array.from(new Set(r)),e=r;const i=await n.doc.addResources(e),o=new Map;if(e.length!==i.length)return o;for(let s=0;s<e.length;s++)o.set(e[s],i[s]);return o}function _U(n,t){var l,c,d,h;const r=t.meta.serverId;if(!r||typeof r!="string")return!1;const i=(c=(l=n.doc).getServerMeta)==null?void 0:c.call(l);if(!i)return!1;const o=/.*(?=\/)/;return((d=(i.serverId||"").match(o))==null?void 0:d[0])===((h=r.match(o))==null?void 0:h[0])}async function xp(n,t){const r=t.meta.resources;if(!r||Object.keys(r).length===0)return;let i=new Map;if(_U(n,t)){const s=Array.from(Object.keys(r));i=await DU(n,s),iT(n,t,i)}const o=new Map;Object.entries(r).forEach(([s,l])=>{i.get(s)===void 0&&s!==l&&o.set(s,l)}),o.size!==0&&iT(n,t,o)}async function MU(n,t,e){await xp(n,t),n.undoManager.runInGroup(()=>{const{start:r,end:i}=n.selection.range,o=n.getBlockById(r.blockId);if(r.blockId===i.blockId&&pe(o)){const s=rt(o),l=n.getBlockIndex(o),[c]=n.insertDocAt(s,l+1,t,e);c&&n.selection.selectBlock(c,dt(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=va(n);n.insertDoc(s,l,t,e)}})}const UU=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function OU(n){let t;for(const e of UU)if(t=n[e],t)break;return t||null}class NU{constructor(t){g(this,"editor");g(this,"handlers",[]);g(this,"hookExecutionAttempt",(t,e,r)=>{for(let i=0;i<this.handlers.length;i++){const o=this.handlers[i];if(o.handleBeforeCopy){const s=o.handleBeforeCopy(this.editor,e,r);if(s===!0)return!0;if(typeof s=="object"&&s!=null)return s}}});g(this,"onPasteText",async(t,e)=>{const r=new DataTransfer;r.setData("text/plain",t);const i=await this.editor.dataConverter.fromData(this.editor,r,e);if(i){const o=[];this.pasteDocs(i,null,o)}});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:r,blockIndex:i,offset:o}=va(this.editor);this.handleBeforeInsertText(r,i,o,e)||(this.defaultInsertText(this.editor,r,i,o,e),this.handleAfterInsertText(r,i,o,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 r=this.handlers[e];r.handleChanged&&r.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleRemoteChanged&&r.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:r,offset:i}=va(this.editor);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,r,i)}}onUpdateCompositionText(t,e,r){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,r),this.editor.selection.caret.update();const{containerId:i,blockIndex:o,offset:s}=va(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,i,o,s,r)}this.editor.selection.updateLastCaretRect()}onCopy(t){wU(this.editor,t,this.hookExecutionAttempt)}onCopyWithoutEvent(){SU(this.editor,this.hookExecutionAttempt)}onCut(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeCut&&i.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const r=this.editor.selection.focusedBlock;pe(r)&&this.editor.deleteBlock(r)}else Bh(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),r=Array.from(t.clipboardData.files);e.then(async i=>{i&&this.pasteDocs(i,t,r)})}onFocus(){z(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,r)=>{var s,l;const i=(s=e.order)!=null?s:1;return((l=r.order)!=null?l:1)-i})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,r,i))return!0}return!1}handleAfterInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,r,i))return!0}return!1}handleBeforeKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,r,i,o){X1(this.editor,o)}defaultHandleKeydown(t,e){return nT(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePasteDoc&&await i.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await MU(this.editor,t,e);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPasteDoc&&await i.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e,r){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,r))return}const i=OU(t);if(!!i){await this.pasteDoc(i);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}forEach(t){this.handlers.forEach(t)}}function PU(n,t,e){const r=ji(t,e);return r.remove(),r}I("copy-dom-attributes");const oT=["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 FU(n,t){for(let l=0;l<oT.length;l++){const c=oT[l];t[c]=n[c]}const e=n.attributes,r=t.attributes,i=[],o=[];for(let l=0;l<e.length;l++){const c=e[l],d=r.getNamedItem(c.name);d?d.value!==c.value&&(d.value=c.value,o.push(c)):i.push(c)}const s=[];for(let l=0;l<r.length;l++){const c=r[l];e.getNamedItem(c.name)||s.push(c)}i.forEach(l=>{t.setAttribute(l.name,l.value)}),o.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function sT(n){const t=Array.from(n.childNodes).filter(e=>!vv(e));return t.forEach(e=>{e.remove()}),t}function lT(n,t,e){var d;const r=n.getContainerById(t),i=ji(r,e),o=Ko(i),s=n.doc.getBlockData(t,e),l=Qt(n,i);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,i,s))n.editorBlockRenders.updateBlock(n,o,i,s);else{const h=n.editorBlocks.createBlock(o,r,s),C=sT(h);sT(i),C.forEach(x=>{i.appendChild(x)});const E=Hd(h);if(E){const x=Hd(i);x&&x.remove(),i.appendChild(E)}FU(h,i)}Pv(n,i,s),n.blockHooks.forEach(h=>{var C;(C=h.update)==null||C.call(h,n,o,r,i,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const KU=I("transform-selection");function aT(n,t,e,r){const{range:i}=n.selection,{anchor:o,focus:s}=i;if(o.blockId!==t&&s.blockId!==t)return i;p(KU,o.isSimple()&&s.isSimple(),"invalid text pos type");let l=o;if(o.blockId===t){const d=fn.transformCursor(o.offset,e,r);l=lt(t,d,"normal")}let c=s;if(s.blockId===t){const d=fn.transformCursor(s.offset,e,r);c=lt(t,d,"normal")}return Xe(n,{anchor:l,focus:c})}const VU=I("handle-block-text-changed");function $U(n,t,e,r,i){const o=n.getContainerById(t),s=ji(o,e),l=n.doc.getBlockData(t,e);if(p(VU,l.text,"no block text"),Ev(n,s).setBlockText(n,s,l.text),!i){const c=aT(n,l.id,r,i);n.selection.setRange(c,{noScroll:!0})}}function HU(n,t){const e=gt.default(n);return t.delete.forEach(i=>{delete e[i]}),{...e,...t.insert}}function cT(n,t,e,r){const i=Qt(n,t);i.handleDeleteBlock&&i.handleDeleteBlock(n,t,e,r),n.emit("blockDeleted",n,t,e,r)}function jU(n,t,e,r){const i=n.getBlockByIndex(t,e);i.querySelectorAll('[data-type="editor-block"]').forEach(o=>{cT(n,o,r,{child:!0})}),cT(n,i,r,{child:!1})}const Or=I("editor-doc");class zU extends oa{constructor(e,r,i){super();g(this,"localEvents",[]);this.editor=e,this.externalDoc=r,this.externalDoc.registerCallback(this),this.registerLocalEvents(i)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var r,i;return(i=(r=this.externalDoc).getVersionHelper)==null?void 0:i.call(r)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,r){return this.externalDoc.getBlockData(e,r)}verifyBlockWritable(e,r){const i=this.editor.getBlockByIndex(e,r);p(Or,this.editor.isBlockWritable(i),`block is not writable, ${e}, ${r}`)}localUpdateBlockText(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const s=this.getBlockData(e,r),l=s.text;p(Or,l,`no text, ${e}, ${r}`);const c=aT(this.editor,s.id,i,!0),d=fn.apply(l,i);this.localEvents.forEach(C=>C.onBeforeUpdateBlockText(e,s.id,l,d,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,r,i);return this.editor.selection.setRange(c,o),h}localUpdateBlockData(e,r,i,o){p(Or,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,r);if(!this.editor.isBlockWritable(s)){const h=Array.from(i.delete).filter(E=>E!=="comments"),C=Object.keys(i.insert).filter(E=>E!=="comments");(h.length>0||C.length>0)&&p(Or,!1,`block is not writable, comment supported only, ${JSON.stringify(i)}}`)}const l=gt.default(this.getBlockData(e,r)),c=gt.default(HU(l,i));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,c,o));const d=this.externalDoc.localUpdateBlockData(e,r,i,o);return this.editor.selection.setRange(Vo(this.editor,o)),d}localInsertBlock(e,r,i,o,s){p(Or,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,r,i,o));const l=this.externalDoc.localInsertBlock(e,r,i,o);return s!=null&&s.noFocus||this.editor.selection.setRange(Vo(this.editor,o),s),l}localDeleteBlock(e,r,i){p(Or,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const o=gt.default(this.getBlockData(e,r));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,r,o,i));const s=this.externalDoc.localDeleteBlock(e,r,i);return this.editor.selection.setRange(Vo(this.editor,i)),s}localDeleteChildContainers(e){return p(Or,!this.editor.readonly,"editor is readonly"),e.forEach(r=>{const i=gt.default(this.getContainerBlocks(r));this.localEvents.forEach(o=>o.onBeforeDeleteChildContainer(r,i))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){p(Or,!this.editor.readonly,"editor is readonly");const r=gt.default(e);r.forEach(i=>{this.localEvents.forEach(o=>o.onBeforeInsertChildContainer(i.containerId,i.blocks))}),this.externalDoc.localInsertChildContainers(r)}onRequestReload(e){Or.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(i=>{var o;return(o=i.onRequestReload)==null?void 0:o.call(i,e)});const r=!1;this.editor.emit("docChanged",this.editor,r)}onUpdateBlockText(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,r,i,o)}),$U(this.editor,e,r,i,o),this.editor.emit("docChanged",this.editor,o)}onUpdateBlockData(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,o)}),lT(this.editor,e,r),this.editor.emit("docChanged",this.editor,o)}onInsertBlock(e,r,i,o){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,r,i,o)});const s=this.editor.getContainerById(e);TI(this.editor,s,r,i),this.editor.emit("docChanged",this.editor,o)}onDeleteBlock(e,r,i){jU(this.editor,e,r,i),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,i)});const o=this.editor.getContainerById(e);PU(this.editor,o,r),this.editor.emit("docChanged",this.editor,i)}onInsertChildContainer(e,r,i){this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,e,r,i)})}onDeleteChildContainer(e,r){this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,e)})}onStatusChanged(e){this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)})}onError(e){this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}uploadResource(e,r){return this.externalDoc.uploadResource(e,r)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,r){return this.externalDoc.buildResourceUrl(e,r)}request(e,r){return this.externalDoc.request(e,r)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}triggerReAuth(){var e,r;return(r=(e=this.externalDoc).triggerReAuth)==null?void 0:r.call(e)}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,r,i;return(i=(r=(e=this.externalDoc).getServerMeta)==null?void 0:r.call(e))!=null?i:{}}reset(e){Or.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function uT(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 Dh=I("undo-action");class La{constructor(t,e,r){g(this,"beforeRange");g(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=r}undo(t){return!1}redo(t){return!1}combinable(t){return p(Dh,t,"no other action"),!1}combine(t){p(Dh,!1,"no other")}setAfterRange(t){this.afterRange&&Dh.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const r=t.doc.findContainerBlocks(this.containerId);return r?r.some(i=>i.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const r=t.doc.toJSON();for(let i=0;i<e.children.length;i++){const o=e.children[i];if(!r.blocks[o])return Dh.warn(`container (${o}) not found, deleted by others?`),!1}}return!0}}const Ia=I("block-action");class fT extends La{constructor(e,r,i,o,s){super(e,r,s);g(this,"blockData");g(this,"blockIndex");this.blockData=gt.default(o),this.blockIndex=i}deleteBlock(e,r){if(!this.findContainerById(e,this.containerId))return Ia.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return Ia.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const o=e.getBlockById(this.blockData.id);if(!o)return!1;try{p(Ia,this.blockIndex===bt(o),"invalid block index"),bh(e,o,Vo(e,r))}catch(s){Ia.warn(s.message),e.selection.selectBlock(o,0)}return!0}insertBlock(e,r){if(!this.findContainerById(e,this.containerId))return Ia.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{Ta(e,this.containerId,this.blockIndex,gt.default(this.blockData),r)}catch(i){Ia.warn(i.message);const o=e.doc.getContainerBlocks(this.containerId),s=Math.min(o.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}I("insert-block-action");class GU extends fT{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class WU extends fT{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class qU extends La{constructor(e){super(e,ft(e.rootContainer),e.selection.range.toDocRange());g(this,"actions",[])}addAction(e){uT(this.actions,e),this.afterRange=e.afterRange}undo(e){let r=!1;return this.actions.concat().reverse().forEach(i=>{i.undo(e)&&(r=!0)}),r}redo(e){let r=!1;return this.actions.forEach(i=>{i.redo(e)&&(r=!0)}),r}setAfterRange(e){this.afterRange=e;const r=this.actions[this.actions.length-1];!r||r instanceof La&&(r.afterRange||r.setAfterRange(e))}}const qo=I("update-block-data-action");class _h extends La{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeBlockData");g(this,"afterBlockData");g(this,"blockId");this.blockId=i,p(qo,this.blockId===o.id,"invalid block id"),p(qo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=gt.default(o),this.afterBlockData=gt.default(s),p(qo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return qo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(qo,i,"no container"),yh(e,r,_h.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return qo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;p(qo,e,"no editor");const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(qo,i,"no container"),yh(e,r,_h.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const r=gt.default(e);return delete r.id,delete r.type,r}}const tl=I("update-block-text-action");class bu extends La{constructor(e,r,i,o,s,l){super(e,r,l);g(this,"beforeRichTextData");g(this,"afterRichTextData");g(this,"blockId");g(this,"type");this.blockId=i,this.beforeRichTextData=gt.default(o),this.afterRichTextData=gt.default(s),this.type=bu.calType(o,s)}static calType(e,r){p(tl,e,"no old data"),p(tl,r,"no new data");const o=fn.diff(e,r),s=new Set;let l=!1;const c=h=>qb(h)?`cjk_${h}`:Gb(h)?"number":Md(h)?"space":Wb(h)?"letter":"unknown";let d=!1;return o.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_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Th(e,i,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return tl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return tl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Th(e,i,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof bu)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const r=e.beforeRange,i=r.anchor;if(!i.isSimple())return!1;const o=this.afterRange;if(!o)return!1;const s=o.anchor;return!(!s.isSimple()||s.blockId!==r.anchor.blockId||s.offset!==i.offset)}combine(e){p(tl,e instanceof bu,"invalid action type");const r=e;this.afterRichTextData=r.afterRichTextData,this.afterRange=e.afterRange}}const dT=I("child-container-action");class hT extends La{constructor(t,e,r){super(t,e,t.selection.range.toDocRange()),this.blocks=r}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(dT.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(dT.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:gt.default(this.blocks)}]),!0)}}class XU extends hT{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class YU extends hT{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Nr=I("undo");class QU{constructor(t){g(this,"editor");g(this,"actions",[]);g(this,"undoCursor");g(this,"currentGroup",null);g(this,"groupCounter",0);g(this,"undoRedoing",!1);g(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):(uT(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(p(Nr,!this.currentGroup,"current group already exists"),this.currentGroup=new qU(this.editor),this.groupCounter=1):(p(Nr,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){p(Nr,this.currentGroup,"current group not exists"),p(Nr,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Nr.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 Nr.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(Vo(this.editor,t.beforeRange))}catch(e){Nr.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(Vo(this.editor,e)):Nr.warn("no after range")}catch(e){Nr.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,r,i,o){this.undoRedoing||(this.prepareSaveUndoState(),fn.diff(r,i).length!==0&&this.addAction(new bu(this.editor,t,e,r,i,o)))}onBeforeUpdateBlockData(t,e,r,i,o){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new _h(this.editor,t,e,r,i,o);this.addAction(s)}onBeforeInsertBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),p(Nr,e>=0,"invalid block index"),p(Nr,r,"no block data"),this.addAction(new GU(this.editor,t,e,r,i)))}onBeforeDeleteBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new WU(this.editor,t,e,r,i)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new XU(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new YU(this.editor,t,e)))}}class JU{async fromData(t,e){const r=e.getData("text/x-ones-editor-doc");if(r)return{"text/x-ones-editor-doc":JSON.parse(r)}}}class ZU{constructor(){g(this,"converters",[]);g(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new JU)}prepareData(t){const e=new DataTransfer;for(let r=0;r<this.converterTypes.length;r++)e.setData(this.converterTypes[r],t.getData(this.converterTypes[r]));return e}async fromData(t,e,r){let i={};const o=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,o,r);l&&(i={...i,...l})}return i}addConverter(t){this.converters.push(t)}}function tO(n){n.editorBlocks.registerBlockClass(Un),n.editorBlocks.registerBlockClass(n3),n.editorBoxes.registerBoxClass(BB),n.editorBoxes.registerBoxClass(TB),n.editorBoxes.registerBoxClass(RB),n.editorBoxes.registerBoxClass(wB),n.editorInsertions.registerInsertionClass(SB),n.editorBlockRenders.registerRender(new bv)}function eO(n,t){tO(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 Mh=I("range-commands");function mT(n,t){n.forEach(e=>{e.source=t,e.children&&mT(e.children,t)})}function gT(n,t,e){const r=st(t);p(Mh,r===e.start.blockId,"invalid start range"),p(Mh,r===e.end.blockId,"invalid end range");const i=n.editorCommandProviders.getCommandProviders();let o=[];if(i.forEach(s=>{const l=s.getAvailableCommands(n,t,e);mT(l,s.id),o.push(...l)}),i.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,o);l&&(o=l)}}),_t(n,t)){if(!ha(e.start))return o;p(Mh,!e.start.isSimple(),"invalid start pos"),p(Mh,!e.end.isSimple(),"invalid end pos");const s=e.start.childContainerId,l=ai(n,s),d=ce(l)[0];if(d){const h=dt(n,d),C=Xe(n,{anchor:lt(d,0,"home"),focus:lt(d,h,"end")}),E=gT(n,d,C);o.push(...E)}}return o}function pT(n){const t=n.getEditor(),e=n.getSelectedBlocks(),r=[],i=n.isReverse()?e[0]:e[e.length-1],o=Xe(t,{anchor:i.start,focus:i.end});return gT(t,i.block,o).forEach(l=>{r.push(l)}),r}function CT(n,t,e,r,i,o){var h;const s=n.editorCommandProviders.getCommandProviders();for(let C=0;C<s.length;C++){const E=s[C];if(E.beforeExecuteCommand&&E.beforeExecuteCommand(n,t,e,r,i))return!1}const l=n.editorCommandProviders.getCommandProvider(r.source),c={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,r,i,{}))return o[st(t)]=c,!0;let d=!1;return _t(n,t)&&ma(n,t,e.start,e.end).forEach(E=>{ce(E).forEach(v=>{const R=dt(n,v),L=Xe(n,{anchor:lt(v,0,"home"),focus:lt(v,R,"end")});CT(n,v,L,r,i,o)&&(d=!0)})}),s.forEach(C=>{C.afterExecuteCommand&&C.afterExecuteCommand(n,t,e,r,i,o)}),d}function ET(n,t,e){const r=n.getEditor(),i={},o=r.editorCommandProviders.getCommandProvider(t.source);return o.executeRangeCommand&&o.executeRangeCommand(r,n,t,e,i)||(n.getSelectedBlocks().forEach(l=>{const c=Xe(r,{anchor:l.start,focus:l.end});CT(r,l.block,c,t,e,i)}),r.focus()),i}const nO=I("command-providers");class AT{constructor(t){g(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(r=>r.id===t);return p(nO,e,`no command provider, id=${t}`),e}getCommands(t){return pT(t)}executeCommand(t,e,r){return this.editor.undoManager.runInGroup(()=>ET(t,e,r))}getEmptyBlockTextAttributes(t,e){let r={};if(this.providers.forEach(i=>{var s;const o=(s=i.getEmptyBlockTextAttributes)==null?void 0:s.call(i,t,e);o&&(r={...r,...o})}),Object.keys(r).length!==0)return r}}function rO(n,t){const e=rt(t),r=ft(e),i=bt(t);lT(n,r,i)}const iO=I("table-scroll");class xT{constructor(t,e,r,i,o){g(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=r,this.handler=i,this.data=o,e.addEventListener(r,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class oO{constructor(t){g(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(r=>r.destroy()),this.handlers.delete(t)})}addEventListener(t,e,r,i){const o=this.handlers.get(t);if(o){if(o.find(s=>s.handler===r&&s.name===e)){iO.warn(`event has already registered: ${e}`);return}o.push(new xT(this.editor,t,e,r,i))}else{const s=new xT(this.editor,t,e,r,i);this.handlers.set(t,[s])}}removeEventListener(t,e,r){if(!t){for(const[o,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&r===c.handler&&s.splice(l,1);else if(r===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(o);continue}}return}const i=this.handlers.get(t);if(i){const o=i.findIndex(s=>s.handler===r&&s.name===e);if(o!==-1){const s=i[o];i.splice(o,1),s.destroy(),i.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const r=this.handlers.get(t);if(r)if(e)for(let i=0;i<r.length;i++){const o=r[i];o.name===e&&(r.splice(i,1),o.destroy())}else r.forEach(i=>{i.destroy()}),this.handlers.delete(t)}}const bT=I("update-block-text");function sO(n,t){const e=n.getBoxById(t.id),r=et(e);p(bT,r,"no parent block"),p(bT,nt(n,r),"not a text block");const i=n.getBlockText(r),o=mB(i,"id",t.id,t);QB(n,r,o)}function lO(n,t){for(const e of n.blockHooks)if(e.writable){const r=e.writable(n,t);if(typeof r=="boolean")return r}return!0}function aO(n){if(n.readonly)return!1;const t=di(n);return!!n.isBlockWritable(t.map(e=>e.block))}class cO{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 uO{constructor(){g(this,"shortcuts",[])}handleKeyboardEvents(t,e){const r=this.shortcuts;for(const i of r){const o=Object.entries(i);for(const[s,l]of o)if(si(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const ro=I("editor");class fO extends Be.TypedEmitter{constructor(e,r,i){var o,s,l,c,d,h,C,E;super();g(this,"parent");g(this,"rootElement");g(this,"contentElement");g(this,"rootContainerObject");g(this,"rootContainer");g(this,"input");g(this,"selection");g(this,"selectionHandler");g(this,"doc");g(this,"id");g(this,"clientId");g(this,"compositingText","");g(this,"undoManager");g(this,"shortcuts",new uO);g(this,"dataConverter",new ZU);g(this,"editorBlocks",new Jv(this));g(this,"editorBoxes",new kB(this));g(this,"editorInsertions",new IB(this));g(this,"editorEmbeds",new t3(this));g(this,"editorDecorators",new DB(this));g(this,"editorCommandProviders",new AT(this));g(this,"editorBlockRenders",new mI(this));g(this,"blockHooks",[]);g(this,"domEvents",new oO(this));g(this,"customs",new Map);g(this,"options");g(this,"inputHandlers",new NU(this));g(this,"settingsProvider");g(this,"_readonly",!1);g(this,"getColor",e=>{const r=this.options.colors;return r.length===0?"#FF1A75":r[e%r.length]});ro.debug("create editor"),this.setMaxListeners(100),this.options={colors:(o=i==null?void 0:i.colors)!=null?o:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"],componentsOptions:(l=(s=i==null?void 0:i.components)==null?void 0:s.options)!=null?l:{},scrollContainer:i==null?void 0:i.scrollContainer,enableComments:(c=i==null?void 0:i.enableComments)!=null?c:!0},this.settingsProvider=(d=i==null?void 0:i.settingsProvider)!=null?d:new cO(this),eO(this,i==null?void 0:i.components),this.blockHooks.push(...(C=(h=i==null?void 0:i.components)==null?void 0:h.blockHooks)!=null?C:[]),this.id=(E=i==null?void 0:i.id)!=null?E:Z(),this.clientId=Z(),this.undoManager=new QU(this),this.doc=new zU(this,r,this.undoManager),this.parent=e,this.rootElement=B("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=B("div",["editor-content"],this.rootElement),this.rootContainerObject=Xv(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new yM(this,this.inputHandlers),this.selection=new gU(this),this.selectionHandler=new EU(this),i!=null&&i.shortcuts&&this.shortcuts.shortcuts.push(...i.shortcuts),me.isMobile&&z(this.rootElement,"mobile"),me.isSafari&&z(this.rootElement,"safari"),this._readonly&&z(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?z(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:An(this.rootContainer)}addCustom(e,r){const i=this.customs.get(e);if(i)return i;const o=r(this);return this.customs.set(e,o),o}getCustom(e){const r=this.customs.get(e);return p(ro,r,`${e} does not exists`),r}replaceCustom(e,r){const i=this.customs.get(e);return i&&i.destroy(),this.customs.set(e,r),r}findCustom(e){return this.customs.get(e)}findCustomByType(e){const r=this.customs.values();for(const i of r)if(i instanceof e)return i;return null}destroyCustom(e){const r=this.customs.get(e);r&&(this.customs.delete(e),r.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,r,i){return this.editorBlocks.createBlock(e,r,i)}createBox(e,r){return this.editorBoxes.createBox(e,r)}createInsertion(e,r){return this.editorInsertions.createInsertion(e,r)}destroy(){ro.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()}focusToBlock(e,r){ep(this,e,r)}isWritable(){return aO(this)}isBlockWritable(e){return lO(this,e)}getChildContainerData(e){const r=this.doc.getContainerBlocks(e);return(!r||!Array.isArray(r))&&(p(ro,r,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),p(ro,Array.isArray(r),`container data is not an array: ${JSON.stringify(r)}`)),r}createChildContainer(e,r,i){return Yv(this,e,r,i)}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 r=this.rootContainer.querySelector(`#${e}`);return r&&p(ro,Fs(r),"not an valid block element"),r!=null?r:null}findBoxById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(ro,jd(r),"not an valid box element"),r!=null?r:null}getBlockById(e){const r=this.findBlockById(e);return p(ro,r,`no block, id=${e}`),r}getBoxById(e){const r=this.findBoxById(e);return p(ro,r,`no box, id=${e}`),r}getBlockByIndex(e,r){const i=this.getContainerById(e);return ji(i,r)}findBlockByIndex(e,r){const i=this.getContainerById(e);return pv(i,r)}getBlockIndex(e){if(typeof e=="string"){const r=this.getBlockById(e);return bt(r)}return bt(e)}getContainerById(e){return ai(this,e)}getParentContainer(e){return rt(e)}reloadBlock(e){rO(this,e)}contains(e){const r=e instanceof Element?e:e.parentElement;return r?r.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,r,i,o,s){const l={blockId:i.id,offset:0},c={anchor:l,focus:l};return Ta(this,e,r,i,o!=null?o:c,s)}insertEmbed(e,r,i,o,s){const l={id:Z(),type:"embed",embedType:i,embedData:o};return this.insertBlock(e,r,l,s)}deleteBlock(e,r){Z1(this,e,r)}mergeTextBlock(e,r){return qB(this,e,r)}breakTextBlock(e,r,i){return ya(this,e,r,i).newBlock}getTextPosition(){return va(this)}getBlockString(e,r){const i=this.getBlockText(e);return fe(i,r)}getBlockData(e){return zo(this,e)}getBoxData(e){return bB(this,e)}getBlockText(e){return vn(this,e)}setBlockText(e,r){QB(this,e,r)}deleteTextFromBlock(e,r,i,o){return Q1(this,e,r,i,o)}insertTextToBlock(e,r,i,o){return $B(this,e,r,i,o)}insertBoxToBlock(e,r,i){return HB(this,e,r,i)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,r,i,o){t5(this,e,r,i,o)}insertDocAt(e,r,i,o){return ip(this,e,r,i,o)}deleteChildContainers(e){WB(this,e)}replaceBlockText(e,r){return Th(this,e,r)}updateBlockData(e,r,i){const o={...this.getBlockData(e),...r},{id:s,type:l,...c}=o;return yh(this,e,c,(i!=null?i:this.selection.range).toDocRange())}updateEmbedData(e,r,i){return JB(this,e,r,i)}updateBoxData(e){sO(this,e)}getSelectedText(){const e=Ra(this);return no(this,e)}clearSelectedContents(){Bh(this)}insertTextBlock(e,r,i,o){const s=gi(e!=null?e:"");return GB(this,s,r,i,o==null?void 0:o.newRange,o==null?void 0:o.insertBlockOptions)}updateCompositionText(e,r){if(e&&!r&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!r){Y1(this);return}r?(this.compositingText="",qc()?e||Y1(this):X1(this,e)):(this.compositingText=e,jB(this))}}function vu(n,t,e){return new fO(n,t,e)}function dO(n){const t=(r,i)=>{const o=r.findIndex(l=>l.id===i.id);if(o===-1){r.push(i);return}const s=r[o];if(s.value!==i.value){r.splice(o,1);return}if(!!s.states){if(!i.states){s.states=[];return}s.states=bg.default(s.states,i.states)}},e=[];return n.forEach(r=>{r.forEach(i=>{t(e,i)})}),e}const hO=["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"];class Bu extends Be.TypedEmitter{constructor(e){super();g(this,"users",new Map);g(this,"cursors",new Map);g(this,"addingUser",!1);g(this,"colors");this.colors=e&&e.length>0?e:hO}setCursor(e){this.addUser(e.user);const r=this.cursors.get(e.user.userId);if(r&&jc.default(r,e))return;this.cursors.set(e.user.userId,e);const i=new Set([e.range.anchor.blockId,e.range.focus.blockId]),o=new Set(i);r&&new Set([r.range.anchor.blockId,r.range.focus.blockId]).forEach(l=>{i.has(l)||o.add(l)}),this.emit("remote-carets-change",[...o])}addUsers(e){this.addingUser=!0,e.forEach(r=>this.addUser(r)),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 r;return(r=this.users.get(e))!=null?r:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const r=this.cursors.get(e);if(r){const i=new Set(new Set([r==null?void 0:r.range.anchor.blockId,r==null?void 0:r.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...i])}}updateUsers(e){this.users.forEach(r=>{e.find(i=>i.userId===r.userId)||this.removeUser(r.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(r=>{this.addUser(r)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const r=new Map;return Array.from(this.cursors.values()).filter(i=>i.range.anchor.blockId===e&&fh(i.range)).forEach(i=>{const o=i.range.focus.offset;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}),r}getCursors(e){return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e||r.range.focus.blockId===e)}onUpdateBlockText(e,r,i){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(fh(l.range)){const{anchor:c,focus:d}=l.range;c.blockId===e.id&&(c.offset=fn.transformCursor(c.offset,r,i)),d.blockId===e.id&&(d.offset=fn.transformCursor(d.offset,r,i))}})}getFixedUserColor(e,r){let i=0;Array.from(e).forEach(s=>{i+=s.charCodeAt(0)});const o=i%this.colors.length;return this.colors[o]}destroy(){this.removeAllListeners()}}const rn=I("local-doc");class bp extends oa{constructor(e,r){super();g(this,"doc");g(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[gi("")]}},this.serviceUrl=(r==null?void 0:r.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return gt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}findContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,r){const i=this.getContainerBlocks(e);p(rn,i,`no container data: ${e}`);const o=i[r];return p(rn,o,`no block data: ${r}`),o}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(rn,o.text,"no text for data");const s=fn.apply(o.text,i);return o.text=s,p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,r,i,!0)}),s}localUpdateBlockData(e,r,i){const o=this.getBlockData(e,r);return i.delete.forEach(s=>delete o[s]),Object.entries(i.insert).forEach(([s,l])=>{o[s]=l}),p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,!0)}),o}localInsertBlock(e,r,i){const o=this.getContainerBlocks(e);return p(rn,o,`no container data: ${e}`),p(rn,r>=0&&r<=o.length,`invalid block index: ${r}, ${o.length}`),o.splice(r,0,i),p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,r,i,!0)}),i}localDeleteBlock(e,r){const i=this.getContainerBlocks(e);p(rn,i,`no container data: ${e}`),p(rn,r>=0&&r<=i.length,`invalid block index: ${r}, ${i.length}`);const o=i[r];return i.splice(r,1),p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,!0)}),o}localInsertChildContainers(e){e.forEach(({containerId:r,blocks:i})=>{this.doc.blocks[r]=i,p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,r,i,!0)})})}localDeleteChildContainers(e){rn.debug(`delete child containers: ${e}`),e.forEach(r=>{p(rn,this.doc.blocks[r],`no child container: ${r}`),delete this.doc.blocks[r]}),e.forEach(r=>{p(rn,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,r,!0)})})}uploadResource(e,r){p(rn,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,r){p(rn,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Bu}setDoc(e){this.doc=gt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,"change doc")})}destroy(){this.clearCallbacks()}}class mO{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function vp(n,t,e){n.addCustom(t,()=>{var o;const r=(o=e())!=null?o:void 0;return new mO(r)})}const vT=I("find-block");function BT(n,t){const e=$s(t);if(!e){if(fr(t))return null;const r=Ks(t);return p(vT,r,"no parent block"),BT(n,r)}return _t(n,e)?ga(n,e,{visibleOnly:!0}):e}function TT(n,t){const e=Hs(t);if(!e){if(fr(t))return null;const r=Ks(t);return p(vT,r,"no parent block"),TT(n,r)}return _t(n,e)?s1(n,e,{visibleOnly:!0}):e}const gO=I("remote-cursor");class pO{constructor(){g(this,"remoteUsers",new Bu)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const r=e;this.handleUpdateUsers(r.users)}else e.type==="caret"?this.handleUpdateCaret(e):gO.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 CO(n){const{blocks:t,meta:e,comments:r,...i}=n;return{rootBlocks:t,meta:e,comments:r,childBlocks:i}}function EO(n){const{blocks:t,meta:e,comments:r}=n,{root:i,...o}=t;return{blocks:i,meta:e,comments:r,...o}}function io(n){const{childBlocks:t,meta:e,comments:r,rootBlocks:i}=CO(gt.default(n));return{blocks:{root:i,...t},meta:e,comments:r}}function oo(n){return n==="root"?"blocks":n}function Da(n){return n==="blocks"?"root":n}const AO={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new cn.default(n)},apply(n,t){const e=new cn.default(n),r=new cn.default(t);return e.compose(r).ops},compose(n,t){const e=new cn.default(n),r=new cn.default(t);return e.compose(r).ops},diff(n,t){const e=new cn.default(n),r=new cn.default(t);return e.diff(r).ops},transform(n,t,e){const r=new cn.default(n);return new cn.default(t).transform(r,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 r=new cn.default(t),i=this.transformCursor(n.index,r,e),o=this.transformCursor(n.index+n.length,r,e);return{...n,index:i,length:o-i}}}};var Xo={},Bp=Eb.default.EventEmitter;Xo.EventEmitter=Bp,Xo.mixin=xO;function xO(n){for(var t in Bp.prototype)n.prototype[t]=Bp.prototype[t]}var yT=["info","warn","error"];function kT(){var n={};yT.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var bO=kT;kT.prototype.setMethods=function(n){n=n||{};var t=this;yT.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var vO=bO,BO=new vO,RT=BO;function el(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,el):this.stack=new Error().stack}el.prototype=Object.create(Error.prototype),el.prototype.constructor=el,el.prototype.name="ShareDBError",el.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 Uh=el,Tu={},wT=TO;function TO(n,t,e,r){var i=function(s,l,c,d){t(c,s,l,"left"),t(d,l,s,"right")},o=n.transformX=function(s,l){e(s),e(l);for(var c=[],d=0;d<l.length;d++){for(var h=l[d],C=[],E=0;E<s.length;){var x=[];if(i(s[E],h,C,x),E++,x.length===1)h=x[0];else if(x.length===0){for(var v=E;v<s.length;v++)r(C,s[v]);h=null;break}else{for(var R=o(s.slice(E),x),L=0;L<R[0].length;L++)r(C,R[0][L]);for(var M=0;M<R[1].length;M++)r(c,R[1][M]);h=null;break}}h!=null&&r(c,h),s=C}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?o(s,l)[0]:o(l,s)[1]}}var ST={exports:{}},Yo=ST.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||""}},Tp=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},yp=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")},Oh=function(n){for(var t=0;t<n.length;t++)yp(n[t])};Yo.apply=function(n,t){var e;Oh(t);for(var r=0;r<t.length;r++){var i=t[r];if(i.i!=null)n=Tp(n,i.p,i.i);else{if(e=n.slice(i.p,i.p+i.d.length),i.d!==e)throw new Error("Delete component '"+i.d+"' does not match deleted text '"+e+"'");n=n.slice(0,i.p)+n.slice(i.p+i.d.length)}}return n};var so=Yo._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:Tp(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:Tp(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Yo.compose=function(n,t){Oh(n),Oh(t);for(var e=n.slice(),r=0;r<t.length;r++)so(e,t[r]);return e},Yo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=0),so(t,r)}return t};var kp=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};Yo.transformCursor=function(n,t,e){for(var r=e==="right",i=0;i<t.length;i++)n=kp(n,t[i],r);return n};var yO=Yo._tc=function(n,t,e,r){if(yp(t),yp(e),t.i!=null)so(n,{i:t.i,p:kp(t.p,e,r==="right")});else if(e.i!=null){var i=t.d;t.p<e.p&&(so(n,{d:i.slice(0,e.p-t.p),p:t.p}),i=i.slice(e.p-t.p)),i!==""&&so(n,{d:i,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)so(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)so(n,t);else{var o={d:"",p:t.p};t.p<e.p&&(o.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(o.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),c=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(c!==d)throw new Error("Delete ops delete different text in the same region of the document");o.d!==""&&(o.p=kp(o.p,e),so(n,o))}return n},kO=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Yo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=kO(n[t]);return n},wT(Yo,yO,Oh,so);var Nh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},RO=function(n){return!!n&&n.constructor===Object},Pr=function(n){return JSON.parse(JSON.stringify(n))},Lt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},lo={};Lt.registerSubtype=function(n){lo[n.name]=n},Lt.create=function(n){return n===void 0?null:Pr(n)},Lt.invertComponent=function(n){var t={p:n.p};return n.t&&lo[n.t]&&(t.t=n.t,t.o=lo[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},Lt.invert=function(n){for(var t=n.slice().reverse(),e=[],r=0;r<t.length;r++)e.push(Lt.invertComponent(t[r]));return e},Lt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Nh(n[t].p))throw new Error("Missing path")},Lt.checkList=function(n){if(!Nh(n))throw new Error("Referenced element not a list")},Lt.checkObj=function(n){if(!RO(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function yu(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 ku(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}Lt.apply=function(n,t){Lt.checkValidOp(t),t=Pr(t);for(var e={data:n},r=0;r<t.length;r++){var i=t[r];(i.si!=null||i.sd!=null)&&yu(i);for(var o=null,s=e,l="data",c=0;c<i.p.length;c++){var d=i.p[c];if(o=s,s=s[l],l=d,o==null)throw new Error("Path invalid")}if(i.t&&i.o!==void 0&&lo[i.t])s[l]=lo[i.t].apply(s[l],i.o);else if(i.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=i.na}else if(i.li!==void 0&&i.ld!==void 0)Lt.checkList(s),s[l]=i.li;else if(i.li!==void 0)Lt.checkList(s),s.splice(l,0,i.li);else if(i.ld!==void 0)Lt.checkList(s),s.splice(l,1);else if(i.lm!==void 0){if(Lt.checkList(s),i.lm!=l){var h=s[l];s.splice(l,1),s.splice(i.lm,0,h)}}else if(i.oi!==void 0)Lt.checkObj(s),s[l]=i.oi;else if(i.od!==void 0)Lt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},Lt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},Lt.incrementalApply=function(n,t,e){for(var r=0;r<t.length;r++){var i=[t[r]];n=Lt.apply(n,i),e(i,n)}return n};var wO=Lt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var r=0;r<n.length;r++)if(n[r]!==t[r]&&(!e||r!==n.length-1))return!1;return!0};Lt.append=function(n,t){if(t=Pr(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)&&(yu(t),yu(e)),wO(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&lo[t.t]){if(e.o=lo[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var r=t.p,i=0;i<e.o.length-1;i++)t.o=[e.o.pop()],t.p=r.slice(),ku(t),n.push(t);ku(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)&&(ku(t),ku(e)),n.push(t)},Lt.compose=function(n,t){Lt.checkValidOp(n),Lt.checkValidOp(t);for(var e=Pr(n),r=0;r<t.length;r++)Lt.append(e,t[r]);return e},Lt.normalize=function(n){var t=[];n=Nh(n)?n:[n];for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=[]),Lt.append(t,r)}return t},Lt.commonLengthForOps=function(n,t){var e=n.p.length,r=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&r++,e===0)return-1;if(r===0)return null;e--,r--;for(var i=0;i<e;i++){var o=n.p[i];if(i>=r||o!==t.p[i])return null}return e},Lt.canOpAffectPath=function(n,t){return Lt.commonLengthForOps({p:t},n)!=null},Lt.transformComponent=function(n,t,e,r){t=Pr(t);var i=Lt.commonLengthForOps(e,t),o=Lt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,o!=null&&l>s&&t.p[o]==e.p[o]){if(t.ld!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.ld=Lt.apply(Pr(t.ld),[c])}else if(t.od!==void 0){var c=Pr(e);c.p=c.p.slice(s),t.od=Lt.apply(Pr(t.od),[c])}}if(i!=null){var d=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(yu(t),c=Pr(e),yu(c)),c.t&&lo[c.t]){if(t.t&&t.t===c.t){var h=lo[t.t].transform(t.o,c.o,r);if(t.si!=null||t.sd!=null)for(var C=t.p,E=0;E<h.length;E++)t.o=[h[E]],t.p=C.slice(),ku(t),Lt.append(n,t);else(!Nh(h)||h.length>0)&&(t.o=h,Lt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[i]===t.p[i])if(d){if(t.ld!==void 0)if(t.li!==void 0&&r==="left")t.ld=Pr(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[i]===e.p[i]?r==="right"&&t.p[i]++:e.p[i]<=t.p[i]&&t.p[i]++,t.lm!==void 0&&d&&e.p[i]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[i]===t.p[i])return n;var C=e.p[i],x=t.p[i],v=t.lm;(C<v||C===v&&x<v)&&t.lm--}if(e.p[i]<t.p[i])t.p[i]--;else if(e.p[i]===t.p[i]){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 x=t.p[i],v=t.lm,R=e.p[i],L=e.lm;if(R!==L)if(x===R)if(r==="left")t.p[i]=L,x===v&&(t.lm=L);else return n;else x>R&&t.p[i]--,x>L?t.p[i]++:x===L&&R>L&&(t.p[i]++,x===v&&t.lm++),(v>R||v===R&&v>x)&&t.lm--,v>L?t.lm++:v===L&&(L>R&&v>x||L<R&&v<x?r==="right"&&t.lm++:v>x?t.lm++:v===R&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var x=e.p[i],v=e.lm;C=t.p[i],C>x&&t.p[i]--,C>v&&t.p[i]++}else{var x=e.p[i],v=e.lm;C=t.p[i],C===x?t.p[i]=v:(C>x&&t.p[i]--,(C>v||C===v&&x>v)&&t.p[i]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[i]===e.p[i])if(t.oi!==void 0&&d){if(r==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[i]===e.p[i])if(r==="left")Lt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[i]==e.p[i]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return Lt.append(n,t),n},wT(Lt,Lt.transformComponent,Lt.checkValidOp,Lt.append);var SO=ST.exports;Lt.registerSubtype(SO);var LO=Lt,IO={type:LO};(function(n){n.defaultType=IO.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)})(Tu);var Fr={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var r 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],r=1;r<arguments.length;r++){var i=arguments[r];e=e[i]||(r===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],r=arguments[arguments.length-1],i=1;i<arguments.length-1;i++){var o=arguments[i];e=e[o]||(e[o]=i===arguments.length-2?r():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],r=[e],i=1;i<arguments.length-1;i++){var o=arguments[i];if(!e.hasOwnProperty(o))break;e=e[o],r.push(e)}for(var i=r.length-1;i>=0;i--){var s=r[i],o=arguments[i+1],l=s[o];(i===r.length-1||!n.hasKeys(l))&&delete s[o]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,r){var i=!1;return e.forEach(function(o){o&&(o(r),i=!0)}),i},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];setTimeout(function(){e.apply(null,r)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(Fr);var LT=Array.isArray,IT=Object.keys,DO=Object.prototype.hasOwnProperty,_O=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=LT(t),i=LT(e),o,s,l;if(r&&i){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!n(t[o],e[o]))return!1;return!0}if(r!=i)return!1;var c=t instanceof Date,d=e instanceof Date;if(c!=d)return!1;if(c&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,C=e instanceof RegExp;if(h!=C)return!1;if(h&&C)return t.toString()==e.toString();var E=IT(t);if(s=E.length,s!==IT(e).length)return!1;for(o=s;o--!==0;)if(!DO.call(e,E[o]))return!1;for(o=s;o--!==0;)if(l=E[o],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},DT=Xo,MO=RT,Jn=Uh,Ph=Tu,Kr=Fr,UO=Kr.clone,OO=_O,On=Jn.CODES,NO=Ft;function Ft(n,t,e){DT.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}DT.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=Ph.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Jn(On.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 Jn(On.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 Jn(On.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 r=n.type===void 0?Ph.defaultType:n.type;this._setType(r),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;Kr.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===On.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 r=this.inflightFetch.shift();if(r&&e.push(r),e.length&&(r=function(i){Kr.callEach(e,i)}),n)return this._emitResponseError(n,r);this.ingestSnapshot(t,r),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var r=this.pendingFetch;this.pendingFetch=[],e.callback&&r.push(e.callback);var i;if(r.length&&(i=function(o){Kr.callEach(r,o)}),n)return this._emitResponseError(n,i);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,i):i&&i(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===On.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=Fh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var r=0;r<this.pendingOps.length;r++){var e=Fh(this.pendingOps[r],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}}},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);PO(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,r=e&&e.wantSubscribe===n;if(r){e.callback=FO([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;Kr.nextTick(function(){n._handleSubscribe()})}}};function PO(n,t,e){if(t){var r=n.pop();n.push(function(i){r&&r(i),e&&e(i)})}else n.push(e)}function FO(n){return n=n.filter(Kr.truthy),n.length?function(t){Kr.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function KO(n){delete n.op,delete n.create,delete n.del}function Fh(n,t){if(n.del)return KO(t);if(t.del)return new Jn(On.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Jn(On.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Jn(On.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 r=n.type.transform(n.op,t.op,"left"),i=n.type.transform(t.op,n.op,"right");n.op=r,t.op=i}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Jn(On.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===Ph.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,r=0;r<n.op.length;r++){var i=n.op[r],o={op:[i]};this.emit("before op",o.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Fh(this.applyStack[s],o);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,o.op)),this.emit("op",o.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 c=this.data;this._setType(null),this.emit("del",c,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 Jn(On.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>=Kr.MAX_SAFE_INTEGER)return this.emit("error",new Jn(On.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 r=new Jn(On.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(r):this.emit("error",r)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(o){return this._hardRollback(o)}var i=this;Kr.nextTick(function(){i.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var r=this._tryCompose(n);if(r){r.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 r=this.pendingOps.splice(e),e=0;e<r.length;e++){var t=r[e],i=this._tryCompose(t);i?i.callbacks=i.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&&!OO(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 r={op:n},i=t&&t.source;this._submit(r,i,e)},Ft.prototype.create=function(n,t,e,r){if(typeof t=="function"?(r=t,e=null,t=null):typeof e=="function"&&(r=e,e=null),t||(t=Ph.defaultType.uri),this.type){var i=new Jn(On.ERR_DOC_ALREADY_CREATED,"Document already exists");return r?r(i):this.emit("error",i)}var o={create:{type:t,data:n}},s=e&&e.source;this._submit(o,s,r)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Jn(On.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var r={del:!0},i=n&&n.source;this._submit(r,i,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:UO(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 MO.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 r=Fh(this.pendingOps[e],t);if(r)return this._hardRollback(r)}try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}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 r=!!t.length,i=0;i<t.length;i++)r=Kr.callEach(t[i].callbacks,n)&&r;if(n&&!r)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Kr.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var nl={};nl.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 _T=Xo,MT=nl.ACTIONS,VO=Fr,$O=Nn;function Nn(n,t,e,r,i,o,s){_T.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=r,this.query=i,this.results=null,o&&o.results&&(this.results=o.results,delete o.results),this.extra=void 0,this.options=o,this.callback=s,this.ready=!1,this.sent=!1}_T.mixin(Nn),Nn.prototype.hasPending=function(){return!this.ready},Nn.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 r=this.results[e];t.push([r.id,r.version])}n.r=t}this.connection.send(n),this.sent=!0}},Nn.prototype.destroy=function(n){this.connection.canSend&&this.action===MT.querySubscribe&&this.connection.send({a:MT.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&VO.nextTick(n)},Nn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Nn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Nn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Nn.prototype._handleResponse=function(n,t,e){var r=this.callback;if(this.callback=null,n)return this._finishResponse(n,r);if(!t)return this._finishResponse(null,r);var i=this,o=1,s=function(h){if(h)return i._finishResponse(h,r);--o||i._finishResponse(null,r)};if(Array.isArray(t))o+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){o++;var c=t[l],d=this.connection.get(c.c||this.collection,l);d.ingestSnapshot(c,s)}s()},Nn.prototype._ingestSnapshots=function(n,t){for(var e=[],r=0;r<n.length;r++){var i=n[r],o=this.connection.get(i.c||this.collection,i.d);o.ingestSnapshot(i,t),e.push(o)}return e},Nn.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)},Nn.prototype._handleError=function(n){this.emit("error",n)},Nn.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 r=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(r)),this.emit("insert",r,e.index);break;case"remove":var o=e.howMany||1,i=this.results.splice(e.index,o);this.emit("remove",i,e.index);break;case"move":var o=e.howMany||1,s=this.results.splice(e.from,o);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)},Nn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var UT=Xo,HO=nl.ACTIONS,jO=Fr,OT=Ci;function Ci(n,t){if(UT.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={}}UT.mixin(Ci),Ci.prototype.submit=function(n,t){this.value=n,this.send(t)},Ci.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},Ci.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()})},Ci.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},Ci.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},Ci.prototype._message=function(){return{a:HO.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},Ci.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},Ci.prototype._callbackOrEmit=function(n,t){if(t)return jO.nextTick(t,n);n&&this.emit("error",n)};var zO=Fr,NT=Rp;function Rp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Rp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Rp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&zO.nextTick(n)};var wp={exports:{}};(function(n,t){(function(e,r){r(t)})(_n,function(e){function r(y,S){S=S|0;for(var _=Math.max(y.length-S,0),N=Array(_),H=0;H<_;H++)N[H]=y[S+H];return N}var i=function(y){var S=r(arguments,1);return function(){var _=r(arguments);return y.apply(null,S.concat(_))}},o=function(y){return function(){var S=r(arguments),_=S.pop();y.call(this,S,_)}};function s(y){var S=typeof y;return y!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function d(y){setTimeout(y,0)}function h(y){return function(S){var _=r(arguments,1);y(function(){S.apply(null,_)})}}var C;l?C=setImmediate:c?C=process.nextTick:C=d;var E=h(C);function x(y){return o(function(S,_){var N;try{N=y.apply(this,S)}catch(H){return _(H)}s(N)&&typeof N.then=="function"?N.then(function(H){v(_,null,H)},function(H){v(_,H.message?H:new Error(H))}):_(null,N)})}function v(y,S,_){try{y(S,_)}catch(N){E(R,N)}}function R(y){throw y}var L=typeof Symbol=="function";function M(y){return L&&y[Symbol.toStringTag]==="AsyncFunction"}function U(y){return M(y)?x(y):y}function F(y){return function(S){var _=r(arguments,1),N=o(function(H,$){var X=this;return y(S,function(J,ct){U(J).apply(X,H.concat(ct))},$)});return _.length?N.apply(this,_):N}}var G=typeof _n=="object"&&_n&&_n.Object===Object&&_n,W=typeof self=="object"&&self&&self.Object===Object&&self,it=G||W||Function("return this")(),at=it.Symbol,At=Object.prototype,Mt=At.hasOwnProperty,Bt=At.toString,se=at?at.toStringTag:void 0;function te(y){var S=Mt.call(y,se),_=y[se];try{y[se]=void 0;var N=!0}catch{}var H=Bt.call(y);return N&&(S?y[se]=_:delete y[se]),H}var yn=Object.prototype,be=yn.toString;function Fn(y){return be.call(y)}var Li="[object Null]",kn="[object Undefined]",gn=at?at.toStringTag:void 0;function Ii(y){return y==null?y===void 0?kn:Li:gn&&gn in Object(y)?te(y):Fn(y)}var mo="[object AsyncFunction]",Ar="[object Function]",yA="[object GeneratorFunction]",kA="[object Proxy]";function RA(y){if(!s(y))return!1;var S=Ii(y);return S==Ar||S==yA||S==mo||S==kA}var ms=9007199254740991;function xl(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=ms}function bl(y){return y!=null&&xl(y.length)&&!RA(y)}var go={};function Ht(){}function Di(y){return function(){if(y!==null){var S=y;y=null,S.apply(this,arguments)}}}var gs=typeof Symbol=="function"&&Symbol.iterator,Cc=function(y){return gs&&y[gs]&&y[gs]()};function hm(y,S){for(var _=-1,N=Array(y);++_<y;)N[_]=S(_);return N}function pn(y){return y!=null&&typeof y=="object"}var vl="[object Arguments]";function mm(y){return pn(y)&&Ii(y)==vl}var xr=Object.prototype,gm=xr.hasOwnProperty,wA=xr.propertyIsEnumerable,Bl=mm(function(){return arguments}())?mm:function(y){return pn(y)&&gm.call(y,"callee")&&!wA.call(y,"callee")},ke=Array.isArray;function Tl(){return!1}var yl=typeof e=="object"&&e&&!e.nodeType&&e,pm=yl&&!0&&n&&!n.nodeType&&n,kl=pm&&pm.exports===yl,Cm=kl?it.Buffer:void 0,Rl=Cm?Cm.isBuffer:void 0,ps=Rl||Tl,wf=9007199254740991,Sf=/^(?:0|[1-9]\d*)$/;function Lf(y,S){var _=typeof y;return S=S==null?wf:S,!!S&&(_=="number"||_!="symbol"&&Sf.test(y))&&y>-1&&y%1==0&&y<S}var If="[object Arguments]",Df="[object Array]",_f="[object Boolean]",Mf="[object Date]",Uf="[object Error]",Of="[object Function]",SA="[object Map]",LA="[object Number]",IA="[object Object]",Em="[object RegExp]",Am="[object Set]",DA="[object String]",_A="[object WeakMap]",MA="[object ArrayBuffer]",UA="[object DataView]",xm="[object Float32Array]",OA="[object Float64Array]",NA="[object Int8Array]",PA="[object Int16Array]",Nf="[object Int32Array]",FA="[object Uint8Array]",Pf="[object Uint8ClampedArray]",KA="[object Uint16Array]",VA="[object Uint32Array]",de={};de[xm]=de[OA]=de[NA]=de[PA]=de[Nf]=de[FA]=de[Pf]=de[KA]=de[VA]=!0,de[If]=de[Df]=de[MA]=de[_f]=de[UA]=de[Mf]=de[Uf]=de[Of]=de[SA]=de[LA]=de[IA]=de[Em]=de[Am]=de[DA]=de[_A]=!1;function $A(y){return pn(y)&&xl(y.length)&&!!de[Ii(y)]}function HA(y){return function(S){return y(S)}}var bm=typeof e=="object"&&e&&!e.nodeType&&e,wl=bm&&!0&&n&&!n.nodeType&&n,jA=wl&&wl.exports===bm,Ec=jA&&G.process,vm=function(){try{var y=wl&&wl.require&&wl.require("util").types;return y||Ec&&Ec.binding&&Ec.binding("util")}catch{}}(),Bm=vm&&vm.isTypedArray,zA=Bm?HA(Bm):$A,GA=Object.prototype,WA=GA.hasOwnProperty;function qA(y,S){var _=ke(y),N=!_&&Bl(y),H=!_&&!N&&ps(y),$=!_&&!N&&!H&&zA(y),X=_||N||H||$,J=X?hm(y.length,String):[],ct=J.length;for(var Ct in y)(S||WA.call(y,Ct))&&!(X&&(Ct=="length"||H&&(Ct=="offset"||Ct=="parent")||$&&(Ct=="buffer"||Ct=="byteLength"||Ct=="byteOffset")||Lf(Ct,ct)))&&J.push(Ct);return J}var Ac=Object.prototype;function XA(y){var S=y&&y.constructor,_=typeof S=="function"&&S.prototype||Ac;return y===_}function xc(y,S){return function(_){return y(S(_))}}var YA=xc(Object.keys,Object),QA=Object.prototype,JA=QA.hasOwnProperty;function Tm(y){if(!XA(y))return YA(y);var S=[];for(var _ in Object(y))JA.call(y,_)&&_!="constructor"&&S.push(_);return S}function bc(y){return bl(y)?qA(y):Tm(y)}function ym(y){var S=-1,_=y.length;return function(){return++S<_?{value:y[S],key:S}:null}}function ZA(y){var S=-1;return function(){var N=y.next();return N.done?null:(S++,{value:N.value,key:S})}}function tx(y){var S=bc(y),_=-1,N=S.length;return function H(){var $=S[++_];return $==="__proto__"?H():_<N?{value:y[$],key:$}:null}}function ex(y){if(bl(y))return ym(y);var S=Cc(y);return S?ZA(S):tx(y)}function br(y){return function(){if(y===null)throw new Error("Callback was already called.");var S=y;y=null,S.apply(this,arguments)}}function Sl(y){return function(S,_,N){if(N=Di(N||Ht),y<=0||!S)return N(null);var H=ex(S),$=!1,X=0,J=!1;function ct(ut,xt){if(X-=1,ut)$=!0,N(ut);else{if(xt===go||$&&X<=0)return $=!0,N(null);J||Ct()}}function Ct(){for(J=!0;X<y&&!$;){var ut=H();if(ut===null){$=!0,X<=0&&N(null);return}X+=1,_(ut.value,ut.key,br(ct))}J=!1}Ct()}}function _i(y,S,_,N){Sl(S)(y,U(_),N)}function ze(y,S){return function(_,N,H){return y(_,S,N,H)}}function Ff(y,S,_){_=Di(_||Ht);var N=0,H=0,$=y.length;$===0&&_(null);function X(J,ct){J?_(J):(++H===$||ct===go)&&_(null)}for(;N<$;N++)S(y[N],N,br(X))}var nx=ze(_i,1/0),Yr=function(y,S,_){var N=bl(y)?Ff:nx;N(y,U(S),_)};function Qr(y){return function(S,_,N){return y(Yr,S,U(_),N)}}function Kf(y,S,_,N){N=N||Ht,S=S||[];var H=[],$=0,X=U(_);y(S,function(J,ct,Ct){var ut=$++;X(J,function(xt,Jt){H[ut]=Jt,Ct(xt)})},function(J){N(J,H)})}var vc=Qr(Kf),Vf=F(vc);function po(y){return function(S,_,N,H){return y(Sl(_),S,U(N),H)}}var Mi=po(Kf),$f=ze(Mi,1),Hf=F($f);function Cs(y,S){for(var _=-1,N=y==null?0:y.length;++_<N&&S(y[_],_,y)!==!1;);return y}function jf(y){return function(S,_,N){for(var H=-1,$=Object(S),X=N(S),J=X.length;J--;){var ct=X[y?J:++H];if(_($[ct],ct,$)===!1)break}return S}}var Es=jf();function As(y,S){return y&&Es(y,S,bc)}function km(y,S,_,N){for(var H=y.length,$=_+(N?1:-1);N?$--:++$<H;)if(S(y[$],$,y))return $;return-1}function rx(y){return y!==y}function Rm(y,S,_){for(var N=_-1,H=y.length;++N<H;)if(y[N]===S)return N;return-1}function Ll(y,S,_){return S===S?Rm(y,S,_):km(y,rx,_)}var Bc=function(y,S,_){typeof S=="function"&&(_=S,S=null),_=Di(_||Ht);var N=bc(y),H=N.length;if(!H)return _(null);S||(S=H);var $={},X=0,J=!1,ct=Object.create(null),Ct=[],ut=[],xt={};As(y,function(Ee,ae){if(!ke(Ee)){Jt(ae,[Ee]),ut.push(ae);return}var ve=Ee.slice(0,Ee.length-1),Br=ve.length;if(Br===0){Jt(ae,Ee),ut.push(ae);return}xt[ae]=Br,Cs(ve,function(k){if(!y[k])throw new Error("async.auto task `"+ae+"` has a non-existent dependency `"+k+"` in "+ve.join(", "));ln(k,function(){Br--,Br===0&&Jt(ae,Ee)})})}),yx(),Pe();function Jt(Ee,ae){Ct.push(function(){vr(Ee,ae)})}function Pe(){if(Ct.length===0&&X===0)return _(null,$);for(;Ct.length&&X<S;){var Ee=Ct.shift();Ee()}}function ln(Ee,ae){var ve=ct[Ee];ve||(ve=ct[Ee]=[]),ve.push(ae)}function $n(Ee){var ae=ct[Ee]||[];Cs(ae,function(ve){ve()}),Pe()}function vr(Ee,ae){if(!J){var ve=br(function(k,Ni){if(X--,arguments.length>2&&(Ni=r(arguments,1)),k){var Bs={};As($,function(Hn,Vt){Bs[Vt]=Hn}),Bs[Ee]=Ni,J=!0,ct=Object.create(null),_(k,Bs)}else $[Ee]=Ni,$n(Ee)});X++;var Br=U(ae[ae.length-1]);ae.length>1?Br($,ve):Br(ve)}}function yx(){for(var Ee,ae=0;ut.length;)Ee=ut.pop(),ae++,Cs(kx(Ee),function(ve){--xt[ve]===0&&ut.push(ve)});if(ae!==H)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function kx(Ee){var ae=[];return As(y,function(ve,Br){ke(ve)&&Ll(ve,Ee,0)>=0&&ae.push(Br)}),ae}};function Co(y,S){for(var _=-1,N=y==null?0:y.length,H=Array(N);++_<N;)H[_]=S(y[_],_,y);return H}var ix="[object Symbol]";function ox(y){return typeof y=="symbol"||pn(y)&&Ii(y)==ix}var sx=1/0,zf=at?at.prototype:void 0,wm=zf?zf.toString:void 0;function Gf(y){if(typeof y=="string")return y;if(ke(y))return Co(y,Gf)+"";if(ox(y))return wm?wm.call(y):"";var S=y+"";return S=="0"&&1/y==-sx?"-0":S}function lx(y,S,_){var N=-1,H=y.length;S<0&&(S=-S>H?0:H+S),_=_>H?H:_,_<0&&(_+=H),H=S>_?0:_-S>>>0,S>>>=0;for(var $=Array(H);++N<H;)$[N]=y[N+S];return $}function ax(y,S,_){var N=y.length;return _=_===void 0?N:_,!S&&_>=N?y:lx(y,S,_)}function Wf(y,S){for(var _=y.length;_--&&Ll(S,y[_],0)>-1;);return _}function cx(y,S){for(var _=-1,N=y.length;++_<N&&Ll(S,y[_],0)>-1;);return _}function ux(y){return y.split("")}var fx="\\ud800-\\udfff",dx="\\u0300-\\u036f",hx="\\ufe20-\\ufe2f",he="\\u20d0-\\u20ff",le=dx+hx+he,mx="\\ufe0e\\ufe0f",gx="\\u200d",px=RegExp("["+gx+fx+le+mx+"]");function Cx(y){return px.test(y)}var Sm="\\ud800-\\udfff",Ex="\\u0300-\\u036f",Lm="\\ufe20-\\ufe2f",Ax="\\u20d0-\\u20ff",Ze=Ex+Lm+Ax,qf="\\ufe0e\\ufe0f",Eo="["+Sm+"]",Tc="["+Ze+"]",Il="\\ud83c[\\udffb-\\udfff]",Kn="(?:"+Tc+"|"+Il+")",Xf="[^"+Sm+"]",Yf="(?:\\ud83c[\\udde6-\\uddff]){2}",Qf="[\\ud800-\\udbff][\\udc00-\\udfff]",Im="\\u200d",Jf=Kn+"?",Zf="["+qf+"]?",Rn="(?:"+Im+"(?:"+[Xf,Yf,Qf].join("|")+")"+Zf+Jf+")*",xx=Zf+Jf+Rn,Vn="(?:"+[Xf+Tc+"?",Tc,Yf,Qf,Eo].join("|")+")",bx=RegExp(Il+"(?="+Il+")|"+Vn+xx,"g");function Dm(y){return y.match(bx)||[]}function Jr(y){return Cx(y)?Dm(y):ux(y)}function yc(y){return y==null?"":Gf(y)}var td=/^\s+|\s+$/g;function Ce(y,S,_){if(y=yc(y),y&&(_||S===void 0))return y.replace(td,"");if(!y||!(S=Gf(S)))return y;var N=Jr(y),H=Jr(S),$=cx(N,H),X=Wf(N,H)+1;return ax(N,$,X).join("")}var Ui=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,ed=/,/,vx=/(=.+)?(\s*)$/,nd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Bx(y){return y=y.toString().replace(nd,""),y=y.match(Ui)[2].replace(" ",""),y=y?y.split(ed):[],y=y.map(function(S){return Ce(S.replace(vx,""))}),y}function _m(y,S){var _={};As(y,function(N,H){var $,X=M(N),J=!X&&N.length===1||X&&N.length===0;if(ke(N))$=N.slice(0,-1),N=N[N.length-1],_[H]=$.concat($.length>0?ct:N);else if(J)_[H]=N;else{if($=Bx(N),N.length===0&&!X&&$.length===0)throw new Error("autoInject task functions require explicit parameters.");X||$.pop(),_[H]=$.concat(ct)}function ct(Ct,ut){var xt=Co($,function(Jt){return Ct[Jt]});xt.push(ut),U(N).apply(null,xt)}}),Bc(_,S)}function rr(){this.head=this.tail=null,this.length=0}function rd(y,S){y.length=1,y.head=y.tail=S}rr.prototype.removeLink=function(y){return y.prev?y.prev.next=y.next:this.head=y.next,y.next?y.next.prev=y.prev:this.tail=y.prev,y.prev=y.next=null,this.length-=1,y},rr.prototype.empty=function(){for(;this.head;)this.shift();return this},rr.prototype.insertAfter=function(y,S){S.prev=y,S.next=y.next,y.next?y.next.prev=S:this.tail=S,y.next=S,this.length+=1},rr.prototype.insertBefore=function(y,S){S.prev=y.prev,S.next=y,y.prev?y.prev.next=S:this.head=S,y.prev=S,this.length+=1},rr.prototype.unshift=function(y){this.head?this.insertBefore(this.head,y):rd(this,y)},rr.prototype.push=function(y){this.tail?this.insertAfter(this.tail,y):rd(this,y)},rr.prototype.shift=function(){return this.head&&this.removeLink(this.head)},rr.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},rr.prototype.toArray=function(){for(var y=Array(this.length),S=this.head,_=0;_<this.length;_++)y[_]=S.data,S=S.next;return y},rr.prototype.remove=function(y){for(var S=this.head;S;){var _=S.next;y(S)&&this.removeLink(S),S=_}return this};function Dl(y,S,_){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var N=U(y),H=0,$=[],X=!1;function J(xt,Jt,Pe){if(Pe!=null&&typeof Pe!="function")throw new Error("task callback must be a function");if(ut.started=!0,ke(xt)||(xt=[xt]),xt.length===0&&ut.idle())return E(function(){ut.drain()});for(var ln=0,$n=xt.length;ln<$n;ln++){var vr={data:xt[ln],callback:Pe||Ht};Jt?ut._tasks.unshift(vr):ut._tasks.push(vr)}X||(X=!0,E(function(){X=!1,ut.process()}))}function ct(xt){return function(Jt){H-=1;for(var Pe=0,ln=xt.length;Pe<ln;Pe++){var $n=xt[Pe],vr=Ll($,$n,0);vr===0?$.shift():vr>0&&$.splice(vr,1),$n.callback.apply($n,arguments),Jt!=null&&ut.error(Jt,$n.data)}H<=ut.concurrency-ut.buffer&&ut.unsaturated(),ut.idle()&&ut.drain(),ut.process()}}var Ct=!1,ut={_tasks:new rr,concurrency:S,payload:_,saturated:Ht,unsaturated:Ht,buffer:S/4,empty:Ht,drain:Ht,error:Ht,started:!1,paused:!1,push:function(xt,Jt){J(xt,!1,Jt)},kill:function(){ut.drain=Ht,ut._tasks.empty()},unshift:function(xt,Jt){J(xt,!0,Jt)},remove:function(xt){ut._tasks.remove(xt)},process:function(){if(!Ct){for(Ct=!0;!ut.paused&&H<ut.concurrency&&ut._tasks.length;){var xt=[],Jt=[],Pe=ut._tasks.length;ut.payload&&(Pe=Math.min(Pe,ut.payload));for(var ln=0;ln<Pe;ln++){var $n=ut._tasks.shift();xt.push($n),$.push($n),Jt.push($n.data)}H+=1,ut._tasks.length===0&&ut.empty(),H===ut.concurrency&&ut.saturated();var vr=br(ct(xt));N(Jt,vr)}Ct=!1}},length:function(){return ut._tasks.length},running:function(){return H},workersList:function(){return $},idle:function(){return ut._tasks.length+H===0},pause:function(){ut.paused=!0},resume:function(){ut.paused!==!1&&(ut.paused=!1,E(ut.process))}};return ut}function Ao(y,S){return Dl(y,1,S)}var xs=ze(_i,1);function Zr(y,S,_,N){N=Di(N||Ht);var H=U(_);xs(y,function($,X,J){H(S,$,function(ct,Ct){S=Ct,J(ct)})},function($){N($,S)})}function kc(){var y=Co(arguments,U);return function(){var S=r(arguments),_=this,N=S[S.length-1];typeof N=="function"?S.pop():N=Ht,Zr(y,S,function(H,$,X){$.apply(_,H.concat(function(J){var ct=r(arguments,1);X(J,ct)}))},function(H,$){N.apply(_,[H].concat($))})}}var Rc=function(){return kc.apply(null,r(arguments).reverse())},id=Array.prototype.concat,_l=function(y,S,_,N){N=N||Ht;var H=U(_);Mi(y,S,function($,X){H($,function(J){return J?X(J):X(null,r(arguments,1))})},function($,X){for(var J=[],ct=0;ct<X.length;ct++)X[ct]&&(J=id.apply(J,X[ct]));return N($,J)})},Mm=ze(_l,1/0),wc=ze(_l,1),Sc=function(){var y=r(arguments),S=[null].concat(y);return function(){var _=arguments[arguments.length-1];return _.apply(this,S)}};function Ml(y){return y}function xo(y,S){return function(_,N,H,$){$=$||Ht;var X=!1,J;_(N,function(ct,Ct,ut){H(ct,function(xt,Jt){xt?ut(xt):y(Jt)&&!J?(X=!0,J=S(!0,ct),ut(null,go)):ut()})},function(ct){ct?$(ct):$(null,X?J:S(!1))})}}function Cn(y,S){return S}var bs=Qr(xo(Ml,Cn)),ti=po(xo(Ml,Cn)),Ul=ze(ti,1);function od(y){return function(S){var _=r(arguments,1);_.push(function(N){var H=r(arguments,1);typeof console=="object"&&(N?console.error&&console.error(N):console[y]&&Cs(H,function($){console[y]($)}))}),U(S).apply(null,_)}}var Um=od("dir");function Om(y,S,_){_=br(_||Ht);var N=U(y),H=U(S);function $(J){if(J)return _(J);var ct=r(arguments,1);ct.push(X),H.apply(this,ct)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}X(null,!0)}function sd(y,S,_){_=br(_||Ht);var N=U(y),H=function($){if($)return _($);var X=r(arguments,1);if(S.apply(this,X))return N(H);_.apply(null,[null].concat(X))};N(H)}function Nm(y,S,_){sd(y,function(){return!S.apply(this,arguments)},_)}function Pm(y,S,_){_=br(_||Ht);var N=U(S),H=U(y);function $(J){if(J)return _(J);H(X)}function X(J,ct){if(J)return _(J);if(!ct)return _(null);N($)}H(X)}function bo(y){return function(S,_,N){return y(S,N)}}function Lc(y,S,_){Yr(y,bo(U(S)),_)}function Ol(y,S,_,N){Sl(S)(y,bo(U(_)),N)}var vo=ze(Ol,1);function Ic(y){return M(y)?y:o(function(S,_){var N=!0;S.push(function(){var H=arguments;N?E(function(){_.apply(null,H)}):_.apply(null,H)}),y.apply(this,S),N=!1})}function ir(y){return!y}var Bo=Qr(xo(ir,ir)),Nl=po(xo(ir,ir)),Dc=ze(Nl,1);function Fm(y){return function(S){return S==null?void 0:S[y]}}function vs(y,S,_,N){var H=new Array(S.length);y(S,function($,X,J){_($,function(ct,Ct){H[X]=!!Ct,J(ct)})},function($){if($)return N($);for(var X=[],J=0;J<S.length;J++)H[J]&&X.push(S[J]);N(null,X)})}function or(y,S,_,N){var H=[];y(S,function($,X,J){_($,function(ct,Ct){ct?J(ct):(Ct&&H.push({index:X,value:$}),J())})},function($){$?N($):N(null,Co(H.sort(function(X,J){return X.index-J.index}),Fm("value")))})}function _c(y,S,_,N){var H=bl(S)?vs:or;H(y,S,U(_),N||Ht)}var Mc=Qr(_c),Pl=po(_c),Uc=ze(Pl,1);function Km(y,S){var _=br(S||Ht),N=U(Ic(y));function H($){if($)return _($);N(H)}H()}var Oc=function(y,S,_,N){N=N||Ht;var H=U(_);Mi(y,S,function($,X){H($,function(J,ct){return J?X(J):X(null,{key:ct,val:$})})},function($,X){for(var J={},ct=Object.prototype.hasOwnProperty,Ct=0;Ct<X.length;Ct++)if(X[Ct]){var ut=X[Ct].key,xt=X[Ct].val;ct.call(J,ut)?J[ut].push(xt):J[ut]=[xt]}return N($,J)})},To=ze(Oc,1/0),K=ze(Oc,1),q=od("log");function j(y,S,_,N){N=Di(N||Ht);var H={},$=U(_);_i(y,S,function(X,J,ct){$(X,J,function(Ct,ut){if(Ct)return ct(Ct);H[J]=ut,ct()})},function(X){N(X,H)})}var mt=ze(j,1/0),wt=ze(j,1);function Gt(y,S){return S in y}function Ie(y,S){var _=Object.create(null),N=Object.create(null);S=S||Ml;var H=U(y),$=o(function(J,ct){var Ct=S.apply(null,J);Gt(_,Ct)?E(function(){ct.apply(null,_[Ct])}):Gt(N,Ct)?N[Ct].push(ct):(N[Ct]=[ct],H.apply(null,J.concat(function(){var ut=r(arguments);_[Ct]=ut;var xt=N[Ct];delete N[Ct];for(var Jt=0,Pe=xt.length;Jt<Pe;Jt++)xt[Jt].apply(null,ut)})))});return $.memo=_,$.unmemoized=y,$}var Yt;c?Yt=process.nextTick:l?Yt=setImmediate:Yt=d;var Nc=h(Yt);function ld(y,S,_){_=_||Ht;var N=bl(S)?[]:{};y(S,function(H,$,X){U(H)(function(J,ct){arguments.length>2&&(ct=r(arguments,1)),N[$]=ct,X(J)})},function(H){_(H,N)})}function wn(y,S){ld(Yr,y,S)}function Fl(y,S,_){ld(Sl(S),y,_)}var ad=function(y,S){var _=U(y);return Dl(function(N,H){_(N[0],H)},S,1)},yo=function(y,S){var _=ad(y,S);return _.push=function(N,H,$){if($==null&&($=Ht),typeof $!="function")throw new Error("task callback must be a function");if(_.started=!0,ke(N)||(N=[N]),N.length===0)return E(function(){_.drain()});H=H||0;for(var X=_._tasks.head;X&&H>=X.priority;)X=X.next;for(var J=0,ct=N.length;J<ct;J++){var Ct={data:N[J],priority:H,callback:$};X?_._tasks.insertBefore(X,Ct):_._tasks.push(Ct)}E(_.process)},delete _.unshift,_};function Kl(y,S){if(S=Di(S||Ht),!ke(y))return S(new TypeError("First argument to race must be an array of functions"));if(!y.length)return S();for(var _=0,N=y.length;_<N;_++)U(y[_])(S)}function ko(y,S,_,N){var H=r(y).reverse();Zr(H,S,_,N)}function Wt(y){var S=U(y);return o(function(N,H){return N.push(function(X,J){if(X)H(null,{error:X});else{var ct;arguments.length<=2?ct=J:ct=r(arguments,1),H(null,{value:ct})}}),S.apply(this,N)})}function Vm(y){var S;return ke(y)?S=Co(y,Wt):(S={},As(y,function(_,N){S[N]=Wt.call(this,_)})),S}function cd(y,S,_,N){_c(y,S,function(H,$){_(H,function(X,J){$(X,!J)})},N)}var Vl=Qr(cd),ud=po(cd),$m=ze(ud,1);function Hm(y){return function(){return y}}function Ro(y,S,_){var N=5,H=0,$={times:N,intervalFunc:Hm(H)};function X(ut,xt){if(typeof xt=="object")ut.times=+xt.times||N,ut.intervalFunc=typeof xt.interval=="function"?xt.interval:Hm(+xt.interval||H),ut.errorFilter=xt.errorFilter;else if(typeof xt=="number"||typeof xt=="string")ut.times=+xt||N;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof y=="function"?(_=S||Ht,S=y):(X($,y),_=_||Ht),typeof S!="function")throw new Error("Invalid arguments for async.retry");var J=U(S),ct=1;function Ct(){J(function(ut){ut&&ct++<$.times&&(typeof $.errorFilter!="function"||$.errorFilter(ut))?setTimeout(Ct,$.intervalFunc(ct)):_.apply(null,arguments)})}Ct()}var ei=function(y,S){S||(S=y,y=null);var _=U(S);return o(function(N,H){function $(X){_.apply(null,N.concat(X))}y?Ro(y,$,H):Ro($,H)})};function $l(y,S){ld(xs,y,S)}var Hl=Qr(xo(Boolean,Ml)),Oi=po(xo(Boolean,Ml)),jl=ze(Oi,1);function fd(y,S,_){var N=U(S);vc(y,function($,X){N($,function(J,ct){if(J)return X(J);X(null,{value:$,criteria:ct})})},function($,X){if($)return _($);_(null,Co(X.sort(H),Fm("value")))});function H($,X){var J=$.criteria,ct=X.criteria;return J<ct?-1:J>ct?1:0}}function zl(y,S,_){var N=U(y);return o(function(H,$){var X=!1,J;function ct(){var Ct=y.name||"anonymous",ut=new Error('Callback function "'+Ct+'" timed out.');ut.code="ETIMEDOUT",_&&(ut.info=_),X=!0,$(ut)}H.push(function(){X||($.apply(null,arguments),clearTimeout(J))}),J=setTimeout(ct,S),N.apply(null,H)})}var jm=Math.ceil,Gl=Math.max;function wo(y,S,_,N){for(var H=-1,$=Gl(jm((S-y)/(_||1)),0),X=Array($);$--;)X[N?$:++H]=y,y+=_;return X}function So(y,S,_,N){var H=U(_);Mi(wo(0,y,1),S,H,N)}var zm=ze(So,1/0),Gm=ze(So,1);function Wm(y,S,_,N){arguments.length<=3&&(N=_,_=S,S=ke(y)?[]:{}),N=Di(N||Ht);var H=U(_);Yr(y,function($,X,J){H(S,$,X,J)},function($){N($,S)})}function Wl(y,S){var _=null,N;S=S||Ht,vo(y,function(H,$){U(H)(function(X,J){arguments.length>2?N=r(arguments,1):N=J,_=X,$(!X)})},function(){S(_,N)})}function ql(y){return function(){return(y.unmemoized||y).apply(null,arguments)}}function Xl(y,S,_){_=br(_||Ht);var N=U(S);if(!y())return _(null);var H=function($){if($)return _($);if(y())return N(H);var X=r(arguments,1);_.apply(null,[null].concat(X))};N(H)}function qm(y,S,_){Xl(function(){return!y.apply(this,arguments)},S,_)}var dd=function(y,S){if(S=Di(S||Ht),!ke(y))return S(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return S();var _=0;function N($){var X=U(y[_++]);$.push(br(H)),X.apply(null,$)}function H($){if($||_===y.length)return S.apply(null,arguments);N(r(arguments,1))}N([])},Tx={apply:i,applyEach:Vf,applyEachSeries:Hf,asyncify:x,auto:Bc,autoInject:_m,cargo:Ao,compose:Rc,concat:Mm,concatLimit:_l,concatSeries:wc,constant:Sc,detect:bs,detectLimit:ti,detectSeries:Ul,dir:Um,doDuring:Om,doUntil:Nm,doWhilst:sd,during:Pm,each:Lc,eachLimit:Ol,eachOf:Yr,eachOfLimit:_i,eachOfSeries:xs,eachSeries:vo,ensureAsync:Ic,every:Bo,everyLimit:Nl,everySeries:Dc,filter:Mc,filterLimit:Pl,filterSeries:Uc,forever:Km,groupBy:To,groupByLimit:Oc,groupBySeries:K,log:q,map:vc,mapLimit:Mi,mapSeries:$f,mapValues:mt,mapValuesLimit:j,mapValuesSeries:wt,memoize:Ie,nextTick:Nc,parallel:wn,parallelLimit:Fl,priorityQueue:yo,queue:ad,race:Kl,reduce:Zr,reduceRight:ko,reflect:Wt,reflectAll:Vm,reject:Vl,rejectLimit:ud,rejectSeries:$m,retry:Ro,retryable:ei,seq:kc,series:$l,setImmediate:E,some:Hl,someLimit:Oi,someSeries:jl,sortBy:fd,timeout:zl,times:zm,timesLimit:So,timesSeries:Gm,transform:Wm,tryEach:Wl,unmemoize:ql,until:qm,waterfall:dd,whilst:Xl,all:Bo,allLimit:Nl,allSeries:Dc,any:Hl,anyLimit:Oi,anySeries:jl,find:bs,findLimit:ti,findSeries:Ul,forEach:Lc,forEachSeries:vo,forEachLimit:Ol,forEachOf:Yr,forEachOfSeries:xs,forEachOfLimit:_i,inject:Zr,foldl:Zr,foldr:ko,select:Mc,selectLimit:Pl,selectSeries:Uc,wrapSync:x};e.default=Tx,e.apply=i,e.applyEach=Vf,e.applyEachSeries=Hf,e.asyncify=x,e.auto=Bc,e.autoInject=_m,e.cargo=Ao,e.compose=Rc,e.concat=Mm,e.concatLimit=_l,e.concatSeries=wc,e.constant=Sc,e.detect=bs,e.detectLimit=ti,e.detectSeries=Ul,e.dir=Um,e.doDuring=Om,e.doUntil=Nm,e.doWhilst=sd,e.during=Pm,e.each=Lc,e.eachLimit=Ol,e.eachOf=Yr,e.eachOfLimit=_i,e.eachOfSeries=xs,e.eachSeries=vo,e.ensureAsync=Ic,e.every=Bo,e.everyLimit=Nl,e.everySeries=Dc,e.filter=Mc,e.filterLimit=Pl,e.filterSeries=Uc,e.forever=Km,e.groupBy=To,e.groupByLimit=Oc,e.groupBySeries=K,e.log=q,e.map=vc,e.mapLimit=Mi,e.mapSeries=$f,e.mapValues=mt,e.mapValuesLimit=j,e.mapValuesSeries=wt,e.memoize=Ie,e.nextTick=Nc,e.parallel=wn,e.parallelLimit=Fl,e.priorityQueue=yo,e.queue=ad,e.race=Kl,e.reduce=Zr,e.reduceRight=ko,e.reflect=Wt,e.reflectAll=Vm,e.reject=Vl,e.rejectLimit=ud,e.rejectSeries=$m,e.retry=Ro,e.retryable=ei,e.seq=kc,e.series=$l,e.setImmediate=E,e.some=Hl,e.someLimit=Oi,e.someSeries=jl,e.sortBy=fd,e.timeout=zl,e.times=zm,e.timesLimit=So,e.timesSeries=Gm,e.transform=Wm,e.tryEach=Wl,e.unmemoize=ql,e.until=qm,e.waterfall=dd,e.whilst=Xl,e.all=Bo,e.allLimit=Nl,e.allSeries=Dc,e.any=Hl,e.anyLimit=Oi,e.anySeries=jl,e.find=bs,e.findLimit=ti,e.findSeries=Ul,e.forEach=Lc,e.forEachSeries=vo,e.forEachLimit=Ol,e.forEachOf=Yr,e.forEachOfSeries=xs,e.forEachOfLimit=_i,e.inject=Zr,e.foldl=Zr,e.foldr=ko,e.select=Mc,e.selectLimit=Pl,e.selectSeries=Uc,e.wrapSync=x,Object.defineProperty(e,"__esModule",{value:!0})})})(wp,wp.exports);var PT={exports:{}},Sp=PT.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),r=2;e===1/0;r*=2)e=Math.log(Math.pow(2,n/r))/Math.log(t)*r;for(var i=e-Math.floor(e),o="",r=0;r<Math.floor(e);r++){var s=Math.floor(Math.random()*t).toString(t);o=s+o}if(i){var l=Math.pow(t,i),s=Math.floor(Math.random()*l).toString(t);o=s+o}var c=parseInt(o,t);return c!==1/0&&c>=Math.pow(2,n)?Sp(n,t):o};Sp.rack=function(n,t,e){var r=function(o){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Sp(n,t)}while(Object.hasOwnProperty.call(i,l));return i[l]=o,l},i=r.hats={};return r.get=function(o){return r.hats[o]},r.set=function(o,s){return r.hats[o]=s,r},r.bits=n||128,r.base=t||16,r};var FT=Xo,GO=OT,WO=NT,Kh=Fr,Lp=wp.exports,qO=PT.exports,KT=nl.ACTIONS,VT=Ve;function Ve(n,t){if(FT.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}FT.mixin(Ve),Ve.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Ve.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Ve.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||qO();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Ve.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(r){if(r)return t._callbackOrEmit(r,n);var i=Object.keys(t._remotePresenceInstances);Lp.parallel([function(o){Lp.each(e,function(s,l){t.localPresences[s].destroy(l)},o)},function(o){if(!t._wantsDestroy)return o();Lp.each(i,function(s,l){t._remotePresenceInstances[s].destroy(l)},o)}],function(o){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(o,n)})})},Ve.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?KT.presenceSubscribe:KT.presenceUnsubscribe,r=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[r]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,r,this)},Ve.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Ve.prototype._receiveUpdate=function(n,t){var e=Kh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var r=this,i=Kh.digOrCreate(this._remotePresenceInstances,t.id,function(){return r._createRemotePresence(t.id)});i.receiveUpdate(t)},Ve.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Ve.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()}},Ve.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Ve.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Ve.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 r=this;this.subscribe(function(i){r._callEachOrEmit(n,i)})},Ve.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Ve.prototype._callbackOrEmit=function(n,t){if(t)return Kh.nextTick(t,n);n&&this.emit("error",n)},Ve.prototype._createLocalPresence=function(n){return new GO(this,n)},Ve.prototype._createRemotePresence=function(n){return new WO(this,n)},Ve.prototype._callEachOrEmit=function(n,t){var e=Kh.callEach(n,t);!e&&t&&this.emit("error",t)};var Ru=OT,$T=Uh,XO=Fr,HT=$T.CODES,YO=Vr;function Vr(n,t){Ru.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()}Vr.prototype=Object.create(Ru.prototype),Vr.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:HT.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,Ru.prototype.submit.call(this,n,t)},Vr.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),Ru.prototype.destroy.call(this,n)},Vr.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={})})}},Vr.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)},Vr.prototype._transformAgainstOp=function(n,t){var e=this,r=this._doc._dataStateVersion;this._pendingMessages.forEach(function(i){var o=e._docDataVersionByPresenceVersion[i.pv];if(!(o>=r))try{i.p=e._transformPresence(i.p,n,t),e._docDataVersionByPresenceVersion[i.pv]=r}catch(l){var s=e._getCallback(i.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(i){this.emit("error",i)}},Vr.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Vr.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Vr.prototype._message=function(){var n=Ru.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Vr.prototype._transformPresence=function(n,t,e){var r=this._doc.type;if(!XO.supportsPresence(r))throw new $T(HT.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+r.name);return r.transformPresence(n,t,e)};var jT={};(function(n){var t=Tu,e=Uh,r=Fr,i=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[c];if(d==null||typeof d!="object")return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(i.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(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(i.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,c){if(typeof l!="object")return new e(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(i.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=c.create,h=t.map[d.type];if(!h)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(E){return E}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var C=o(l,c.op);if(C)return C;l.v++}else l.v++};function o(l,c){if(!l.type)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,c)}catch(h){return new e(i.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,c,d){if(c.v!=null&&c.v!==d.v)return new e(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(c.create||"op"in c)return new e(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in c||c.create||c.del)||"op"in d&&c.create)return new e(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in c){if(!l)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,d.op,"left")}catch(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,d){d=d||{};for(var h=0;h<c.length;h++){var C=c[h];if(d._normalizeLegacyJson0Ops)try{s(l,C)}catch{return new e(i.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=C.v;var E=n.apply(l,C);if(E)return E}},n.transformPresence=function(l,c,d){var h=this.checkOp(c);if(h)return h;var C=l.t;if(typeof C=="string"&&(C=t.map[C]),!C)return{code:i.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!r.supportsPresence(C))return{code:i.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:C.transformPresence(l.p,c.op,d)}catch(E){return{code:i.ERR_PRESENCE_TRANSFORM_FAILED,message:E.message||E}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var d=c.op;if(!!d){var h=l.data;d.length>1&&(h=r.clone(h));for(var C=0;C<d.length;C++){var E=d[C];typeof E.lm=="string"&&(E.lm=+E.lm);for(var x=E.p,v=h,R=0;R<x.length;R++){var L=x[R];Object.prototype.toString.call(v)=="[object Array]"?x[R]=+L:v.constructor===Object&&(x[R]=L.toString()),v=v[L]}C<d.length-1&&(h=t.defaultType.apply(h,[E]))}}}}})(jT);var wu=NT,QO=jT,JO=gr;function gr(n,t){wu.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()}gr.prototype=Object.create(wu.prototype),gr.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},gr.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),wu.prototype.destroy.call(this,n)},gr.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)},gr.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))}})}},gr.prototype._handleOp=function(n,t,e){var r=e===this.src;this._transformAgainstOp(n,r),this._cacheOp(n,r),this._setPendingPresence()},wu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},wu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},gr.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)}},gr.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++):QO.transformPresence(this._pending,t,e)}var r=this._pending.v>=this._doc.version;return r&&this._stopCachingOps(),r},gr.prototype._startCachingOps=function(){this._opCache=[]},gr.prototype._stopCachingOps=function(){this._opCache=null},gr.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var zT=VT,ZO=YO,tN=JO;function _a(n,t,e){var r=_a.channel(t,e);zT.call(this,n,r),this.collection=t,this.id=e}var eN=_a;_a.prototype=Object.create(zT.prototype),_a.channel=function(n,t){return n+"."+t},_a.prototype._createLocalPresence=function(n){return new ZO(this,n)},_a.prototype._createRemotePresence=function(n){return new tN(this,n)};var nN=rN;function rN(n,t,e,r,i){this.id=n,this.v=t,this.type=e,this.data=r,this.m=i}var iN=nN,GT=Xo,WT=Su;function Su(n,t,e,r,i){if(GT.EventEmitter.call(this),typeof i!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=r,this.collection=e,this.callback=i,this.sent=!1}GT.mixin(Su),Su.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Su.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Su.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,r=new iN(this.id,t.v,t.type,t.data,e);this.callback(null,r)};var qT=WT,oN=Fr,sN=nl.ACTIONS,lN=Ip;function Ip(n,t,e,r,i,o){if(qT.call(this,n,t,e,r,o),!oN.isValidVersion(i))throw new Error("Snapshot version must be a positive integer or null");this.version=i}Ip.prototype=Object.create(qT.prototype),Ip.prototype._message=function(){return{a:sN.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var XT=WT,aN=Fr,cN=nl.ACTIONS,uN=Dp;function Dp(n,t,e,r,i,o){if(XT.call(this,n,t,e,r,o),!aN.isValidTimestamp(i))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=i}Dp.prototype=Object.create(XT.prototype),Dp.prototype._message=function(){return{a:cN.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var fN=NO,dN=$O,hN=VT,YT=eN,mN=lN,gN=uN,QT=Xo,Ma=Uh,ie=nl.ACTIONS,JT=Tu,$r=Fr,Lu=RT,Iu=Ma.CODES;function ZT(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var pN=kt;function kt(n){QT.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=ZT(n),this.bindToSocket(n)}QT.mixin(kt),kt.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=ZT(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(r){try{var i=typeof r.data=="string"?JSON.parse(r.data):r.data}catch{Lu.warn("Failed to parse message",r);return}e.debug&&Lu.info("RECV",JSON.stringify(i));var o={data:i};if(e.emit("receive",o),!!o.data)try{e.handleMessage(o.data)}catch(s){$r.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(r){e.emit("connection error",r)},n.onclose=function(r){r==="closed"||r==="Closed"?e._setState("closed",r):r==="stopped"||r==="Stopped by server"?e._setState("stopped",r):e._setState("disconnected",r)}},kt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=t2(n.error,n),delete n.error),n.a){case ie.initLegacy:return this._handleLegacyInit(n);case ie.handshake:return this._handleHandshake(t,n);case ie.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ie.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ie.queryUnsubscribe:return;case ie.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 ie.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ie.bulkSubscribe:case ie.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ie.snapshotFetch:case ie.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ie.fetch:var r=this.getExisting(n.c,n.d);r&&r._handleFetch(t,n.data);return;case ie.subscribe:case ie.unsubscribe:var r=this.getExisting(n.c,n.d);r&&r._handleSubscribe(t,n.data);return;case ie.op:var r=this.getExisting(n.c,n.d);r&&r._handleOp(t,n);return;case ie.presence:return this._handlePresence(t,n);case ie.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ie.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ie.presenceRequest:return this._handlePresenceRequest(t,n);case ie.pingPong:return this._handlePingPong(t);default:Lu.warn("Ignoring unrecognized message",n)}};function t2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}kt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var r in t.data){var i=t.data[r],o=this.getExisting(t.c,r);o&&(n?o[e](n):i.error?o[e](t2(i.error)):o[e](null,i))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var r=t.b[s],o=this.getExisting(t.c,r);o&&o[e](n)}else if(t.b)for(var r in t.b){var o=this.getExisting(t.c,r);o&&o[e](n)}else Lu.error("Invalid bulk message",t)},kt.prototype._reset=function(){this.agent=null},kt.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 Ma(Iu.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 r in this.queries){var i=this.queries[r];i._onConnectionStateChanged()}for(var o in this.collections){var s=this.collections[o];for(var r in s)s[r]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var r in this._snapshotRequests){var c=this._snapshotRequests[r];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},kt.prototype.startBulk=function(){this.bulk||(this.bulk={})},kt.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},kt.prototype._sendBulk=function(n,t,e){if(!!e){var r=[],i={},o=0,s;for(var l in e){var c=e[l];c==null?r.push(l):(i[l]=c,s=l,o++)}if(r.length===1){var l=r[0];this.send({a:n,c:t,d:l})}else r.length&&this.send({a:"b"+n,c:t,b:r});if(o===1){var d=i[s];this.send({a:n,c:t,d:s,v:d})}else o&&this.send({a:"b"+n,c:t,b:i})}},kt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var r=this.bulk[t.collection]||(this.bulk[t.collection]={}),i=r[n]||(r[n]={}),o=i.hasOwnProperty(t.id);return i[t.id]=e,o}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},kt.prototype.sendFetch=function(n){return this._sendActions(ie.fetch,n,n.version)},kt.prototype.sendSubscribe=function(n){return this._sendActions(ie.subscribe,n,n.version)},kt.prototype.sendUnsubscribe=function(n){return this._sendActions(ie.unsubscribe,n)},kt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ie.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)},kt.prototype.send=function(n){this.debug&&Lu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},kt.prototype.ping=function(){if(!this.canSend)throw new Ma(Iu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ie.pingPong};this.send(n)},kt.prototype.close=function(){this.socket.close()},kt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},kt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),r=e[t];return r||(r=e[t]=new fN(this,n,t),this.emit("doc",r)),r._wantsDestroy=!1,r},kt.prototype._destroyDoc=function(n){!n._wantsDestroy||($r.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},kt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},kt.prototype._createQuery=function(n,t,e,r,i){var o=this.nextQueryId++,s=new dN(n,this,o,t,e,r,i);return this.queries[o]=s,s.send(),s},kt.prototype._destroyQuery=function(n){delete this.queries[n.id]},kt.prototype.createFetchQuery=function(n,t,e,r){return this._createQuery(ie.queryFetch,n,t,e,r)},kt.prototype.createSubscribeQuery=function(n,t,e,r){return this._createQuery(ie.querySubscribe,n,t,e,r)},kt.prototype.hasPending=function(){return!!(this._firstDoc(Vh)||this._firstQuery(Vh)||this._firstSnapshotRequest())};function Vh(n){return n.hasPending()}kt.prototype.hasWritePending=function(){return!!this._firstDoc(CN)};function CN(n){return n.hasWritePending()}kt.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 r=this._firstSnapshotRequest();if(r){r.once("ready",this._nothingPendingRetry(n));return}$r.nextTick(n)},kt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$r.nextTick(function(){t.whenNothingPending(n)})}},kt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var r in e){var i=e[r];if(n(i))return i}}},kt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},kt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},kt.prototype.fetchSnapshot=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new mN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},kt.prototype.fetchSnapshotByTimestamp=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new gN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},kt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},kt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},kt.prototype._initializeHandshake=function(){this.send({a:ie.handshake,id:this.id})},kt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},kt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},kt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Ma(Iu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(JT.map[n.type]!==JT.defaultType)return this.emit("error",new Ma(Iu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Ma(Iu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},kt.prototype.getPresence=function(n){var t=this,e=$r.digOrCreate(this._presences,n,function(){return new hN(t,n)});return e._wantsDestroy=!1,e},kt.prototype.getDocPresence=function(n,t){var e=YT.channel(n,t),r=this,i=$r.digOrCreate(this._presences,e,function(){return new YT(r,n,t)});return i._wantsDestroy=!1,i},kt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var r={a:n,ch:e.channel,seq:t};return this.send(r),r.seq},kt.prototype._addPresence=function(n){$r.digOrCreate(this._presences,n.channel,function(){return n})},kt.prototype._handlePresenceSubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},kt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},kt.prototype._handlePresence=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},kt.prototype._handlePresenceRequest=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var e2=pN,EN=Tu;const Du={err:1001,msg:"user auth error",name:"AuthError"},$h={err:1002,msg:"you don't have required permission",name:"PermissionError"},_p={err:1003,msg:"Too many user connected",name:"MaxUserError"},_u={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},AN={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},xN={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},rl="x-live-editor-token",Ua="x-live-editor-base-url",dn=I("auth-connection");function bN(n){try{n()}catch(t){dn.error(t)}}class vN{constructor(t,e){g(this,"enabled",!0);g(this,"connection");g(this,"ws");g(this,"retryCount");g(this,"events",new Cb.EventEmitter);g(this,"token",null);g(this,"resourceToken",null);g(this,"reAuth",async()=>{if(this.connection&&this.reauthFunc){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}});this.url=t,this.reauthFunc=e,this.retryCount=0,window.addEventListener("offline",()=>{var r;this.token="fake",(r=this.connection)==null||r.close()})}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async auth(t){p(dn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,r=await window.fetch(e,{method:"GET",headers:{[rl]:t.token,[Ua]:this.getBase64BaseURL()},credentials:"include"});return r.status,this.enabled?(this.token=t.token,await r.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Ua]:li(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new G6.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(e2.prototype),p(dn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const r=this.connection.handleMessage.bind(this.connection);let i=!1;this.connection.handleMessage=o=>{var l;const s=o;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in s||s.a==="pong")this.handleMessage(s);else{Object.prototype.hasOwnProperty.call(s,"a")&&s.a==="hs"&&(i||(i=!0)),Object.prototype.hasOwnProperty.call(s,"a")&&s.a!=="init"&&s.a!=="hs"&&(i&&(dn.info("retrying re-auth success"),i=!1,this.emitAuthRecover()),this.retryCount=0);try{r(s)}catch(c){if((c==null?void 0:c.type)==="writeConflict"){this.emitWriteConflictError(c,s);return}if((l=c==null?void 0:c.message)!=null&&l.startsWith("Cannot invert subtype")){this.emitWriteConflictError(c,s);return}throw c}}},e2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc){this.retryCount>=5&&(dn.warn("retry auth times exceed 5, broadcast auth error"),this.emitAuthError()),this.retryCount+=1,dn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){dn.error(t),setTimeout(()=>this.handleAuthError(),0)}}}emitPermissionError(){const t=new Error($h.msg);t.code=$h.err,this.events.emit("error",t)}emitAuthRecover(){this.events.emit("authRecover")}emitAuthError(){const t=new Error(Du.msg);t.code=Du.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(_u.msg);t.code=_u.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 r=e.err;if(r===Du.err)dn.warn("auth error"),this.handleAuthError();else if(r===_p.err)dn.warn(_p.msg),this.emitMaxUsersError();else if(r===_u.err){dn.warn(_u.msg);try{this.emitRequestReloadError()}catch(i){dn.error(`error occurred while process reload error: ${JSON.stringify(i)}`)}finally{this.end(!1)}}else r===$h.err?this.emitPermissionError():(dn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError())}get(t,e){return p(dn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(p(dn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onAuthError(t){this.events.addListener("error",t)}onAuthRecover(t){this.events.addListener("authRecover",t)}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){p(dn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){p(dn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),bN(()=>{var r;return(r=this.connection)==null?void 0:r.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}I("utils/file");function BN(){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}BN();async function TN(n){const e=n.size,r=Math.floor((e+102400-1)/102400),i=new W6.Hash;for(let s=0;s<r;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();i.update(new Uint8Array(h))}const o=i.digest();return li(o)}const Ei=I("sharedb-doc/client"),yN=Ab.default.create();class kN{constructor(t,e,r){g(this,"connection");g(this,"auth");g(this,"doc",null);g(this,"reauthFunc");g(this,"clientId",Z());g(this,"getDoc",async()=>{const t=r=>new Promise((i,o)=>{r.fetch(s=>{s?o(s):i()})});p(Ei,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth),window.addEventListener("online",async()=>{await this.connection.init({...this.auth,token:"fake"})});const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),Ei.debug(e),e});this.auth=t;const i=`${e}/${this.auth.appId}/${this.auth.docId}`;EN.register(Bd.type),this.connection=new vN(i,r),this.reauthFunc=r}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Ei,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,r=>{(t==="error"||this.doc)&&e(r)})}onAuthError(t){this.connection.onAuthError(t)}onAuthRecover(t){this.connection.onAuthRecover(t)}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,r,i,o){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...o},data:{name:r,size:i}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const r=`${this.apiServer()}/resources`;try{const i=`${r}/hash`,o=await this.request(i,{method:"post",headers:{[rl]:this.connection.token},data:{resources:t}});return o.data&&Array.isArray(o.data)?o.data:[]}catch{return[]}}async uploadFile(t,e,r,i,o){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=x=>{Ei.info(`on progress: ${x.loaded}`);let v=x.loaded*100/s;v>100&&(v=100),i(v)},c=await TN(e),d=await this.getFileUrlByHash(t,c,e.name,e.size,r);if(d)return i(-1),d;let h=t;o!=null&&o.thumbnail&&(h+="/thumbnail");const C=new FormData;C.append("file-size",`${e.size}`),C.append("file-hash",c),C.append("file",e,e.name);const E=await this.request(h,{method:"post",data:C,withCredentials:!0,headers:{...r},onUploadProgress:l});return Ei.info(E),i(100),Array.isArray(E.data)?E.data[0]:E.data}async uploadResource(t,e=()=>{},r){const o=`${this.apiServer()}/resources`;p(Ei,this.connection.token,"no connection token");const s=await this.uploadFile(o,t,{[rl]:this.connection.token},e,r);return p(Ei,s,"no result"),s}async request(t,e){var o,s;let r=this.connection.token,i;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),p(Ei,r,"no token"),c.headers={...c.headers,[rl]:r,[Ua]:this.connection.getBase64BaseURL()};try{return await yN(t,c)}catch(d){if(i=d,((o=d==null?void 0:d.response)==null?void 0:o.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;r=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw p(Ei,i,"no error"),i}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=xb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Ei,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const r=`${this.apiServer()}/resources/external/${li(t)}`;return(await this.request(r)).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 i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken&&o.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}reAuth(){this.connection.reAuth()}}function RN(){return{blocks:[{id:Z(),type:"text",text:[]}],comments:{},meta:{}}}const Mp=I("block-ids");class wN{constructor(){g(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((i,o)=>o-i);for(let i=0;i<e.length;i++){const o=e[i];if(o>=t){const s=this.ids.get(o);p(Mp,s!==void 0,"old id is not exists"),this.ids.delete(o),this.ids.set(o+1,s)}}const r=Z();this.ids.set(t,r)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((r,i)=>r-i);for(let r=0;r<e.length;r++){const i=e[r];if(i>t){const o=this.ids.get(i);p(Mp,o!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i-1,o)}}}getId(t){let e=this.ids.get(t);return e||(e=Z(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class SN{constructor(){g(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new wN,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 r=0;r<e.length;r++){const i=e[r],o=i[1].getById(t);if(o)return{containerId:i[0],blockIndex:o[0]}}return p(Mp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class n2{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,r)=>{t[r]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Up=I("op-parse-handler");class LN{constructor(t,e){g(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const r={...t,containerId:(i=>i==="blocks"?"root":i)(t.containerId)};this.actions.push(r)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,r){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:r})}onDeleteBlockData(t,e,r){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:r})}onInsertBlockData(t,e,r,i){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:r,value:i})}onUpdateBlockText(t,e,r){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:r})}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,r=new Map,i=new SN,o=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of o)if(s.type==="deleteBlock"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);i.onDeleteBlock(l.containerId,l.blockIndex);const d=r.get(c);d&&(Up.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),r.delete(c));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,c=`${l.containerId}-${l.blockIndex}`;if(e.has(c)){Up.warn("delete block data after delete block, ignore it");continue}const d=i.getBlockId(l.containerId,l.blockIndex);let h=r.get(d);h||(h=new n2,r.set(d,h)),h.delete(l.key)}else p(Up,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);let d=r.get(c);d||(d=new n2,r.set(c,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(r.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:d}=i.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(c,d,l.toDocBlockDelta(),this.local)})}}const $e=I("op-parser");class r2{}class Op{constructor(t){g(this,"key");this.key=t}}function IN(n,t,e){const r=t.concat(),i=r[0];if(typeof i!="number"||(r.shift(),r.length===1))return!1;const o=r[0];if(typeof o!="object"||!o.i||Object.keys(o).length!==1)return!1;for(let l=1;l<r.length;l++){const c=r[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=o.i;p($e,s.id,"block id is required"),p($e,s.type,"block type is required");for(let l=1;l<r.length;l++){const c=r[l],d=c[0],h=c[1];s[d]=h.i}return e.onInsertBlock(n,i,s),!0}function Np(n,t,e,r){if(e==="upsert"&&IN(n,t,r))return;p($e,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const i=t.concat(),o=i[0];i.shift();const s=[];for(;i.length>0;){const l=i[0];if(l==="text"){const c=i[1];if(p($e,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),p($e,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),i.splice(0,2),e==="upsert"){const h=c.e;r.onUpdateBlockText(n,o,h)}p($e,i.length===0,`invalid block ops.length !== 0, ${JSON.stringify(i)}`)}else if(Array.isArray(l)){p($e,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];p($e,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const d=l[1];if(c==="text"){if(p($e,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&r.onInsertBlockData(n,o,c,d.i),d.r&&e==="remove"&&r.onDeleteBlockData(n,o,c),d.et==="rich-text"&&e==="upsert"){const C=d.e;r.onUpdateBlockText(n,o,C)}}else e==="remove"&&d.r&&s.push(new Op(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i);i.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new r2),e==="upsert"&&c.i&&r.onInsertBlock(n,o,c.i),i.shift()}else{p($e,typeof l=="string","data is not string"),p($e,l!=="text","data !== 'text'"),p($e,i.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(i)}`);const c=l,d=i[1];e==="remove"&&d.r&&s.push(new Op(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i),i.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof r2?r.onDeleteBlock(n,o):l instanceof Op?r.onDeleteBlockData(n,o,l.key):p($e,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function DN(n,t,e){$e.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function _N(n,t,e){const r=n[1],i=n[2];p($e,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),p($e,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?$e.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&e.onUpdateComment(r):i.i?t==="upsert"&&e.onCreateComment(r):i.r?t==="remove"&&e.onDeleteComment(r):$e.error(`unknown comment op, ${JSON.stringify(n)}`)}function Pp(n,t,e){const r=n[0];if(Array.isArray(r)){r.forEach(s=>{Pp(s,t,e)});return}const i=r;if(p($e,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){DN(n);return}if(i==="comments"){_N(n,t,e);return}const o=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Np(o,s,t,e)}):n.slice(1).forEach(s=>{Np(o,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(o),s.i&&t==="upsert"&&e.onCreateContainer(o,s.i)}else p($e,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Np(o,n.slice(1),t,e)}function Fp(n,t,e){const r=new LN(t,e);for(let i=0;i<2;i++){const o=i===0?"remove":"upsert",s=gt.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Pp(c,o,r)}):Pp(s,o,r)}r.end()}const MN=I("sharedb-comments");function Kp(n){const t=n.blocks;p(MN,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([r,i])=>{Array.isArray(i)&&(e.blocks[r]=i)}),gt.default(e)}function i2(n){const{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}}function Vp(n,t){const e=EO(t),{comments:r,meta:i,blocks:o,...s}=e,l={...n,blocks:o,...s},c=gt.default(l);return delete c.children,c}const oe=I("sharedb-doc/doc-container"),o2="ot-json1";Bd.type.registerSubtype(AO.type),Bd.type.name=o2,Bd.type.invert=null;class Mu extends oa{constructor(e,r,i=!0){super();g(this,"doc");g(this,"client");g(this,"localPresence");g(this,"remoteCaretHandler",new pO);g(this,"batching",0);g(this,"status","clean");g(this,"disableLogout");g(this,"destroyed",!1);g(this,"handleNothingPending",()=>{this.setStatus("clean")});g(this,"handleCreate",()=>{this.handleReload("doc created")});g(this,"handleDel",()=>{});g(this,"handleReload",e=>{this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)})});g(this,"handleReset",async e=>{const r=new Error(`reset doc: ${e}`);r.code="ResetDoc",this.callbacks.forEach(i=>{var o;return(o=i.onError)==null?void 0:o.call(i,r)}),this.destroy()});g(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});g(this,"insertObject",async(e,r,i)=>{const o=[e,r,{i}];return this.submitOp(o)});g(this,"deleteObject",async(e,r)=>{const i=[e,r,{r:!0}];return this.submitOp(i)});g(this,"replaceObject",async(e,r,i)=>{const o=[e,r,{r:!0,i}];return this.submitOp(o)});g(this,"updateObject",async(e,r,i)=>{const o=this.data()[e][r],s=[e,r];return Object.entries(i).forEach(([l,c])=>{if(!jc.default(o[l],c))if(o[l]===void 0){if(c!=null){const d={i:c};s.push([l,d])}}else if(c==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:c};s.push([l,d])}}),Object.entries(o).forEach(([l,c])=>{if((i[l]===void 0||i[l]===null)&&c!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});g(this,"broadcastMessage",async e=>{const r={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(r)});g(this,"data",()=>this.doc.data);g(this,"submitOp",async e=>new Promise((r,i)=>{if(this.destroyed){oe.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},o=>{o?(oe.error(`invalid op, ${o.message}, ${JSON.stringify(e)}`),i(o),oe.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):r()}),this.doc.data||(oe.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));g(this,"createDoc",async e=>new Promise((r,i)=>{this.doc.create(e,o2,o=>{o?i(o):r()})}));g(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const r=e.map(({containerId:i,blocks:o})=>[oo(i),{i:o}]);return this.submitOp([r])});g(this,"submitDeleteChildContainer",async e=>{const r=[oo(e),{r:!0}];return this.submitOp(r)});g(this,"submitInsertBlock",async(e,r,i)=>{const o=[oo(e),r,{i}];return this.submitOp(o)});g(this,"submitDeleteBlock",async(e,r)=>{const i=[oo(e),r,{r:!0}];return this.submitOp(i)});g(this,"submitUpdateBlockData",async(e,r,i)=>{if(i.delete.length===0&&Object.keys(i.insert).length===0)return Promise.resolve();const o=[oo(e),r],s=new Set(i.delete);Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c)){const h={r:!0,i:d};o.push([c,h])}});const l=new Set(Object.keys(i.insert));return i.delete.forEach(c=>{if(l.has(c))return;const d={r:!0};o.push([c,d])}),Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c))return;const h={i:d};o.push([c,h])}),this.submitOp(o)});g(this,"submitUpdateRichText",async(e,r,i)=>{const o=[oo(e),r,"text",{e:i,et:"rich-text"}];return this.submitOp(o)});g(this,"handleOp",(e,r,i)=>{if(this.destroyed){oe.warn("handleOp: destroyed");return}try{Fp(e,this,!!r)}catch(o){throw oe.error(o),o}});this.client=e,this.doc=r,this.doc.preventCompose=!0,this.disableLogout=i,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,p(oe,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const r=new kN(e.auth,e.serverUrl,e.reauthFunc),i=await r.getDoc(),o=new Mu(r,i,e.disableLogout);if(i.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await o.createDoc(e.templateData||RN())}return await o.initPresence(),await o.subscribe(),o.initEvents(),o}catch(r){throw oe.error(r),oe.error(`failed to load doc: ${JSON.stringify(r)}`),r}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onAuthError(e=>{this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}),this.client.onAuthRecover(()=>{this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}),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,r)=>{if(this.localPresence)e();else{const i=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);i.on("receive",(o,s)=>{this.onCustomMessage(s)}),i.subscribe(o=>{o?r(o):(this.localPresence=i.create(Z()),e())})}})}subscribe(){return new Promise((e,r)=>{this.doc.subscribe(i=>{i?r(i):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return io(this.data())}getContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[oo(e)];return p(oe,i,`no container data: ${e}`),gt.default(i)}findContainerBlocks(e){const r=this.data();p(oe,r,"no doc data");const i=r[oo(e)];return i!=null?i:null}getBlockData(e,r){const i=this.data();p(oe,i,"no doc data");const o=i[oo(e)];p(oe,o,`no container data: ${e}`);const s=o[r];return p(oe,s,`no block data: ${r}`),gt.default(s)}localInsertBlock(e,r,i){return this.submitInsertBlock(e,r,i),this.getBlockData(e,r)}localDeleteBlock(e,r){const i=this.getBlockData(e,r);return this.submitDeleteBlock(e,r),i}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(oe,o.text,"no block text");const s=gt.default(o.text);this.submitUpdateRichText(e,r,i);const l=fn.apply(s,i);return p(oe,l,"no block text"),l}localUpdateBlockData(e,r,i){const o=gt.default(this.getBlockData(e,r));return this.submitUpdateBlockData(e,r,i),o}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(r=>{this.submitDeleteChildContainer(r)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(r=>i2(r))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const r=this.data().comments[e];return Kp(r)}localCreateComment(e,r){const i=Vp(e,r),s=["comments",i.id,{i}];return this.submitOp(s)}localDeleteComment(e){const r=["comments",e,{r:!0}];return this.submitOp(r)}localUpdateComment(e,r){const i=Vp(e,r),o=["comments",e.id,{r:!0,i}];return this.submitOp(o)}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,r,i){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onDeleteBlock)==null?void 0:s.call(o,Da(e),r,i)})}onInsertBlock(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Da(e),r,i,o)})}onUpdateBlockData(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Da(e),r,i,o)})}onUpdateBlockText(e,r,i,o){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Da(e),r,i,o)})}onDeleteContainer(e,r){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not delete root container in doc"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,Da(e),r)})}onCreateContainer(e,r,i){p(oe,this.callbacks.length>0,"no callbacks"),p(oe,e!=="root","should not create root container in doc"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,Da(e),r,i)})}onDeleteComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteComment)==null?void 0:o.call(i,e,r)})}onCreateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onCreateComment)==null?void 0:o.call(i,e,r)})}onUpdateComment(e,r){p(oe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onUpdateComment)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){const r=e;(r==null?void 0:r.type)==="custom"&&(r==null?void 0:r.clientId)!==this.client.clientId?this.callbacks.forEach(i=>{var o;return(o=i.onCustomMessage)==null?void 0:o.call(i,r.data)}):(r==null?void 0:r.type)==="onlineUsers"&&setTimeout(()=>{const i={type:"custom",data:e,clientId:"-"};this.onCustomMessage(i)})}onAuthRecover(){this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}async addResources(e){let r=[];return e.forEach(o=>{const s=o.split("|");r.push(...s)}),r=Array.from(new Set(r)),await this.client.getFileUrlsByHashes(r)}async uploadResource(e,r){var o;return{resourceId:await this.client.uploadResource(e,(o=r==null?void 0:r.onProgress)!=null?o:()=>{})}}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}request(e,r){return this.client.request(e,r)}getUser(){const e=this.client.clientId,{permission:r,userId:i,displayName:o,avatarUrl:s}=this.client.auth;return{permission:r,clientId:e,userId:i,displayName:o,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return io(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return io(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:io(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:io(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,r){Fp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}triggerReAuth(){this.client.reAuth()}}I("remote-cursor");class s2{constructor(t){g(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});g(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));g(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const r=this.editor.findBlockById(e);r&&this.editor.reloadBlock(r)})});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 l2=I("remote-cursor-decorator");class $p{decorateText(t,e,r){const i=t.doc.getRemoteUsers();if(!i)return{};const o=new Map,{containerId:s,blockIndex:l}=e[e.length-1];p(l2,typeof s=="string","invalid path containerId"),p(l2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),d=un(r);return i.getSimpleCursors(c.id).forEach((C,E)=>{E>d&&(E=d);const x=C.map(R=>({id:Z(),type:"remote-cursor",name:R.user.displayName,time:R.time,rainbowIndex:R.user.rainbowIndex})),v=o.get(E);v?v.push(...x):o.set(E,x)}),{insertions:o}}}const Hp=I("sharedb-doc/share-db-server"),UN=Ab.default.create();class ON{constructor(t,e){g(this,"auth");g(this,"clientId",Z());this.serverUrl=e,this.auth=t}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Hp,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}apiServer(){const t=`${this.serverUrl}/${this.auth.appId}/${this.auth.docId}`;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}`)}getBaseURL(){const t=new URL(this.apiServer());return`${t.protocol}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async request(t,e){var o;const r=this.auth.token,i=e||{};i.url=t,i.headers||(i.headers={}),p(Hp,r,"no token"),i.headers={...i.headers,[rl]:r,[Ua]:this.getBase64BaseURL()};try{return await UN(t,i)}catch(s){throw(o=s.response)!=null&&o.data&&(s.responseData=s.response.data),s}}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=xb.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Hp,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).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 i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken,e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}}const NN=I("sharedb-doc/share-db-server");function a2(n){const t=new URL(n);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}function PN(n){return li(a2(n))}class Hh extends oa{constructor(e){super();g(this,"remoteUsers",new Bu);g(this,"client");this.options=e,this.client=new ON(e.auth,e.serverUrl)}destroy(){}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}getRemoteUsers(){return this.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return io(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return io(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:io(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:io(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}parseHistoryData(e,r){Fp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}static async auth(e,r){p(NN,e.token,"no auth token");const i=`${a2(r)}/auth`,o=await window.fetch(i,{method:"GET",headers:{[rl]:e.token,[Ua]:PN(r)},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return await o.json()}static async load(e){const r=`${e.serverUrl}/${e.auth.appId}/${e.auth.docId}`;return await this.auth(e.auth,r),new Hh(e)}}class c2 extends Be.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,r){if(Xt(ai(this.editor,t)))return;const i=this.editor.getBlockByIndex(t,e),o=et(this.editor.getContainerById(t));o&&this.emit("change",this.editor,o,i,r)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}onInsertBlock(t,e){setTimeout(()=>{this.handleChild(t,e,"insert")})}onDeleteBlock(t,e){this.handleChild(t,e,"remove")}destroy(){this.editor.doc.unregisterCallback(this)}}function u2(n,t){n.addCustom("child-block-tracker",()=>new c2(n)).addListener("change",t)}function f2(n,t){n.addCustom("child-block-tracker",()=>new c2(n)).removeListener("change",t)}const zat="",FN={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"}},KN={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},VN={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"}};D.mergeLang({"zh-CN":FN,"en-US":KN,"ja-JP":VN});const Gat="";I("button");function pr(n,t,e,r,i){const o=B("button",["editor-button"],null);return o.setAttribute("data-button-id",n),i&&o.setAttribute(`data-editor-tooltip-${i}`,t),e?typeof e=="string"?e.startsWith("<")?o.innerHTML=e:o.innerText=e:o.appendChild(e):o.innerText=t,r&&(r.indexOf("checked")!==-1&&z(o,"checked"),r.indexOf("disabled")!==-1&&(o.disabled=!0),r.indexOf("primary")!==-1&&z(o,"primary")),o}const Wat="",jh=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
32
32
|
<path d="M8.00874 7.89952L12.9497 2.94975M8.00874 7.89952L12.9497 12.8492M8.00874 7.89952L3.05025 12.8492M8.00874 7.89952L3.05025 2.94975" stroke="currentColor" stroke-linejoin="round"/>
|
|
33
33
|
</svg>
|
|
34
34
|
`,d2=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|