@ones-editor/editor 0.0.3-beta.38 → 0.0.3-beta.39

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
@@ -23,7 +23,7 @@ Available method signatures are:
23
23
  `)}function nb(n,t){return t.blocks.root.map(r=>Yg(n,r,t)).join(`
24
24
  `)}const Ll=w("action-helper");function io(n,t){const e=j(t),o=U(e),r=K(t);return n.doc.getBlockData(o,r)}function we(n,t){d(Ll,H(n,t),"not a text kind block");const o=io(n,t).text;return d(Ll,o,"no text in block"),o}function Ml(n,t,e){return fe(we(n,t),e).left}function Jg(n,t){const e=z(t);d(Ll,e,"no parent block");const o=we(n,e),r=Em(t),i=o.find(s=>{const l=s.attributes;return l?l.box&&l.id===r:!1});return d(Ll,i,"failed to find box"),i.attributes}const ob=w("get-text-position");function Sr(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ut||d(ob,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=K(r),s=j(r),l=U(s),{offset:c}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const _i=w("insert-text");function Xg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(d(_i,r,"no block data"),d(_i,r.text,"no block text"),ce(r.text)===0)return d(_i,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Jt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function rb(n,t,e){const o=j(t),r=U(o),i=K(t);return Xg(n,r,i,e)}function tp(n,t,e,o,r){const i=j(t),s=U(i),l=K(t),c=rb(n,t,e),a=vl(e,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),we(n,t)}function ep(n,t,e,o){const r=j(t),i=U(r),s=K(t),l=vl(e," ",o);return n.doc.localUpdateBlockText(i,s,l),we(n,t)}function $d(n,t,e,o,r){const i=n.doc.getBlockData(e,o);d(_i,i,"no block data"),d(_i,i.text,"no block text");const s=Xg(n,e,o,r),l=vl(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),we(n,n.getBlockById(i.id))}function jd(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Sr(n);$d(n,t,e,o,r)}const Rl=w("update-composition-text");function np(n){const t=n.selection.range.start;t instanceof Ut||d(Rl,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);d(Rl,H(n,o),"not a text kind block");const r=j(o),i=U(r),s=K(o),l=n.doc.getBlockData(i,s);d(Rl,l,"no block data in doc"),d(Rl,l.text,"no text data in text block");const c=rt(o);gl(n,Ro(o),e,c,l.text)}function op(n){i8(n)}function Tr(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ol=w("delete-block-text");function Hd(n,t,e,o,r){d(Ol,H(n,t),"block is not a text kind block");const i=j(t),s=U(i),l=K(t),c=n.doc.getBlockData(s,l);d(Ol,c,"no block data in doc"),d(Ol,c.text,"no text data in text block");let a=e;me(t,e)||(a=Po(t,a));let u=e+o;d(Ol,u<=Z(n,t),`invalid offset and count: ${e}, ${o}`),me(t,u)||(u=Er(t,u));const f=u-a,m=bg(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const Fd=w("break-text-block");function rp(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Dr(n,t,e,o){d(Fd,H(n,t),`block is not a text kind block: ${it(t)}`),d(Fd,e>=0&&e<=Z(n,t),`invalid offset: ${e}`);const r=j(t),i=U(r),s=K(t),l=o!=null&&o.copyBlockAttributes?rp(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===Z(n,t))){const C=e===0?s:s+1,v={...jn(""),...l,...o==null?void 0:o.newBlockData},y=Lt(n,t.id,0),E=Tr(n,i,C,v,y);return{block:t,newBlock:E}}d(Fd,me(t,e),"not a valid offset");const c=we(n,t),{right:a}=fe(c,e),u=ce(a);u>0&&Hd(n,t,e,u);const f={...jn(a),...l,...o==null?void 0:o.newBlockData},m=Tr(n,i,s+1,f,Lt(n,f.id,0));return{block:t,newBlock:m}}const ib=w("prepare-insert-new-block");function sb(n,t,e){if(t&&e!==void 0&&e!==null){const a=n.getContainerById(t),u=Ot(a);return d(ib,e>=0&&e<=u.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=U(j(r)),e=K(r),!H(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===Z(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const c=Dr(n,r,s).newBlock;return{containerId:t,blockIndex:K(c)}}const lb=w("auto-insert-block");function ip(n,t,e,o,r,i){const s=sb(n,e,o);d(lb,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Tr(n,s.containerId,s.blockIndex,t,r!=null?r:c,i)}const sp=w("range-in-block");function lp(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||vt(n,o),s=r===n||vt(n,r);return!!(i||s)}function cp(n,t){const e=n.doc.toJSON(),o=new Set(Object.values(e.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=gt(t);if(i){for(;i&&!o.has(G(i));)i=gt(i);d(sp,i,"no prev block while deleting a block"),r=Lt(n,i,Z(n,i))}else{const s=ht(t);d(sp,s,"no prev and next block while deleting a block"),r=Lt(n,s,0)}return r}const cb=w("delete-block");function Al(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Al(n,i,e)})}))}function zd(n,t,e){const o=j(t),r=U(o),i=K(t),s=n.doc.getBlockData(r,i);return d(cb,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Vt(n,{anchor:e.start,focus:e.end})),s}function Ud(n,t,e){const o=j(t);Ve(o)===1&&n.insertTextBlock("",U(o),0);let r=e?oo(n,e):null;if(!r){const l=n.selection.range;lp(t,l)?r=cp(n,t):r=l}const i=zd(n,t,r),s=[];return Al(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i}function ab(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Al(n,r,e)}),n.doc.localDeleteChildContainers(e)}function ap(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Al(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Vd=w("merge-text-block");function dp(n,t,e){d(Vd,H(n,t),"only text block can be merged"),d(Vd,H(n,e),"only text block can be merged");const o=io(n,t),r=io(n,e),i=o.text,s=r.text;d(Vd,i&&s,"block data has no text");const l=j(t),c=U(l),a=K(t),u=Z(n,t),f=$d(n,s,c,a,u),m=Lt(n,t,ce(i));return Ud(n,e,m),f}const bn=w("clear-selected-contents");function _l(n,t){d(bn,H(n,t.block),"not a text kind block");const{start:e,end:o}=t;d(bn,e.isSimple(),"not a simple block position"),d(bn,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;d(bn,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function up(n,t,e){const o=U(t),r=Ot(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function db(n,t){const{block:e,start:o,end:r}=t;if(H(n,e)){_l(n,t);return}if(De(e)||o.isSimple()){d(bn,r.isSimple(),"invalid range");const s=j(e),l=K(e),c=n.insertTextBlock("",U(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}d(bn,ct(n,e),"invalid block kind"),d(bn,!o.isSimple()&&!r.isSimple(),"invalid range"),kr(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{up(n,s,{focus:l===0})})}function ub(n){const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(d(bn,e.length>0,"no selected block"),e.length===1){db(n,e[0]);return}const o=e[0],r=o.block,i=j(r);d(bn,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(H(n,r)){_l(n,o);const u=Lt(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),H(n,l)){_l(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(u);return}n.deleteBlock(l),n.selection.setRange(u);return}if(H(n,l)){_l(n,s),e.slice(0,e.length-1).reverse().forEach(u=>n.deleteBlock(u.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Ve(i)){up(n,i,{focus:!0});return}const c=gt(r),a=ht(l);d(bn,c||a,"no prev or next block"),e.forEach(u=>n.deleteBlock(u.block))}function qd(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),ub(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}function hp(n,t,e){const o=j(t),r=U(o),i=K(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),we(n,t)}function fp(n,t,e){const o=n.getBlockText(t),r=oe.diff(o,e);hp(n,t,r)}function Nl(n,t,e){const o=we(n,t),r=typeof e=="string"?Oi(e):e,i=oe.diff(o,r);return hp(n,t,i)}const Ni=w("update-block-data");function Pl(n,t,e,o){const r=j(t),i=U(r),s=K(t),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),u=new Set(Object.keys(e));return a.forEach(m=>{if(!u.has(m)){if(m==="id"||m==="type"||m==="text")return;Ni.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(e).forEach(([m,C])=>{d(Ni,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const v=l[m];if(C==null){v!=null&&(Ni.debug(`delete key: ${m}`),c.delete.push(m));return}v!==C&&(Gs.default(v,C)||m==="text"&&oe.diff(v,C).length===0||(a.has(m)?(Ni.debug(`replace key: ${m}`),c.delete.push(m)):Ni.debug(`insert key: ${m}`),c.insert[m]=C))}),n.doc.localUpdateBlockData(i,s,c,o),io(n,t)}function mp(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Wd(n,t,e){if(!ct(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=ye(n,t).getChildContainers(n,t)[0],i=Kt(r);Wd(n,i,e)}function Ho(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const $l=w("clone-block");function Fo(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(u,f)=>(d($l,e!==f,"invalid child block"),Fo(n,u,e,o)));let i={};const s=new Map,l=Y.default(e);l.children&&(l.children=l.children.map(u=>{const f=N(),m=t.blocks[u];d($l,Array.isArray(m),"invalid child blocks");const C=m.map(L=>Fo(n,t,L,o)),v=Ho(C),{root:y,...E}=v.blocks;return i={...i,...E},i[f]=v.blocks.root,s.set(u,f),f}));const c=Array.from(s.entries()),a=u=>{for(const f of c){const[m,C]=f,v=`${m}/`;if(u.startsWith(v)){const y=u.substring(v.length),E=`${C}/${y}`;return $l.debug(`replace key: ${u} -> ${E}`),E}}return u};return Array.from(Object.entries(l)).forEach(([u,f])=>{const m=a(u);m!==u&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((u,f)=>o.containerIdMap.set(f,u))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Gd(n,t,e,o){const r=t.blocks[e];d($l,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fo(n,t,l,o));return Ho(i)}function Zd(n,t,e){const o=t.blocks.root.map(r=>Fo(n.editorBlocks,t,r,e));return Y.default(Ho(o))}const gp=w("insert-doc");function pp(n,t,e,o,r){if(ct(n,t)){gp.warn("failed to insert doc into a complex block");return}const i=Zd(n,o,r),s=j(t),l=K(t),c=U(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var x,O,A;Object.entries(i.blocks).forEach(([P,V])=>{P!=="root"&&n.doc.localInsertChildContainer(P,V)});const a=i.blocks.root;if(De(t)){n.deleteBlock(t);let P;a.reverse().forEach(V=>{const nt=n.insertBlock(c,l,V);P||(P=nt)}),P&&n.selection.selectBlock(P,Z(n,P));return}if(d(gp,H(n,t),"not a text block"),yt(n,t)){const P=K(t);let V;a.forEach((nt,ot)=>{const ut=n.insertBlock(c,P+ot,nt);ot===a.length-1&&(V=ut)}),V&&n.selection.selectBlock(V,Z(n,V));return}if(a.length===1){const P=a[0];if(Ti(n,P.type)){n.insertTextToBlock(t,e,(x=P.text)!=null?x:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,P);return}const u=e===Z(n,t),f=e===0,m=a[0],C=a[a.length-1];let v;!u&&!f?v=n.breakTextBlock(t,e,{forceInsertAfter:!0}):v=t;const y=f?l:l+1;u?(v=n.insertBlock(c,l+1,C),n.selection.selectBlock(v,Z(n,v))):(n.selection.selectBlock(v,0),Ti(n,C.type)?n.insertTextToBlock(v,0,(O=C.text)!=null?O:[]):n.insertBlock(c,y,C));const E=n.selection.range;let L=y;Ti(n,m.type)?f?(n.insertBlock(c,y,m),L+=1):n.insertTextToBlock(t,e,(A=m.text)!=null?A:[]):(n.insertBlock(c,y,m),L+=1),a.slice(1,a.length-1).reverse().forEach(P=>{n.insertBlock(c,L,P)}),n.selection.setRange(E)}),n.doc.endBatchUpdate()}function Yd(n,t,e,o,r){const i=Zd(n,o,r),s=U(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,u])=>{a!=="root"&&n.doc.localInsertChildContainer(a,u)}),i.blocks.root.reverse().forEach(a=>{const u=n.insertBlock(s,e,a);l.push(u)})}),l}function Cp(n,t,e){const o=Ve(t);Yd(n,t,o,e);for(let r=0;r<o;r++){const i=Kt(t);n.deleteBlock(i)}}const Pi=w("add-text-attribute");function hb(n,t,e,o){const{start:r,end:i}=e;d(Pi,r.blockId===i.blockId&&r.blockId===G(t),"invalid range"),d(Pi,o,"invalid attribute name");const s=n.getBlockText(t),l=xr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function bp(n,t,e,o,r){const{start:i,end:s}=e;d(Pi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range"),d(Pi,o,"invalid attribute name");const l=n.getBlockText(t),c=yl(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function Lr(n,t,e,o,r){const{start:i,end:s}=e;d(Pi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range");const l=n.getBlockText(t),c=Sg(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function vp(n,t,e,o){const r=Ke(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!H(n,s))return;if(yt(n,s)){o(n,G(s),t,e);return}const a=Vt(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?Lr(n,s,a,t,e):(Lr(n,s,a,"color",null),Lr(n,s,a,"backgroundColor",null))})})}function kp(n,t,e){const o=Ke(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!H(n,i))return;if(yt(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,G(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,G(i),"backgroundColor",null);return}const c=Vt(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Lr(n,i,c,"color",null),(t==="clearBackground"||t==="clearAll")&&Lr(n,i,c,"backgroundColor",null)})})}function Qd(n,t){const e=Ke(n,{simpleBlockOnly:!0}).filter(s=>H(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(Z(n,s.block)===0)return t(n,G(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return Lg(l.offset,c.offset-l.offset,a)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,c]=o(s);l===null||r===null?r=null:r=l===r?r:null,c===null||i===null?i=null:i=c===i?i:null}),[r,i])}function yp(n){let t=Gt(n.rootContainer);if(ct(n,t)){const e=yr(n,t);e&&(t=e)}n.selection.selectBlock(t,Z(n,t))}function wp(n){yp(n),n.focus()}const Kd=w("selected-block-to-doc");function Bp(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{Bp(n,i,e)}),e.blocks[o]=Y.default(r)})}function jl(n,t,e={ignoreLockInfo:!0}){const o=kt(n,t.block);if(o.selectionToDoc)return o.selectionToDoc(n,t);const r=Y.default(io(n,t.block));if(!e.ignoreLockInfo&&r.lock&&delete r.lock,H(n,t.block)){const s=t.start,l=t.end;if(d(Kd,r.text,"no block text"),s.offset===l.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:c}=Jt(r.text,s.offset,l.offset-s.offset);return{blocks:{root:[{...r,text:c}]},meta:{},comments:{}}}if(De(t.block))return{blocks:{root:[r]},meta:{},comments:{}};d(Kd,ct(n,t.block),"not complex block"),d(Kd,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return Bp(n,r,i),i}function Jd(n,t,e=!0){const o=$(t,0,"normal"),r=$(t,Z(n,t),"end");return jl(n,{block:t,start:o,end:r},{ignoreLockInfo:e})}const fb=w("block-to-doc");function mb(n,t){d(fb,t.length>0,"invalid params, no blocks");const e=t.map(o=>Jd(n,o));return Ho(e)}function Hl(n){const e=n.selection.range.getSelectedBlocks().map(o=>jl(n,o));return Ho(e)}function Xd(n,t){const e=n.getContainerById(t),i=Ot(e).map(s=>({start:$(s,0,"home"),end:$(s,Z(n,s),"end"),block:s})).map(s=>jl(n,s));return Ho(i)}function Ep(n,t,e){if(t.type==="embed"){const s=t.embedData.src;s&&typeof s=="string"&&e.add(s);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{Ep(n,l,e)})})}function gb(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):Ep(t,r,e)}),Array.from(e)}function tu(n,t){return t.blocks.root.map(r=>Pd(n,r,t)).join(`
25
25
  `)}function eu(n,t){return t.blocks.root.map(r=>Dl(n,r,t)).join(`
26
- `)}function nu(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Do(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function ou(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=gb(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function pb(n,t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData||n.selection.range.isCollapsed())return;const e=Hl(n);ou(n,e);const o=tu(n,e),r=eu(n,e),i=nu(o,e);t.clipboardData.setData("text/html",i),t.clipboardData.setData("text/plain",r),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(e))}function Cb(n){if(n.selection.range.isCollapsed())return;const t=Hl(n);ou(n,t);const e=tu(n,t),o=nu(e,t),r=new Blob([o],{type:"text/html"});rl([{type:"text/html",data:r}])}async function ru(n,t){const e=Jd(n,t,!1);ou(n,e);const o=tu(n,e),r=eu(n,e),i=nu(o,e);return rl([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}const iu=w("editor-input");class bb{constructor(t,e){h(this,"editor");h(this,"composing",!1);h(this,"callbacks");h(this,"inputElement");h(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Si(t)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});h(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});h(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});h(this,"handleCompositionstart",t=>{this.composing=!0,this.callbacks.onCompositionStart(t)});h(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});h(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});h(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}setTimeout(()=>{this.composing||(this.inputElement.value="")})}});h(this,"handleCopy",t=>{pb(this.editor,t)});h(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}iu.debug("on cut")});h(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});this.editor=t,this.callbacks=e;const o=b("input",["editor-input"],t.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const t=this.inputElement;t.removeEventListener("compositionstart",this.handleCompositionstart),t.removeEventListener("compositionend",this.handleCompositionend),t.onkeydown=null,t.oninput=null,t.oncopy=null,t.onpaste=null,t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),St.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(t){this.callbacks.onChanged(t)}handleRemoteChanged(t){this.callbacks.onRemoteChanged(t)}addHandler(t){this.callbacks.addHandler(t)}removeHandler(t){this.callbacks.removeHandler(t)}defaultInsertText(t,e,o,r,i){d(iu,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(iu,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function vb(n){const e=n.rootElement.getBoundingClientRect(),o=window.innerWidth,r=window.innerHeight,i=0-e.top+r/2,s=0-e.left+o/2,l=n.input.inputElement;l.style.left=`${s}px`,l.style.top=`${i}px`}const su=w("editor-caret");class kb{constructor(t){h(this,"editor");h(this,"caretElem");h(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=b("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const t=window.getComputedStyle(this.caretElem);return t.display!=="none"&&t.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const t=this.editor.selection.range.start;if(!(t instanceof Ut))return!1;const e=this.editor.getBlockById(t.blockId);return!!H(this.editor,e)}update(){if(Pf(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",vb(this.editor);return}const{range:e}=this.editor.selection;d(su,e.isCollapsed,"range is not collapsed");const o=e.start;d(su,o instanceof Ut,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(su,H(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Io(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Ae(r,o);const l=this.editor.contentElement.getBoundingClientRect(),c=i.left-l.left,a=i.top-l.top;t.style.left=`${c}px`,t.style.top=`${a}px`,t.style.height=`${i.height}px`;const u=this.editor.input.inputElement;u.style.left=`${c}px`,u.style.top=`${a+i.height-24}px`,St.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`)}}function yb(n){Fm(n),n.selection.range.getSelectedBlocks().forEach(t=>zm(n,t.block,t.start,t.end))}function Ip(n){return _n(n.rootContainer).clientHeight}function wb(n){return n.getFirstBlock().getBoundingClientRect().top}function Bb(n){return n.getLastBlock().getBoundingClientRect().bottom}function lu(n){const t=_n(n.rootContainer);return new DOMRect(t.clientLeft,t.clientTop,t.clientWidth,t.clientHeight)}function Eb(n,t){const e=lu(n),o=n.getBlockById(t.blockId),i=Ze(n,o,t);return So(e,i.x,i.y)&&So(e,i.right,i.bottom)}function Ib(n,t){const e=lu(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function xb(n,t){const e=lu(n),o=t.getBoundingClientRect();return So(e,o.x,o.y)||So(e,o.right,o.bottom)}function Sb(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,u=n.getContainerById(a.childContainerId);xb(n,u)||u.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(De(a)&&Ib(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(Eb(n,o))return;const i=Ze(n,r,o),s=r.getBoundingClientRect(),l=At(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,Bi(c),setTimeout(()=>{c.remove()})}function Tb(n,t){if(t.isCollapsed())return!1;const e=Kt(n.rootContainer),o=Gt(n.rootContainer),{start:r,end:i}=t;return r.blockId===G(e)&&r.offset===0&&i.blockId===G(o)&&i.offset===Z(n,o)}const Fl=w("editor-selection");class Db{constructor(t){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(lp(e,i)){Fl.debug("adjust selection because remote deleted current block");const s=cp(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=G(e);this.caret=new kb(t);const r=$(o,0,"normal");this._range=Vt(t,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=$(t,e,"normal");let i;o&&(i=$(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=Vt(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),lt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!Tb(this.editor,r))&&F(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),yb(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!vr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ze(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){Sb(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=Z(this.editor,e)||d(Fl,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||d(Fl,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&lt(e,"focused")&&(F(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{F(t,"focused"),F(t,"child-focused")})}setBlockFocused(t){if(lt(t,"focused"))return!1;M(t,"focused");let e=j(t);for(;We(e);){const o=z(e);d(Fl,o,"parent block not found"),M(o,"child-focused"),e=j(o)}return!0}}const xp=w("line-offset");function cu(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!H(n,e))return $(e,0,"home");let r=fg(e,t).start;const{next:i}=ml(e,r);return i&&Re(i)&&xi(i)==="br"&&(r+=1),$(e,r,"home")}function au(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===Z(n,e)||!H(n,e))return $(e,0,"end");const o=fg(e,t);return $(e,o.end,"end")}function Lb(n){if(!n.selection.range.focus.isSimple())return;const e=cu(n),o=au(n);!e||!o||n.selection.setSelection(e,o)}const Ne=w("block-text");function Sp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>0&&e<=Z(n,t),`invalid offset: ${e}`);const o=Po(t,e),r=e-o;r===0&&d(Ne,!1,`no text before offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,o,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return yd(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:Xs(l.insert)?"space":"text",offset:o,length:l.insert.length}}function Tp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>=0&&e<Z(n,t),`invalid offset: ${e}`);const r=Er(t,e)-e;r===0&&d(Ne,!1,`no text after offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,e,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return yd(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:Xs(l.insert)?"space":"text",offset:e,length:l.insert.length}}function Dp(n,t,e,o){let r=e;for(;r>0;){const i=Sp(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function Lp(n,t,e,o){const r=Z(n,t);let i=e;for(;i<r;){const s=Tp(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function Mp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Sp(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=Dp(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=Dp(n,t,r,"text");return i?i.offset+i.length:0}function Rp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Tp(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=Lp(n,t,r,"space");if(!s||s.offset===0)return Z(n,t);if(s.charType==="box")return s.offset;r=s.offset}const i=Lp(n,t,r,"text");return i?i.offset:Z(n,t)}const Op=w("word-offset");function du(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"home");if(e.offset===0||!H(n,o)){const s=gt(o);if(!s)return null;const l=$(s,Z(n,s),"end");if(t==="select"&&H(n,s)){const c=Mp(n,s,l.offset);return $(s,c,"normal")}return l}const r=Mp(n,o,e.offset);return $(o,r,"normal")}function uu(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"end");if(e.offset===Z(n,o)||!H(n,o)){const s=ht(o);if(!s)return null;const l=$(s,0,"home");if(t==="select"&&H(n,s)){const c=Rp(n,s,l.offset);return $(s,c,"end")}return l}const r=Rp(n,o,e.offset);return $(o,r,"normal")}function Mb(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!H(n,e))return;const o=du(n,"select"),r=uu(n,"select");!o||!r||n.selection.setSelection(o,r)}const ge=w("adjust-selection-pos");function Ap(n){const t=[];for(;n;){const e=j(n);if(t.unshift(e),Ct(e))return t;const o=z(e);d(ge,o,"child container has not parent container"),n=o}d(ge,!1,"should not come here: getParentContainers")}function _p(n,t){for(;t;){const e=j(t);if(e===n)return t;const o=z(e);d(ge,o,"could not find parent block for a child container"),t=o}d(ge,!1,"no parent block in specified container")}function Rb(n,t){const e=Ap(n),o=Ap(t);d(ge,e.length>0&&o.length>0,"block has not parent container"),d(ge,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=_p(r,n),s=_p(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Np(n,t){let e=z(t);for(d(ge,e,"element is not in a block");e;){const o=j(e);d(ge,We(o),"not a child container");const r=z(o);if(d(ge,r,"child container has not parent block"),r===n)return o;e=r}d(ge,!1,"failed to find parent container in complex block")}function zl(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ut&&e instanceof Ut?{anchor:t,focus:e}:(d(ge,t instanceof Ye&&e instanceof Ye,"both start and end are not simple or complex"),fl(n,o,t,e));const i=j(o),s=j(r);if(i===s)return t instanceof Ye&&(t=$(o,0,"home")),e instanceof Ye&&(e=$(r,Z(n,r),"end")),d(ge,t instanceof Ut,"not valid position type"),d(ge,e instanceof Ut,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ut&&e instanceof Ye){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const y=z(i);if(y&&y===z(v)){const E=bt(y,U(i)),L=bt(y,U(v));return fl(n,y,E,L)}}return null}const l=Js(o,r)>0,{newBlock1:c,newBlock2:a}=Rb(o,r);if(c===a){const v=c,y=Np(v,o),E=Np(v,r);return t=bt(c,U(y)),e=bt(c,U(E)),ge.debug(`select in complex block: ${y.id}, ${E.id}`),fl(n,v,t,e)}let u=l?Z(n,c):0;c===o&&t instanceof Ut&&(u=t.offset);let m=l?0:Z(n,a);return a===r&&e instanceof Ut&&(m=e.offset),t=$(c,u,l?"end":"home"),e=$(a,m,l?"home":"end"),{anchor:t,focus:e}}const Ob=w("range-from-point");function Pp(n,t,e){const o=[0,-12,12];for(let r=0;r<o.length;r++){const i=document.elementsFromPoint(t,e+o[r])[0];if(!i||!n.rootContainer.contains(i))continue;const s=z(i);if(!s||!n.contains(s))continue;const l=kt(n,s).getRangeFromPoint(n,s,t,e+o[r]);if(l)return l}return null}function $p(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Kt(t),c=$(l,0,"home");return new se(n,{anchor:c,focus:c})}const i=Gt(t),s=$(i,Z(n,i),"end");return new se(n,{anchor:s,focus:s})}function Ab(n,t,e){const o=Pp(n,t,e);if(o){if(o instanceof se)return o;d(Ob,o instanceof Qe,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return $p(n,a,t,e)}const r=document.elementsFromPoint(t,e)[0];if(!r)return null;const{children:i}=r,s=Array.from(i).filter(c=>mn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const u=c.getBoundingClientRect(),f=a.getBoundingClientRect();return fn(u,t,e)>fn(f,t,e)?a:c});return $p(n,l,t,e)}class _b{constructor(t){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",t=>{this.mouseDownEvent=t;const e=Ab(this.editor,t.x,t.y);if(e){if(e instanceof Qe)return;const o=this.editor.selection.range;if(t.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,e.focus),this.startPos=e.start}else this.editor.selection.setSelection(e.anchor,e.focus),this.startPos=e.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=Pp(this.editor,t.x,t.y);if(!e)return;const o=zl(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",t=>{this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){Mb(this.editor)}handleTripleClick(t){Lb(this.editor)}}const Nb=w("move-complex-block-position");function Pb(n,t,e){const o=n.getBlockById(t.blockId);d(Nb,ct(n,o),"is not a complex block");const r=ye(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?bt(o,U(s)):null}const $i=w("move-simple-block-position");function jp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[0];return Kt(o)}function Hp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Gt(o)}function Fp(n,t,e){const o=e?jp(n,t):Hp(n,t);return ct(n,o)?Fp(n,o,e):o}function $b(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===0?jp(n,e):pr(e)}function jb(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===1?Hp(n,e):gr(e)}function hu(n){return n==="ArrowLeft"||n==="ArrowUp"}function fu(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);d($i,r,"child container has not parent block"),d($i,ct(n,r),"is not a complex block");const i=ye(n,r).getNextContainer(n,r,o,e);return i?hu(e)?Gt(i):Kt(i):fu(n,r,e)}function Hb(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);if(d($i,r,"child container has not parent block"),hu(e)){const l=gt(r);if(l)return l}else{const l=ht(r);if(l)return l}const i=fu(n,r,e);if(i)return i;let s=r;for(;!Ct(j(s));)s=z(j(s));return hu(e)?gt(s):ht(s)}function Fb(n,t,e){return!ct(n,t)||ye(n,t).enableKeyboardSelect?t:Fp(n,t,e==="ArrowDown"||e==="ArrowRight")}function zb(n,t,e){const o=n.getBlockById(t.blockId),i=kt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?$b(n,t):jb(n,t);if(s||(s=fu(n,o,e),s||(s=Hb(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Ct(j(o)))return null;const l=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(l,0,"home")}return null}if(s=Fb(n,s,e),H(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return k8(n,s,o,t,l);if(e==="ArrowUp")return v8(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?$(s,Z(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?$(s,0,"home"):null}function Ub(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(H(n,r))return o;const i=ht(r);if(i)return $(i,0,"home");if(!Ct(j(r))||n.readonly)return o;const s=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(s,0,"home")}function Vb(n,t,e){const o=n.selection.range;let r;if(o instanceof se)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=Ub(n,t,o):r=zb(n,o.getFocusedPos(),t);else if(r=Pb(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Gt(s);r=$(l,0,"home")}else{const l=Kt(s);r=$(l,Z(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:zl(n,o.anchor,r):null}function so(n,t,e){const o=Vb(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function qb(n){return so(n,"ArrowLeft","move"),!0}function Wb(n){return so(n,"ArrowRight","move"),!0}function Gb(n){return so(n,"ArrowUp","move"),!0}function Zb(n){if(so(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=j(t);if(Ct(e)||Gt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",U(o),Ve(o)),!0}function Yb(n){return so(n,"ArrowDown","select"),!0}function Qb(n){return so(n,"ArrowLeft","select"),!0}function Kb(n){return so(n,"ArrowRight","select"),!0}function Jb(n){return so(n,"ArrowUp","select"),!0}function Xb(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function tv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ev(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function nv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function mu(n,t){if(!ct(n,t))return t;const o=ye(n,t).getChildContainers(n,t)[0],i=Ot(o)[0];return mu(n,i)}function gu(n,t){if(!ct(n,t))return t;const e=ye(n,t).getChildContainers(n,t),o=e[e.length-1],r=Ot(o),i=r[r.length-1];return gu(n,i)}function ov(n){const t=gu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(e),!0}function rv(n){const t=mu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(e),!0}function iv(n){const t=mu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function sv(n){const t=gu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function lv(n){if(!n.selection.range.focus.isSimple())return!1;const e=cu(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function av(n){if(!n.selection.range.focus.isSimple())return!1;const e=cu(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function dv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const zp=w("find-block-position");function uv(n,t,e,o){d(zp,ct(n,t),"is not a complex block");const r=ye(n,t).getChildContainers(n,t);d(zp,r.length>0,"complex block has not any child container");const i=Ze(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=ig(n,t,s,l);return pu(n,c,e,o)}function pu(n,t,e,o){if(ct(n,t))return uv(n,t,e,o);const r=G(t);let i=Number.MAX_SAFE_INTEGER;const s=Ze(n,e,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=$(r,0,"home");const u=Z(n,t);for(let f=0;f<=u;f++){const m=$(r,f,"normal"),C=Ze(n,t,m),v=fn(C,l,c);v<i&&(i=v,a=m)}return a}const Up=w("page-offset");function hv(n,t){const e=Ip(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<wb(n))return n.getFirstBlock();const i=gt(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=gt(s)}return n.getFirstBlock()}function fv(n,t){const e=Ip(n)*.9,o=t.getBoundingClientRect(),r=Bb(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=ht(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=ht(l)}return n.getLastBlock()}function Vp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=hv(n,e);let r;return o===n.getFirstBlock()?r=$(o,0,"home"):r=pu(n,o,e,t),r}function qp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=fv(n,e);let r;return o===n.getLastBlock()?r=$(o,Z(n,o),"end"):r=pu(n,o,e,t),r}function mv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function gv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function pv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);if(!e)return!1;const o=zl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function Cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);if(!e)return!1;const o=zl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const ji=w("select-all");function bv(n,t){const e=t.getEditor(),o=ye(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=G(n);return t.start.blockId===s&&t.start.childContainerId===U(r)&&t.end.blockId===s&&t.end.childContainerId===U(i)}function vv(n,t){d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block");const e=ye(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Vt(n,{anchor:bt(t,U(o)),focus:bt(t,U(r))}))}function Wp(n,t){const e=j(t),o=Ot(e),r=o[0],i=o[o.length-1],s=$(r,0,"home"),l=$(i,Z(n,i),"end");n.selection.setSelection(s,l,{noScroll:!0})}function kv(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&H(n,t)){const r=e.start,i=e.end,s=Z(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return M(n.rootContainer,"select-all"),Wp(n,Kt(n.rootContainer)),!1}return d(ji,!e.isSimple(),"invalid range type"),bv(t,e)?(Wp(n,t),!1):(d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block"),vv(n,t),!0)}function yv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function wv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const Gp=w("delete-text");function Zp(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ut||d(Gp,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(Gp,H(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!me(s,l-e)){const c=Po(s,l);e=l-c}}else if(t==="forward"&&l+e>Z(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function Yp(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const Bv=w("handle-backspace");function Cu(n,t){if(!yt(n,t))return;const e=j(t);Ve(e)!==1&&n.deleteBlock(t)}function Ev(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===0){if(Yp(n,o))return;const r=gt(o);if(r)if(H(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ct(n,r)){Cu(n,o);const i=yr(n,r);i?n.selection.selectBlock(i,Z(n,i)):n.selection.selectBlock(r,0,Z(n,r))}else Cu(n,o),d(Bv,De(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=j(o);if(We(i)){const s=ng(n,i);s&&(Cu(n,o),n.selection.selectBlock(s,Z(n,s)))}}}else Zp(n,"backward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function Iv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===Z(n,o)){const r=ht(o);r&&(H(n,r)?n.mergeTextBlock(o,r,{focus:!0}):yt(n,o)?n.deleteBlock(o,Lt(n,r,0)):n.deleteBlock(r))}else Zp(n,"forward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function xv(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(H(n,e)){if(yt(n,e)&&Yp(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function Sv(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!H(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const Tv=w("input-handler-actions");function Dv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(xv(n),!0))}function Lv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Iv(n),!0))}function Mv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Ev(n),!0))}function Rv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Sv(n),!0))}function Ov(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{const e=n.selection.focusedBlock,o=n.selection.range.start;d(Tv,o.isSimple(),"not simple position"),n.insertTextToBlock(e,o.offset,t)}),!0)}function Av(n){return Cb(n),qd(n),!0}const Ul={ArrowDown:Zb,ArrowUp:Gb,ArrowLeft:qb,ArrowRight:Wb,"Shift+ArrowDown":Yb,"Shift+ArrowUp":Jb,"Shift+ArrowLeft":Qb,"Shift+ArrowRight":Kb,"CtrlOrCmd+ArrowLeft":Xb,"CtrlOrCmd+ArrowRight":tv,"CtrlOrCmd+Shift+ArrowLeft":ev,"CtrlOrCmd+Shift+ArrowRight":nv,"CtrlOrCmd+ArrowUp":rv,"CtrlOrCmd+ArrowDown":ov,"CtrlOrCmd+Shift+ArrowUp":iv,"CtrlOrCmd+Shift+ArrowDown":sv,"CtrlOrCmd+A":kv,Home:av,End:dv,"Shift+Home":lv,"Shift+End":cv,PageUp:mv,PageDown:gv,"Shift+PageUp":pv,"Shift+PageDown":Cv,"CtrlOrCmd+X":Av,"CtrlOrCmd+Z":yv,"CtrlOrCmd+Shift+Z":wv,Enter:Dv,Delete:Lv,Backspace:Mv,"Shift+Enter":Rv,"CtrlOrCmd+Shift+V":Ov};function Qp(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function Kp(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(i.src=l)}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{Kp(n,l,e)})})}function Jp(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):Kp(t,r,e)})}async function _v(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function Nv(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function Pv(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(Nv(n,t)){const s=Array.from(Object.keys(o));r=await _v(n,s),Jp(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&Jp(n,t,i)}async function $v(n,t){await Pv(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Sr(n);n.insertDoc(e,o,t)})}const jv=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function Hv(n){let t;for(const e of jv)if(t=n[e],t)break;return t||null}class Fv{constructor(t){h(this,"editor");h(this,"handlers",[]);this.editor=t}onInsertText(t,e){if(!H(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Sr(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e))}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=Sr(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Sr(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{if(!o)return;for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,t,o))return}const r=Hv(o);if(!!r){await this.pasteDoc(r);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,t,o))return}}})}onFocus(){M(this.editor.rootElement,"active")}onBlur(){F(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t)}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){jd(this.editor,i)}defaultHandleKeydown(t,e){return Qp(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleBeforePasteDoc&&await o.handleBeforePasteDoc(this.editor,t))return}await $v(this.editor,t);for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleAfterPasteDoc&&await o.handleAfterPasteDoc(this.editor,t))return}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function zv(n,t,e){const o=fr(t,e);return o.remove(),o}w("copy-dom-attributes");const Xp=["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 Uv(n,t){for(let l=0;l<Xp.length;l++){const c=Xp[l];t[c]=n[c]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const c=e[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];e.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function t2(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function e2(n,t,e){var a;const o=n.getContainerById(t),r=fr(o,e),i=Ro(r),s=n.doc.getBlockData(t,e),l=kt(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=t2(u);t2(r),f.forEach(C=>r.appendChild(C));const m=cl(u);if(m){const C=cl(r);C&&C.remove(),r.appendChild(m)}Uv(u,r)}Vm(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const Vv=w("transform-selection");function n2(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(Vv,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=oe.transformCursor(i.offset,e,o);l=$(t,a,"normal")}let c=s;if(s.blockId===t){const a=oe.transformCursor(s.offset,e,o);c=$(t,a,"normal")}return Vt(n,{anchor:l,focus:c})}const qv=w("handle-block-text-changed");function Wv(n,t,e,o,r){const i=n.getContainerById(t),s=fr(i,e),l=n.doc.getBlockData(t,e);if(d(qv,l.text,"no block text"),Hm(n,s).setBlockText(n,s,l.text),!r){const c=n2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Gv(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function o2(n,t,e,o){const r=kt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function Zv(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{o2(n,i,o,{child:!0})}),o2(n,r,o,{child:!1})}const Hn=w("editor-doc");class Yv extends vi{constructor(e,o,r){super();h(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}localUpdateBlockText(e,o,r,i){d(Hn,this.editor.isWritable(),"editor is readonly");const s=this.getBlockData(e,o),l=s.text;d(Hn,l,`no text, ${e}, ${o}`);const c=n2(this.editor,s.id,r,!0),a=oe.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(e,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(e,o,r,i){d(Hn,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Gv(s,r));this.localEvents.forEach(a=>a.onBeforeUpdateBlockData(e,s.id,s,l,i));const c=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(oo(this.editor,i)),c}localInsertBlock(e,o,r,i,s){d(Hn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(oo(this.editor,i),s),l}localDeleteBlock(e,o,r){d(Hn,this.editor.isWritable(),"editor is readonly");const i=Y.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(oo(this.editor,r)),s}localDeleteChildContainers(e){return d(Hn,this.editor.isWritable(),"editor is readonly"),e.forEach(o=>{const r=Y.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return d(Hn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Hn.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),Wv(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),e2(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);w7(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){Zv(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);zv(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Hn.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function r2(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 bu=w("undo-action");class Mr{constructor(t,e,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return d(bu,t,"no other action"),!1}combine(t){d(bu,!1,"no other")}setAfterRange(t){this.afterRange&&bu.warn("after range has already set"),this.afterRange=t}}const Qv=w("block-action");class i2 extends Mr{constructor(e,o,r,i,s){super(e,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Y.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(d(Qv,this.blockIndex===K(i),"invalid block index"),zd(e,i,oo(e,o)),!0):!1}insertBlock(e,o){return Tr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Kv extends i2{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class Jv extends i2{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class Xv extends Mr{constructor(e){super(e,U(e.rootContainer),e.selection.range.toDocRange());h(this,"actions",[])}addAction(e){r2(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Mr&&(o.afterRange||o.setAfterRange(e))}}const zo=w("update-block-data-action");class Vl extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(zo,this.blockId===i.id,"invalid block id"),d(zo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Y.default(i),this.afterBlockData=Y.default(s),d(zo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),Pl(e,o,Vl.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),Pl(e,o,Vl.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const vu=w("update-block-text-action");class Hi extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Y.default(i),this.afterRichTextData=Y.default(s),this.type=Hi.calType(i,s)}static calType(e,o){d(vu,e,"no old data"),d(vu,o,"no new data");const i=oe.diff(e,o),s=new Set;let l=!1;const c=u=>Yf(u)?`cjk_${u}`:Gf(u)?"number":Xs(u)?"space":Zf(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Nl(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Nl(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Hi)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){d(vu,e instanceof Hi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class s2 extends Mr{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainer(this.containerId,Y.default(this.blocks)),!0}}class tk extends s2{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class ek extends s2{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Xe=w("undo");class nk{constructor(t){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(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):(r2(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(Xe,!this.currentGroup,"current group already exists"),this.currentGroup=new Xv(this.editor),this.groupCounter=1):(d(Xe,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(Xe,this.currentGroup,"current group not exists"),d(Xe,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Xe.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 Xe.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(oo(this.editor,t.beforeRange))}catch(e){Xe.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(oo(this.editor,e)):Xe.warn("no after range")}catch(e){Xe.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),oe.diff(o,r).length!==0&&this.addAction(new Hi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Vl(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(Xe,e>=0,"invalid block index"),d(Xe,o,"no block data"),this.addAction(new Kv(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Jv(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new tk(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ek(this.editor,t,e)))}}class ok{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class rk{constructor(){h(this,"converters",[]);this.addConverter(new ok)}async fromData(t,e){let o={};for(const r of this.converters){const i=await r.fromData(t,e);i&&(o={...o,...i})}return o}addConverter(t){this.converters.push(t)}}class ik{constructor(t){h(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class _t extends Wt.TypedEmitter{constructor(e){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=z(o);if((!r||!vt(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?G(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&vt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&F(s,"hover"),e&&M(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new _t(e))}getParentTextContentChild(e,o){if(!H(this.editor,e))return null;const r=rt(e);return o.parentElement===r?o:od(o)}}const l2="style-color-",c2="style-bg-color-";class sk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(l2)?i["data-style-color"]=s.substring(l2.length):s.startsWith(c2)?i["data-style-bg-color"]=s.substring(c2.length):s.startsWith("style")&&r.push(s):typeof l=="string"&&s==="link"&&(r.push("link"),i.link=l)}),{classes:r,attributes:i}}renderBlock(t,e,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=t.selection)==null?void 0:l.range)==null?void 0:c.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),_t.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&M(o,"focused"),_t.get(t).hoveringBlockId()===r.id&&M(o,"hover")}}function lk(n){n.editorBlocks.registerBlockClass(Ai),n.editorBlocks.registerBlockClass(eg),n.editorBoxes.registerBoxClass(Fg),n.editorBoxes.registerBoxClass(zg),n.editorInsertions.registerInsertionClass(qg),n.editorBlockRenders.registerRender(new sk)}function ck(n,t){lk(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 a2=w("range-commands");function d2(n,t){n.forEach(e=>{e.source=t,e.children&&d2(e.children,t)})}function u2(n,t,e){const o=G(t);d(a2,o===e.start.blockId,"invalid start range"),d(a2,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);d2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),ct(n,t)&&kr(n,t,e.start,e.end).forEach(l=>{Ot(l).forEach(a=>{const u=Z(n,a),f=Vt(n,{anchor:$(a,0,"home"),focus:$(a,u,"end")}),m=u2(n,a,f);i.push(...m)})}),i}function h2(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Vt(t,{anchor:r.start,focus:r.end});u2(t,r.block,i).forEach(l=>{o.push(l)})}),o}function f2(n,t,e,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,t,e,o,r,{}))return i[G(t)]=c,!0;let a=!1;return ct(n,t)&&kr(n,t,e.start,e.end).forEach(m=>{Ot(m).forEach(v=>{const y=Z(n,v),E=Vt(n,{anchor:$(v,0,"home"),focus:$(v,y,"end")});f2(n,v,E,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function m2(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const c=Vt(o,{anchor:l.start,focus:l.end});f2(o,l.block,c,t,e,r)}),r}const ak=w("command-providers");class g2{constructor(t){h(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return d(ak,e,`no command provider, id=${t}`),e}getCommands(t){return h2(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>m2(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function dk(n,t){const e=j(t),o=U(e),r=K(t);e2(n,o,r)}const uk=w("table-scroll");class p2{constructor(t,e,o,r,i){h(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class hk{constructor(t){h(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){uk.warn(`event has already registered: ${e}`);return}i.push(new p2(this.editor,t,e,o,r))}else{const s=new p2(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const C2=w("update-block-text");function fk(n,t){const e=n.getBoxById(t.id),o=z(e);d(C2,o,"no parent block"),d(C2,H(n,o),"not a text block");const r=n.getBlockText(o),i=Rg(r,"id",t.id,t);fp(n,o,i)}function mk(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function gk(n){return n.readonly?!1:!Ke(n).find(o=>!n.isBlockWritable(o.block))}class pk{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}async getItem(t){return window.localStorage.getItem(this.getKey(t))}async setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}async removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class Ck{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(An(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Fn=w("editor");class bk extends Wt.TypedEmitter{constructor(e,o,r){var i,s,l,c,a,u,f;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Ck);h(this,"dataConverter",new rk);h(this,"editorBlocks",new Km(this));h(this,"editorBoxes",new Vg(this));h(this,"editorInsertions",new Gg(this));h(this,"editorEmbeds",new Xm(this));h(this,"editorDecorators",new Zg(this));h(this,"editorCommandProviders",new g2(this));h(this,"editorBlockRenders",new ik(this));h(this,"blockHooks",[]);h(this,"domEvents",new hk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new Fv(this));h(this,"settingsProvider");h(this,"_readonly",!1);Fn.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(c=r==null?void 0:r.settingsProvider)!=null?c:new pk(this),ck(this,r==null?void 0:r.components),this.blockHooks.push(...(u=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?u:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new nk(this),this.doc=new Yv(this,o,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=Pm(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new bb(this,this.inputHandlers),this.selection=new Db(this),this.selectionHandler=new _b(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),St.isMobile&&M(this.rootElement,"mobile"),St.isSafari&&M(this.rootElement,"safari"),this._readonly&&M(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?M(this.rootElement,"readonly"):F(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:_n(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return d(Fn,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){Fn.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,o){Wd(this,e,o)}isWritable(){return gk(this)}isBlockWritable(e){return mk(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return d(Fn,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),d(Fn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return $m(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,mr(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,nd(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return d(Fn,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return d(Fn,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return fr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return K(o)}return K(e)}getContainerById(e){return Cr(this,e)}getParentContainer(e){return j(e)}reloadBlock(e){dk(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Tr(this,e,o,r,i!=null?i:c,s)}insertEmbed(e,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Ud(this,e,o)}mergeTextBlock(e,o){return dp(this,e,o)}breakTextBlock(e,o,r){return Dr(this,e,o,r).newBlock}getTextPosition(){return Sr(this)}getBlockString(e,o){const r=this.getBlockText(e);return wt(r,o)}getBlockData(e){return io(this,e)}getBoxData(e){return Jg(this,e)}getBlockText(e){return we(this,e)}setBlockText(e,o){fp(this,e,o)}deleteTextFromBlock(e,o,r,i){return Hd(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return tp(this,e,o,r,i)}insertBoxToBlock(e,o,r){return ep(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){pp(this,e,o,r,i)}insertDocAt(e,o,r,i){return Yd(this,e,o,r,i)}deleteChildContainers(e){ap(this,e)}replaceBlockText(e,o){return Nl(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...c}=i;return Pl(this,e,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return mp(this,e,o,r)}updateBoxData(e){fk(this,e)}getSelectedText(){const e=Hl(this);return eu(this,e)}clearSelectedContents(){qd(this)}insertTextBlock(e,o,r,i){const s=jn(e!=null?e:"");return ip(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){op(this);return}o?(this.compositingText="",Wa()||jd(this,e)):(this.compositingText=e,np(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Fi(n,t,e){return new bk(n,t,e)}function vk(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=$a.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const kk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class ql extends Wt.TypedEmitter{constructor(e){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=e&&e.length>0?e:kk}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&Gs.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&xl(r.range)&&Ng(r.range)).forEach(r=>{const i=r.range.anchor.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(xl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=oe.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=oe.transformCursor(a.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xt=w("local-doc");class ku extends vi{constructor(e,o){super();h(this,"doc");h(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[jn("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Y.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);d(Xt,r,`no container data: ${e}`);const i=r[o];return d(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Xt,i.text,"no text for data");const s=oe.apply(i.text,r);return i.text=s,d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return d(Xt,i,`no container data: ${e}`),d(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);d(Xt,r,`no container data: ${e}`),d(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainer(e,o){this.doc.blocks[e]=o,d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!0)})}localDeleteChildContainers(e){Xt.debug(`delete child containers: ${e}`),e.forEach(o=>{d(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){d(Xt,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(Xt,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ql}setDoc(e){this.doc=Y.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}function Uo(n){return Ct(j(n))}class yk{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function yu(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new yk(o)})}const wk=w("remote-cursor");class Bk{constructor(){h(this,"remoteUsers",new ql)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):wk.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 Ek(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function zi(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=Ek(Y.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function lo(n){return n==="root"?"blocks":n}function Rr(n){return n==="blocks"?"root":n}const Ik={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ne.default(n)},apply(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},compose(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},diff(n,t){const e=new ne.default(n),o=new ne.default(t);return e.diff(o).ops},transform(n,t,e){const o=new ne.default(n);return new ne.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new ne.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var Ui=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},co={},wu=xf.default.EventEmitter;co.EventEmitter=wu,co.mixin=xk;function xk(n){for(var t in wu.prototype)n.prototype[t]=wu.prototype[t]}var b2=["info","warn","error"];function v2(){var n={};b2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var Sk=v2;v2.prototype.setMethods=function(n){n=n||{};var t=this;b2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var Tk=Sk,Dk=new Tk,k2=Dk;function Vo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Vo):this.stack=new Error().stack}Vo.prototype=Object.create(Error.prototype),Vo.prototype.constructor=Vo,Vo.prototype.name="ShareDBError",Vo.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 Wl=Vo,Vi={},y2=Lk;function Lk(n,t,e,o){var r=function(s,l,c,a){t(c,s,l,"left"),t(a,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var C=[];if(r(s[m],u,f,C),m++,C.length===1)u=C[0];else if(C.length===0){for(var v=m;v<s.length;v++)o(f,s[v]);u=null;break}else{for(var y=i(s.slice(m),C),E=0;E<y[0].length;E++)o(f,y[0][E]);for(var L=0;L<y[1].length;L++)o(c,y[1][L]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var w2={exports:{}},ao=w2.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||""}},Bu=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Eu=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")},Gl=function(n){for(var t=0;t<n.length;t++)Eu(n[t])};ao.apply=function(n,t){var e;Gl(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=Bu(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var zn=ao._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:Bu(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:Bu(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};ao.compose=function(n,t){Gl(n),Gl(t);for(var e=n.slice(),o=0;o<t.length;o++)zn(e,t[o]);return e},ao.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),zn(t,o)}return t};var Iu=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};ao.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=Iu(n,t[r],o);return n};var Mk=ao._tc=function(n,t,e,o){if(Eu(t),Eu(e),t.i!=null)zn(n,{i:t.i,p:Iu(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(zn(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&zn(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)zn(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)zn(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),a=e.d.slice(s-e.p,l-e.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=Iu(i.p,e),zn(n,i))}return n},Rk=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};ao.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=Rk(n[t]);return n},y2(ao,Mk,Gl,zn);var Zl=function(n){return Object.prototype.toString.call(n)=="[object Array]"},Ok=function(n){return!!n&&n.constructor===Object},tn=function(n){return JSON.parse(JSON.stringify(n))},tt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Un={};tt.registerSubtype=function(n){Un[n.name]=n},tt.create=function(n){return n===void 0?null:tn(n)},tt.invertComponent=function(n){var t={p:n.p};return n.t&&Un[n.t]&&(t.t=n.t,t.o=Un[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},tt.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(tt.invertComponent(t[o]));return e},tt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Zl(n[t].p))throw new Error("Missing path")},tt.checkList=function(n){if(!Zl(n))throw new Error("Referenced element not a list")},tt.checkObj=function(n){if(!Ok(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function qi(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 Wi(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}tt.apply=function(n,t){tt.checkValidOp(t),t=tn(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&qi(r);for(var i=null,s=e,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Un[r.t])s[l]=Un[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)tt.checkList(s),s[l]=r.li;else if(r.li!==void 0)tt.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)tt.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(tt.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)tt.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)tt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},tt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},tt.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=tt.apply(n,r),e(r,n)}return n};var Ak=tt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};tt.append=function(n,t){if(t=tn(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)&&(qi(t),qi(e)),Ak(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Un[t.t]){if(e.o=Un[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),Wi(t),n.push(t);Wi(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)&&(Wi(t),Wi(e)),n.push(t)},tt.compose=function(n,t){tt.checkValidOp(n),tt.checkValidOp(t);for(var e=tn(n),o=0;o<t.length;o++)tt.append(e,t[o]);return e},tt.normalize=function(n){var t=[];n=Zl(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),tt.append(t,o)}return t},tt.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},tt.canOpAffectPath=function(n,t){return tt.commonLengthForOps({p:t},n)!=null},tt.transformComponent=function(n,t,e,o){t=tn(t);var r=tt.commonLengthForOps(e,t),i=tt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var c=tn(e);c.p=c.p.slice(s),t.ld=tt.apply(tn(t.ld),[c])}else if(t.od!==void 0){var c=tn(e);c.p=c.p.slice(s),t.od=tt.apply(tn(t.od),[c])}}if(r!=null){var a=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(qi(t),c=tn(e),qi(c)),c.t&&Un[c.t]){if(t.t&&t.t===c.t){var u=Un[t.t].transform(t.o,c.o,o);if(t.si!=null||t.sd!=null)for(var f=t.p,m=0;m<u.length;m++)t.o=[u[m]],t.p=f.slice(),Wi(t),tt.append(n,t);else(!Zl(u)||u.length>0)&&(t.o=u,tt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(a){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=tn(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&a&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&a&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&a){if(e.p[r]===t.p[r])return n;var f=e.p[r],C=t.p[r],v=t.lm;(f<v||f===v&&C<v)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var C=t.p[r],v=t.lm,y=e.p[r],E=e.lm;if(y!==E)if(C===y)if(o==="left")t.p[r]=E,C===v&&(t.lm=E);else return n;else C>y&&t.p[r]--,C>E?t.p[r]++:C===E&&y>E&&(t.p[r]++,C===v&&t.lm++),(v>y||v===y&&v>C)&&t.lm--,v>E?t.lm++:v===E&&(E>y&&v>C||E<y&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===y&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&a){var C=e.p[r],v=e.lm;f=t.p[r],f>C&&t.p[r]--,f>v&&t.p[r]++}else{var C=e.p[r],v=e.lm;f=t.p[r],f===C?t.p[r]=v:(f>C&&t.p[r]--,(f>v||f===v&&C>v)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&a){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")tt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!a)return n;if(t.oi!==void 0)delete t.od;else return n}}}return tt.append(n,t),n},y2(tt,tt.transformComponent,tt.checkValidOp,tt.append);var _k=w2.exports;tt.registerSubtype(_k);var Nk=tt,Pk={type:Nk};(function(n){n.defaultType=Pk.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)})(Vi);var en={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(en);var B2=Array.isArray,E2=Object.keys,$k=Object.prototype.hasOwnProperty,jk=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=B2(t),r=B2(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var c=t instanceof Date,a=e instanceof Date;if(c!=a)return!1;if(c&&a)return t.getTime()==e.getTime();var u=t instanceof RegExp,f=e instanceof RegExp;if(u!=f)return!1;if(u&&f)return t.toString()==e.toString();var m=E2(t);if(s=m.length,s!==E2(e).length)return!1;for(i=s;i--!==0;)if(!$k.call(e,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},I2=co,Hk=k2,Be=Wl,Yl=Vi,nn=en,Fk=nn.clone,zk=jk,pe=Be.CODES,Uk=st;function st(n,t,e){I2.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}I2.mixin(st),st.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())})},st.prototype._setType=function(n){if(typeof n=="string"&&(n=Yl.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Be(pe.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},st.prototype._setData=function(n){this.data=n,this._dataStateVersion++},st.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Be(pe.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 Be(pe.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?Yl.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},st.prototype.whenNothingPending=function(n){var t=this;nn.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},st.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},st.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},st.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},st.prototype._emitResponseError=function(n,t){if(n&&n.code===pe.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)},st.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){nn.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},st.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){nn.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},st.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===pe.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=Ql(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Ql(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},st.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))},st.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()},st.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);Vk(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},st.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},st.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},st.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=qk([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},st.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;nn.nextTick(function(){n._handleSubscribe()})}}};function Vk(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function qk(n){return n=n.filter(nn.truthy),n.length?function(t){nn.callEach(n,t)}:null}st.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Wk(n){delete n.op,delete n.create,delete n.del}function Ql(n,t){if(n.del)return Wk(t);if(t.del)return new Be(pe.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}st.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Be(pe.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===Yl.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Ql(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},st.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 Be(pe.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>=nn.MAX_SAFE_INTEGER)return this.emit("error",new Be(pe.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)}},st.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Be(pe.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;nn.nextTick(function(){r.flush()})},st.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},st.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},st.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!zk(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}}},st.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},st.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=Yl.defaultType.uri),this.type){var r=new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},st.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Be(pe.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},st.prototype.pause=function(){this.paused=!0},st.prototype.resume=function(){this.paused=!1,this.flush()},st.prototype.toSnapshot=function(){return{v:this.version,data:Fk(this.data),type:this.type.uri}},st.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return Hk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},st.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=Ql(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},st.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=nn.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},st.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=nn.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var qo={};qo.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 x2=co,S2=qo.ACTIONS,Gk=en,Zk=Ce;function Ce(n,t,e,o,r,i,s){x2.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}x2.mixin(Ce),Ce.prototype.hasPending=function(){return!this.ready},Ce.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Ce.prototype.destroy=function(n){this.connection.canSend&&this.action===S2.querySubscribe&&this.connection.send({a:S2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Gk.nextTick(n)},Ce.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ce.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ce.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ce.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var c=t[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},Ce.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Ce.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)},Ce.prototype._handleError=function(n){this.emit("error",n)},Ce.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Ce.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var T2=co,Yk=qo.ACTIONS,Qk=en,D2=vn;function vn(n,t){if(T2.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={}}T2.mixin(vn),vn.prototype.submit=function(n,t){this.value=n,this.send(t)},vn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},vn.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()})},vn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},vn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},vn.prototype._message=function(){return{a:Yk.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},vn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},vn.prototype._callbackOrEmit=function(n,t){if(t)return Qk.nextTick(t,n);n&&this.emit("error",n)};var Kk=en,L2=xu;function xu(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}xu.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},xu.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Kk.nextTick(n)};var Su={exports:{}};(function(n,t){(function(e,o){o(t)})(Ui,function(e){function o(p,k){k=k|0;for(var B=Math.max(p.length-k,0),I=Array(B),D=0;D<B;D++)I[D]=p[k+D];return I}var r=function(p){var k=o(arguments,1);return function(){var B=o(arguments);return p.apply(null,k.concat(B))}},i=function(p){return function(){var k=o(arguments),B=k.pop();p.call(this,k,B)}};function s(p){var k=typeof p;return p!=null&&(k=="object"||k=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(p){setTimeout(p,0)}function u(p){return function(k){var B=o(arguments,1);p(function(){k.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function C(p){return i(function(k,B){var I;try{I=p.apply(this,k)}catch(D){return B(D)}s(I)&&typeof I.then=="function"?I.then(function(D){v(B,null,D)},function(D){v(B,D.message?D:new Error(D))}):B(null,I)})}function v(p,k,B){try{p(k,B)}catch(I){m(y,I)}}function y(p){throw p}var E=typeof Symbol=="function";function L(p){return E&&p[Symbol.toStringTag]==="AsyncFunction"}function x(p){return L(p)?C(p):p}function O(p){return function(k){var B=o(arguments,1),I=i(function(D,T){var R=this;return p(k,function(_,q){x(_).apply(R,D.concat(q))},T)});return B.length?I.apply(this,B):I}}var A=typeof Ui=="object"&&Ui&&Ui.Object===Object&&Ui,P=typeof self=="object"&&self&&self.Object===Object&&self,V=A||P||Function("return this")(),nt=V.Symbol,ot=Object.prototype,ut=ot.hasOwnProperty,dt=ot.toString,Et=nt?nt.toStringTag:void 0;function re(p){var k=ut.call(p,Et),B=p[Et];try{p[Et]=void 0;var I=!0}catch{}var D=dt.call(p);return I&&(k?p[Et]=B:delete p[Et]),D}var Xn=Object.prototype,te=Xn.toString;function Fe(p){return te.call(p)}var bo="[object Null]",cr="[object Undefined]",ar=nt?nt.toStringTag:void 0;function vo(p){return p==null?p===void 0?cr:bo:ar&&ar in Object(p)?re(p):Fe(p)}var ua="[object AsyncFunction]",IP="[object Function]",xP="[object GeneratorFunction]",SP="[object Proxy]";function TP(p){if(!s(p))return!1;var k=vo(p);return k==IP||k==xP||k==ua||k==SP}var DP=9007199254740991;function $3(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=DP}function Ps(p){return p!=null&&$3(p.length)&&!TP(p)}var rf={};function ft(){}function ko(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var sf=typeof Symbol=="function"&&Symbol.iterator,LP=function(p){return sf&&p[sf]&&p[sf]()};function MP(p,k){for(var B=-1,I=Array(p);++B<p;)I[B]=k(B);return I}function ha(p){return p!=null&&typeof p=="object"}var RP="[object Arguments]";function j3(p){return ha(p)&&vo(p)==RP}var H3=Object.prototype,OP=H3.hasOwnProperty,AP=H3.propertyIsEnumerable,_P=j3(function(){return arguments}())?j3:function(p){return ha(p)&&OP.call(p,"callee")&&!AP.call(p,"callee")},un=Array.isArray;function NP(){return!1}var F3=typeof e=="object"&&e&&!e.nodeType&&e,z3=F3&&!0&&n&&!n.nodeType&&n,PP=z3&&z3.exports===F3,U3=PP?V.Buffer:void 0,$P=U3?U3.isBuffer:void 0,jP=$P||NP,HP=9007199254740991,FP=/^(?:0|[1-9]\d*)$/;function zP(p,k){var B=typeof p;return k=k==null?HP:k,!!k&&(B=="number"||B!="symbol"&&FP.test(p))&&p>-1&&p%1==0&&p<k}var UP="[object Arguments]",VP="[object Array]",qP="[object Boolean]",WP="[object Date]",GP="[object Error]",ZP="[object Function]",YP="[object Map]",QP="[object Number]",KP="[object Object]",JP="[object RegExp]",XP="[object Set]",t$="[object String]",e$="[object WeakMap]",n$="[object ArrayBuffer]",o$="[object DataView]",r$="[object Float32Array]",i$="[object Float64Array]",s$="[object Int8Array]",l$="[object Int16Array]",c$="[object Int32Array]",a$="[object Uint8Array]",d$="[object Uint8ClampedArray]",u$="[object Uint16Array]",h$="[object Uint32Array]",It={};It[r$]=It[i$]=It[s$]=It[l$]=It[c$]=It[a$]=It[d$]=It[u$]=It[h$]=!0,It[UP]=It[VP]=It[n$]=It[qP]=It[o$]=It[WP]=It[GP]=It[ZP]=It[YP]=It[QP]=It[KP]=It[JP]=It[XP]=It[t$]=It[e$]=!1;function f$(p){return ha(p)&&$3(p.length)&&!!It[vo(p)]}function m$(p){return function(k){return p(k)}}var V3=typeof e=="object"&&e&&!e.nodeType&&e,$s=V3&&!0&&n&&!n.nodeType&&n,g$=$s&&$s.exports===V3,lf=g$&&A.process,q3=function(){try{var p=$s&&$s.require&&$s.require("util").types;return p||lf&&lf.binding&&lf.binding("util")}catch{}}(),W3=q3&&q3.isTypedArray,p$=W3?m$(W3):f$,C$=Object.prototype,b$=C$.hasOwnProperty;function v$(p,k){var B=un(p),I=!B&&_P(p),D=!B&&!I&&jP(p),T=!B&&!I&&!D&&p$(p),R=B||I||D||T,_=R?MP(p.length,String):[],q=_.length;for(var Q in p)(k||b$.call(p,Q))&&!(R&&(Q=="length"||D&&(Q=="offset"||Q=="parent")||T&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||zP(Q,q)))&&_.push(Q);return _}var k$=Object.prototype;function y$(p){var k=p&&p.constructor,B=typeof k=="function"&&k.prototype||k$;return p===B}function w$(p,k){return function(B){return p(k(B))}}var B$=w$(Object.keys,Object),E$=Object.prototype,I$=E$.hasOwnProperty;function x$(p){if(!y$(p))return B$(p);var k=[];for(var B in Object(p))I$.call(p,B)&&B!="constructor"&&k.push(B);return k}function cf(p){return Ps(p)?v$(p):x$(p)}function S$(p){var k=-1,B=p.length;return function(){return++k<B?{value:p[k],key:k}:null}}function T$(p){var k=-1;return function(){var I=p.next();return I.done?null:(k++,{value:I.value,key:k})}}function D$(p){var k=cf(p),B=-1,I=k.length;return function D(){var T=k[++B];return T==="__proto__"?D():B<I?{value:p[T],key:T}:null}}function L$(p){if(Ps(p))return S$(p);var k=LP(p);return k?T$(k):D$(p)}function Dn(p){return function(){if(p===null)throw new Error("Callback was already called.");var k=p;p=null,k.apply(this,arguments)}}function fa(p){return function(k,B,I){if(I=ko(I||ft),p<=0||!k)return I(null);var D=L$(k),T=!1,R=0,_=!1;function q(W,X){if(R-=1,W)T=!0,I(W);else{if(X===rf||T&&R<=0)return T=!0,I(null);_||Q()}}function Q(){for(_=!0;R<p&&!T;){var W=D();if(W===null){T=!0,R<=0&&I(null);return}R+=1,B(W.value,W.key,Dn(q))}_=!1}Q()}}function dr(p,k,B,I){fa(k)(p,x(B),I)}function ee(p,k){return function(B,I,D){return p(B,k,I,D)}}function M$(p,k,B){B=ko(B||ft);var I=0,D=0,T=p.length;T===0&&B(null);function R(_,q){_?B(_):(++D===T||q===rf)&&B(null)}for(;I<T;I++)k(p[I],I,Dn(R))}var R$=ee(dr,1/0),yo=function(p,k,B){var I=Ps(p)?M$:R$;I(p,x(k),B)};function ai(p){return function(k,B,I){return p(yo,k,x(B),I)}}function G3(p,k,B,I){I=I||ft,k=k||[];var D=[],T=0,R=x(B);p(k,function(_,q,Q){var W=T++;R(_,function(X,xt){D[W]=xt,Q(X)})},function(_){I(_,D)})}var ma=ai(G3),Z3=O(ma);function di(p){return function(k,B,I,D){return p(fa(B),k,x(I),D)}}var ui=di(G3),af=ee(ui,1),Y3=O(af);function ga(p,k){for(var B=-1,I=p==null?0:p.length;++B<I&&k(p[B],B,p)!==!1;);return p}function O$(p){return function(k,B,I){for(var D=-1,T=Object(k),R=I(k),_=R.length;_--;){var q=R[p?_:++D];if(B(T[q],q,T)===!1)break}return k}}var A$=O$();function js(p,k){return p&&A$(p,k,cf)}function _$(p,k,B,I){for(var D=p.length,T=B+(I?1:-1);I?T--:++T<D;)if(k(p[T],T,p))return T;return-1}function N$(p){return p!==p}function P$(p,k,B){for(var I=B-1,D=p.length;++I<D;)if(p[I]===k)return I;return-1}function pa(p,k,B){return k===k?P$(p,k,B):_$(p,N$,B)}var df=function(p,k,B){typeof k=="function"&&(B=k,k=null),B=ko(B||ft);var I=cf(p),D=I.length;if(!D)return B(null);k||(k=D);var T={},R=0,_=!1,q=Object.create(null),Q=[],W=[],X={};js(p,function(Tt,Dt){if(!un(Tt)){xt(Dt,[Tt]),W.push(Dt);return}var Yt=Tt.slice(0,Tt.length-1),to=Yt.length;if(to===0){xt(Dt,Tt),W.push(Dt);return}X[Dt]=to,ga(Yt,function(gi){if(!p[gi])throw new Error("async.auto task `"+Dt+"` has a non-existent dependency `"+gi+"` in "+Yt.join(", "));Ln(gi,function(){to--,to===0&&xt(Dt,Tt)})})}),Dj(),ie();function xt(Tt,Dt){Q.push(function(){Mn(Tt,Dt)})}function ie(){if(Q.length===0&&R===0)return B(null,T);for(;Q.length&&R<k;){var Tt=Q.shift();Tt()}}function Ln(Tt,Dt){var Yt=q[Tt];Yt||(Yt=q[Tt]=[]),Yt.push(Dt)}function ze(Tt){var Dt=q[Tt]||[];ga(Dt,function(Yt){Yt()}),ie()}function Mn(Tt,Dt){if(!_){var Yt=Dn(function(gi,wf){if(R--,arguments.length>2&&(wf=o(arguments,1)),gi){var Bf={};js(T,function(Mj,Rj){Bf[Rj]=Mj}),Bf[Tt]=wf,_=!0,q=Object.create(null),B(gi,Bf)}else T[Tt]=wf,ze(Tt)});R++;var to=x(Dt[Dt.length-1]);Dt.length>1?to(T,Yt):to(Yt)}}function Dj(){for(var Tt,Dt=0;W.length;)Tt=W.pop(),Dt++,ga(Lj(Tt),function(Yt){--X[Yt]===0&&W.push(Yt)});if(Dt!==D)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Lj(Tt){var Dt=[];return js(p,function(Yt,to){un(Yt)&&pa(Yt,Tt,0)>=0&&Dt.push(to)}),Dt}};function hi(p,k){for(var B=-1,I=p==null?0:p.length,D=Array(I);++B<I;)D[B]=k(p[B],B,p);return D}var $$="[object Symbol]";function j$(p){return typeof p=="symbol"||ha(p)&&vo(p)==$$}var H$=1/0,Q3=nt?nt.prototype:void 0,K3=Q3?Q3.toString:void 0;function uf(p){if(typeof p=="string")return p;if(un(p))return hi(p,uf)+"";if(j$(p))return K3?K3.call(p):"";var k=p+"";return k=="0"&&1/p==-H$?"-0":k}function F$(p,k,B){var I=-1,D=p.length;k<0&&(k=-k>D?0:D+k),B=B>D?D:B,B<0&&(B+=D),D=k>B?0:B-k>>>0,k>>>=0;for(var T=Array(D);++I<D;)T[I]=p[I+k];return T}function z$(p,k,B){var I=p.length;return B=B===void 0?I:B,!k&&B>=I?p:F$(p,k,B)}function U$(p,k){for(var B=p.length;B--&&pa(k,p[B],0)>-1;);return B}function V$(p,k){for(var B=-1,I=p.length;++B<I&&pa(k,p[B],0)>-1;);return B}function q$(p){return p.split("")}var W$="\\ud800-\\udfff",G$="\\u0300-\\u036f",Z$="\\ufe20-\\ufe2f",Y$="\\u20d0-\\u20ff",Q$=G$+Z$+Y$,K$="\\ufe0e\\ufe0f",J$="\\u200d",X$=RegExp("["+J$+W$+Q$+K$+"]");function tj(p){return X$.test(p)}var J3="\\ud800-\\udfff",ej="\\u0300-\\u036f",nj="\\ufe20-\\ufe2f",oj="\\u20d0-\\u20ff",rj=ej+nj+oj,ij="\\ufe0e\\ufe0f",sj="["+J3+"]",hf="["+rj+"]",ff="\\ud83c[\\udffb-\\udfff]",lj="(?:"+hf+"|"+ff+")",X3="[^"+J3+"]",tC="(?:\\ud83c[\\udde6-\\uddff]){2}",eC="[\\ud800-\\udbff][\\udc00-\\udfff]",cj="\\u200d",nC=lj+"?",oC="["+ij+"]?",aj="(?:"+cj+"(?:"+[X3,tC,eC].join("|")+")"+oC+nC+")*",dj=oC+nC+aj,uj="(?:"+[X3+hf+"?",hf,tC,eC,sj].join("|")+")",hj=RegExp(ff+"(?="+ff+")|"+uj+dj,"g");function fj(p){return p.match(hj)||[]}function rC(p){return tj(p)?fj(p):q$(p)}function mj(p){return p==null?"":uf(p)}var gj=/^\s+|\s+$/g;function pj(p,k,B){if(p=mj(p),p&&(B||k===void 0))return p.replace(gj,"");if(!p||!(k=uf(k)))return p;var I=rC(p),D=rC(k),T=V$(I,D),R=U$(I,D)+1;return z$(I,T,R).join("")}var Cj=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,bj=/,/,vj=/(=.+)?(\s*)$/,kj=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function yj(p){return p=p.toString().replace(kj,""),p=p.match(Cj)[2].replace(" ",""),p=p?p.split(bj):[],p=p.map(function(k){return pj(k.replace(vj,""))}),p}function iC(p,k){var B={};js(p,function(I,D){var T,R=L(I),_=!R&&I.length===1||R&&I.length===0;if(un(I))T=I.slice(0,-1),I=I[I.length-1],B[D]=T.concat(T.length>0?q:I);else if(_)B[D]=I;else{if(T=yj(I),I.length===0&&!R&&T.length===0)throw new Error("autoInject task functions require explicit parameters.");R||T.pop(),B[D]=T.concat(q)}function q(Q,W){var X=hi(T,function(xt){return Q[xt]});X.push(W),x(I).apply(null,X)}}),df(B,k)}function hn(){this.head=this.tail=null,this.length=0}function sC(p,k){p.length=1,p.head=p.tail=k}hn.prototype.removeLink=function(p){return p.prev?p.prev.next=p.next:this.head=p.next,p.next?p.next.prev=p.prev:this.tail=p.prev,p.prev=p.next=null,this.length-=1,p},hn.prototype.empty=function(){for(;this.head;)this.shift();return this},hn.prototype.insertAfter=function(p,k){k.prev=p,k.next=p.next,p.next?p.next.prev=k:this.tail=k,p.next=k,this.length+=1},hn.prototype.insertBefore=function(p,k){k.prev=p.prev,k.next=p,p.prev?p.prev.next=k:this.head=k,p.prev=k,this.length+=1},hn.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):sC(this,p)},hn.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):sC(this,p)},hn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},hn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},hn.prototype.toArray=function(){for(var p=Array(this.length),k=this.head,B=0;B<this.length;B++)p[B]=k.data,k=k.next;return p},hn.prototype.remove=function(p){for(var k=this.head;k;){var B=k.next;p(k)&&this.removeLink(k),k=B}return this};function lC(p,k,B){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var I=x(p),D=0,T=[],R=!1;function _(X,xt,ie){if(ie!=null&&typeof ie!="function")throw new Error("task callback must be a function");if(W.started=!0,un(X)||(X=[X]),X.length===0&&W.idle())return m(function(){W.drain()});for(var Ln=0,ze=X.length;Ln<ze;Ln++){var Mn={data:X[Ln],callback:ie||ft};xt?W._tasks.unshift(Mn):W._tasks.push(Mn)}R||(R=!0,m(function(){R=!1,W.process()}))}function q(X){return function(xt){D-=1;for(var ie=0,Ln=X.length;ie<Ln;ie++){var ze=X[ie],Mn=pa(T,ze,0);Mn===0?T.shift():Mn>0&&T.splice(Mn,1),ze.callback.apply(ze,arguments),xt!=null&&W.error(xt,ze.data)}D<=W.concurrency-W.buffer&&W.unsaturated(),W.idle()&&W.drain(),W.process()}}var Q=!1,W={_tasks:new hn,concurrency:k,payload:B,saturated:ft,unsaturated:ft,buffer:k/4,empty:ft,drain:ft,error:ft,started:!1,paused:!1,push:function(X,xt){_(X,!1,xt)},kill:function(){W.drain=ft,W._tasks.empty()},unshift:function(X,xt){_(X,!0,xt)},remove:function(X){W._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!W.paused&&D<W.concurrency&&W._tasks.length;){var X=[],xt=[],ie=W._tasks.length;W.payload&&(ie=Math.min(ie,W.payload));for(var Ln=0;Ln<ie;Ln++){var ze=W._tasks.shift();X.push(ze),T.push(ze),xt.push(ze.data)}D+=1,W._tasks.length===0&&W.empty(),D===W.concurrency&&W.saturated();var Mn=Dn(q(X));I(xt,Mn)}Q=!1}},length:function(){return W._tasks.length},running:function(){return D},workersList:function(){return T},idle:function(){return W._tasks.length+D===0},pause:function(){W.paused=!0},resume:function(){W.paused!==!1&&(W.paused=!1,m(W.process))}};return W}function cC(p,k){return lC(p,1,k)}var fi=ee(dr,1);function wo(p,k,B,I){I=ko(I||ft);var D=x(B);fi(p,function(T,R,_){D(k,T,function(q,Q){k=Q,_(q)})},function(T){I(T,k)})}function mf(){var p=hi(arguments,x);return function(){var k=o(arguments),B=this,I=k[k.length-1];typeof I=="function"?k.pop():I=ft,wo(p,k,function(D,T,R){T.apply(B,D.concat(function(_){var q=o(arguments,1);R(_,q)}))},function(D,T){I.apply(B,[D].concat(T))})}}var aC=function(){return mf.apply(null,o(arguments).reverse())},wj=Array.prototype.concat,Ca=function(p,k,B,I){I=I||ft;var D=x(B);ui(p,k,function(T,R){D(T,function(_){return _?R(_):R(null,o(arguments,1))})},function(T,R){for(var _=[],q=0;q<R.length;q++)R[q]&&(_=wj.apply(_,R[q]));return I(T,_)})},dC=ee(Ca,1/0),uC=ee(Ca,1),hC=function(){var p=o(arguments),k=[null].concat(p);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Hs(p){return p}function mi(p,k){return function(B,I,D,T){T=T||ft;var R=!1,_;B(I,function(q,Q,W){D(q,function(X,xt){X?W(X):p(xt)&&!_?(R=!0,_=k(!0,q),W(null,rf)):W()})},function(q){q?T(q):T(null,R?_:k(!1))})}}function fC(p,k){return k}var ba=ai(mi(Hs,fC)),Fs=di(mi(Hs,fC)),va=ee(Fs,1);function mC(p){return function(k){var B=o(arguments,1);B.push(function(I){var D=o(arguments,1);typeof console=="object"&&(I?console.error&&console.error(I):console[p]&&ga(D,function(T){console[p](T)}))}),x(k).apply(null,B)}}var gC=mC("dir");function pC(p,k,B){B=Dn(B||ft);var I=x(p),D=x(k);function T(_){if(_)return B(_);var q=o(arguments,1);q.push(R),D.apply(this,q)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}R(null,!0)}function gf(p,k,B){B=Dn(B||ft);var I=x(p),D=function(T){if(T)return B(T);var R=o(arguments,1);if(k.apply(this,R))return I(D);B.apply(null,[null].concat(R))};I(D)}function CC(p,k,B){gf(p,function(){return!k.apply(this,arguments)},B)}function bC(p,k,B){B=Dn(B||ft);var I=x(k),D=x(p);function T(_){if(_)return B(_);D(R)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}D(R)}function vC(p){return function(k,B,I){return p(k,I)}}function ka(p,k,B){yo(p,vC(x(k)),B)}function zs(p,k,B,I){fa(k)(p,vC(x(B)),I)}var Us=ee(zs,1);function pf(p){return L(p)?p:i(function(k,B){var I=!0;k.push(function(){var D=arguments;I?m(function(){B.apply(null,D)}):B.apply(null,D)}),p.apply(this,k),I=!1})}function ya(p){return!p}var wa=ai(mi(ya,ya)),Vs=di(mi(ya,ya)),Ba=ee(Vs,1);function kC(p){return function(k){return k==null?void 0:k[p]}}function Bj(p,k,B,I){var D=new Array(k.length);p(k,function(T,R,_){B(T,function(q,Q){D[R]=!!Q,_(q)})},function(T){if(T)return I(T);for(var R=[],_=0;_<k.length;_++)D[_]&&R.push(k[_]);I(null,R)})}function Ej(p,k,B,I){var D=[];p(k,function(T,R,_){B(T,function(q,Q){q?_(q):(Q&&D.push({index:R,value:T}),_())})},function(T){T?I(T):I(null,hi(D.sort(function(R,_){return R.index-_.index}),kC("value")))})}function Cf(p,k,B,I){var D=Ps(k)?Bj:Ej;D(p,k,x(B),I||ft)}var Ea=ai(Cf),qs=di(Cf),Ia=ee(qs,1);function yC(p,k){var B=Dn(k||ft),I=x(pf(p));function D(T){if(T)return B(T);I(D)}D()}var xa=function(p,k,B,I){I=I||ft;var D=x(B);ui(p,k,function(T,R){D(T,function(_,q){return _?R(_):R(null,{key:q,val:T})})},function(T,R){for(var _={},q=Object.prototype.hasOwnProperty,Q=0;Q<R.length;Q++)if(R[Q]){var W=R[Q].key,X=R[Q].val;q.call(_,W)?_[W].push(X):_[W]=[X]}return I(T,_)})},wC=ee(xa,1/0),BC=ee(xa,1),EC=mC("log");function Sa(p,k,B,I){I=ko(I||ft);var D={},T=x(B);dr(p,k,function(R,_,q){T(R,_,function(Q,W){if(Q)return q(Q);D[_]=W,q()})},function(R){I(R,D)})}var IC=ee(Sa,1/0),xC=ee(Sa,1);function SC(p,k){return k in p}function TC(p,k){var B=Object.create(null),I=Object.create(null);k=k||Hs;var D=x(p),T=i(function(_,q){var Q=k.apply(null,_);SC(B,Q)?m(function(){q.apply(null,B[Q])}):SC(I,Q)?I[Q].push(q):(I[Q]=[q],D.apply(null,_.concat(function(){var W=o(arguments);B[Q]=W;var X=I[Q];delete I[Q];for(var xt=0,ie=X.length;xt<ie;xt++)X[xt].apply(null,W)})))});return T.memo=B,T.unmemoized=p,T}var Ta;c?Ta=process.nextTick:l?Ta=setImmediate:Ta=a;var DC=u(Ta);function bf(p,k,B){B=B||ft;var I=Ps(k)?[]:{};p(k,function(D,T,R){x(D)(function(_,q){arguments.length>2&&(q=o(arguments,1)),I[T]=q,R(_)})},function(D){B(D,I)})}function LC(p,k){bf(yo,p,k)}function MC(p,k,B){bf(fa(k),p,B)}var vf=function(p,k){var B=x(p);return lC(function(I,D){B(I[0],D)},k,1)},RC=function(p,k){var B=vf(p,k);return B.push=function(I,D,T){if(T==null&&(T=ft),typeof T!="function")throw new Error("task callback must be a function");if(B.started=!0,un(I)||(I=[I]),I.length===0)return m(function(){B.drain()});D=D||0;for(var R=B._tasks.head;R&&D>=R.priority;)R=R.next;for(var _=0,q=I.length;_<q;_++){var Q={data:I[_],priority:D,callback:T};R?B._tasks.insertBefore(R,Q):B._tasks.push(Q)}m(B.process)},delete B.unshift,B};function OC(p,k){if(k=ko(k||ft),!un(p))return k(new TypeError("First argument to race must be an array of functions"));if(!p.length)return k();for(var B=0,I=p.length;B<I;B++)x(p[B])(k)}function Da(p,k,B,I){var D=o(p).reverse();wo(D,k,B,I)}function La(p){var k=x(p);return i(function(I,D){return I.push(function(R,_){if(R)D(null,{error:R});else{var q;arguments.length<=2?q=_:q=o(arguments,1),D(null,{value:q})}}),k.apply(this,I)})}function AC(p){var k;return un(p)?k=hi(p,La):(k={},js(p,function(B,I){k[I]=La.call(this,B)})),k}function _C(p,k,B,I){Cf(p,k,function(D,T){B(D,function(R,_){T(R,!_)})},I)}var NC=ai(_C),kf=di(_C),PC=ee(kf,1);function $C(p){return function(){return p}}function Ma(p,k,B){var I=5,D=0,T={times:I,intervalFunc:$C(D)};function R(W,X){if(typeof X=="object")W.times=+X.times||I,W.intervalFunc=typeof X.interval=="function"?X.interval:$C(+X.interval||D),W.errorFilter=X.errorFilter;else if(typeof X=="number"||typeof X=="string")W.times=+X||I;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof p=="function"?(B=k||ft,k=p):(R(T,p),B=B||ft),typeof k!="function")throw new Error("Invalid arguments for async.retry");var _=x(k),q=1;function Q(){_(function(W){W&&q++<T.times&&(typeof T.errorFilter!="function"||T.errorFilter(W))?setTimeout(Q,T.intervalFunc(q)):B.apply(null,arguments)})}Q()}var jC=function(p,k){k||(k=p,p=null);var B=x(k);return i(function(I,D){function T(R){B.apply(null,I.concat(R))}p?Ma(p,T,D):Ma(T,D)})};function HC(p,k){bf(fi,p,k)}var Ra=ai(mi(Boolean,Hs)),Ws=di(mi(Boolean,Hs)),Oa=ee(Ws,1);function FC(p,k,B){var I=x(k);ma(p,function(T,R){I(T,function(_,q){if(_)return R(_);R(null,{value:T,criteria:q})})},function(T,R){if(T)return B(T);B(null,hi(R.sort(D),kC("value")))});function D(T,R){var _=T.criteria,q=R.criteria;return _<q?-1:_>q?1:0}}function zC(p,k,B){var I=x(p);return i(function(D,T){var R=!1,_;function q(){var Q=p.name||"anonymous",W=new Error('Callback function "'+Q+'" timed out.');W.code="ETIMEDOUT",B&&(W.info=B),R=!0,T(W)}D.push(function(){R||(T.apply(null,arguments),clearTimeout(_))}),_=setTimeout(q,k),I.apply(null,D)})}var Ij=Math.ceil,xj=Math.max;function Sj(p,k,B,I){for(var D=-1,T=xj(Ij((k-p)/(B||1)),0),R=Array(T);T--;)R[I?T:++D]=p,p+=B;return R}function Aa(p,k,B,I){var D=x(B);ui(Sj(0,p,1),k,D,I)}var UC=ee(Aa,1/0),VC=ee(Aa,1);function qC(p,k,B,I){arguments.length<=3&&(I=B,B=k,k=un(p)?[]:{}),I=ko(I||ft);var D=x(B);yo(p,function(T,R,_){D(k,T,R,_)},function(T){I(T,k)})}function WC(p,k){var B=null,I;k=k||ft,Us(p,function(D,T){x(D)(function(R,_){arguments.length>2?I=o(arguments,1):I=_,B=R,T(!R)})},function(){k(B,I)})}function GC(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function yf(p,k,B){B=Dn(B||ft);var I=x(k);if(!p())return B(null);var D=function(T){if(T)return B(T);if(p())return I(D);var R=o(arguments,1);B.apply(null,[null].concat(R))};I(D)}function ZC(p,k,B){yf(function(){return!p.apply(this,arguments)},k,B)}var YC=function(p,k){if(k=ko(k||ft),!un(p))return k(new Error("First argument to waterfall must be an array of functions"));if(!p.length)return k();var B=0;function I(T){var R=x(p[B++]);T.push(Dn(D)),R.apply(null,T)}function D(T){if(T||B===p.length)return k.apply(null,arguments);I(o(arguments,1))}I([])},Tj={apply:r,applyEach:Z3,applyEachSeries:Y3,asyncify:C,auto:df,autoInject:iC,cargo:cC,compose:aC,concat:dC,concatLimit:Ca,concatSeries:uC,constant:hC,detect:ba,detectLimit:Fs,detectSeries:va,dir:gC,doDuring:pC,doUntil:CC,doWhilst:gf,during:bC,each:ka,eachLimit:zs,eachOf:yo,eachOfLimit:dr,eachOfSeries:fi,eachSeries:Us,ensureAsync:pf,every:wa,everyLimit:Vs,everySeries:Ba,filter:Ea,filterLimit:qs,filterSeries:Ia,forever:yC,groupBy:wC,groupByLimit:xa,groupBySeries:BC,log:EC,map:ma,mapLimit:ui,mapSeries:af,mapValues:IC,mapValuesLimit:Sa,mapValuesSeries:xC,memoize:TC,nextTick:DC,parallel:LC,parallelLimit:MC,priorityQueue:RC,queue:vf,race:OC,reduce:wo,reduceRight:Da,reflect:La,reflectAll:AC,reject:NC,rejectLimit:kf,rejectSeries:PC,retry:Ma,retryable:jC,seq:mf,series:HC,setImmediate:m,some:Ra,someLimit:Ws,someSeries:Oa,sortBy:FC,timeout:zC,times:UC,timesLimit:Aa,timesSeries:VC,transform:qC,tryEach:WC,unmemoize:GC,until:ZC,waterfall:YC,whilst:yf,all:wa,allLimit:Vs,allSeries:Ba,any:Ra,anyLimit:Ws,anySeries:Oa,find:ba,findLimit:Fs,findSeries:va,forEach:ka,forEachSeries:Us,forEachLimit:zs,forEachOf:yo,forEachOfSeries:fi,forEachOfLimit:dr,inject:wo,foldl:wo,foldr:Da,select:Ea,selectLimit:qs,selectSeries:Ia,wrapSync:C};e.default=Tj,e.apply=r,e.applyEach=Z3,e.applyEachSeries=Y3,e.asyncify=C,e.auto=df,e.autoInject=iC,e.cargo=cC,e.compose=aC,e.concat=dC,e.concatLimit=Ca,e.concatSeries=uC,e.constant=hC,e.detect=ba,e.detectLimit=Fs,e.detectSeries=va,e.dir=gC,e.doDuring=pC,e.doUntil=CC,e.doWhilst=gf,e.during=bC,e.each=ka,e.eachLimit=zs,e.eachOf=yo,e.eachOfLimit=dr,e.eachOfSeries=fi,e.eachSeries=Us,e.ensureAsync=pf,e.every=wa,e.everyLimit=Vs,e.everySeries=Ba,e.filter=Ea,e.filterLimit=qs,e.filterSeries=Ia,e.forever=yC,e.groupBy=wC,e.groupByLimit=xa,e.groupBySeries=BC,e.log=EC,e.map=ma,e.mapLimit=ui,e.mapSeries=af,e.mapValues=IC,e.mapValuesLimit=Sa,e.mapValuesSeries=xC,e.memoize=TC,e.nextTick=DC,e.parallel=LC,e.parallelLimit=MC,e.priorityQueue=RC,e.queue=vf,e.race=OC,e.reduce=wo,e.reduceRight=Da,e.reflect=La,e.reflectAll=AC,e.reject=NC,e.rejectLimit=kf,e.rejectSeries=PC,e.retry=Ma,e.retryable=jC,e.seq=mf,e.series=HC,e.setImmediate=m,e.some=Ra,e.someLimit=Ws,e.someSeries=Oa,e.sortBy=FC,e.timeout=zC,e.times=UC,e.timesLimit=Aa,e.timesSeries=VC,e.transform=qC,e.tryEach=WC,e.unmemoize=GC,e.until=ZC,e.waterfall=YC,e.whilst=yf,e.all=wa,e.allLimit=Vs,e.allSeries=Ba,e.any=Ra,e.anyLimit=Ws,e.anySeries=Oa,e.find=ba,e.findLimit=Fs,e.findSeries=va,e.forEach=ka,e.forEachSeries=Us,e.forEachLimit=zs,e.forEachOf=yo,e.forEachOfSeries=fi,e.forEachOfLimit=dr,e.inject=wo,e.foldl=wo,e.foldr=Da,e.select=Ea,e.selectLimit=qs,e.selectSeries=Ia,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(Su,Su.exports);var M2={exports:{}},Tu=M2.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var c=parseInt(i,t);return c!==1/0&&c>=Math.pow(2,n)?Tu(n,t):i};Tu.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Tu(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var R2=co,Jk=D2,Xk=L2,Kl=en,Du=Su.exports,ty=M2.exports,O2=qo.ACTIONS,A2=Pt;function Pt(n,t){if(R2.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}R2.mixin(Pt),Pt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Pt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Pt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||ty();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Pt.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);Du.parallel([function(i){Du.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Du.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Pt.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?O2.presenceSubscribe:O2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Pt.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._receiveUpdate=function(n,t){var e=Kl.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Kl.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Pt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Pt.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()}},Pt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Pt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Pt.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Pt.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Pt.prototype._callbackOrEmit=function(n,t){if(t)return Kl.nextTick(t,n);n&&this.emit("error",n)},Pt.prototype._createLocalPresence=function(n){return new Jk(this,n)},Pt.prototype._createRemotePresence=function(n){return new Xk(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=Kl.callEach(n,t);!e&&t&&this.emit("error",t)};var Gi=D2,_2=Wl,ey=en,N2=_2.CODES,ny=on;function on(n,t){Gi.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()}on.prototype=Object.create(Gi.prototype),on.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:N2.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,Gi.prototype.submit.call(this,n,t)},on.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),Gi.prototype.destroy.call(this,n)},on.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={})})}},on.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)},on.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},on.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},on.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},on.prototype._message=function(){var n=Gi.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},on.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!ey.supportsPresence(o))throw new _2(N2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var P2={};(function(n){var t=Vi,e=Wl,o=en,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=t.map[c];if(a==null||typeof a!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=t.map[a.type];if(!u)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=t.map[l.type];if(!a)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new e(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=t.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var C=m.p,v=u,y=0;y<C.length;y++){var E=C[y];Object.prototype.toString.call(v)=="[object Array]"?C[y]=+E:v.constructor===Object&&(C[y]=E.toString()),v=v[E]}f<a.length-1&&(u=t.defaultType.apply(u,[m]))}}}}})(P2);var Zi=L2,oy=P2,ry=Pe;function Pe(n,t){Zi.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()}Pe.prototype=Object.create(Zi.prototype),Pe.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},Pe.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),Zi.prototype.destroy.call(this,n)},Pe.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)},Pe.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))}})}},Pe.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Zi.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Zi.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},Pe.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)}},Pe.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++):oy.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},Pe.prototype._startCachingOps=function(){this._opCache=[]},Pe.prototype._stopCachingOps=function(){this._opCache=null},Pe.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var $2=A2,iy=ny,sy=ry;function Or(n,t,e){var o=Or.channel(t,e);$2.call(this,n,o),this.collection=t,this.id=e}var ly=Or;Or.prototype=Object.create($2.prototype),Or.channel=function(n,t){return n+"."+t},Or.prototype._createLocalPresence=function(n){return new iy(this,n)},Or.prototype._createRemotePresence=function(n){return new sy(this,n)};var cy=ay;function ay(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var dy=cy,j2=co,H2=Yi;function Yi(n,t,e,o,r){if(j2.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}j2.mixin(Yi),Yi.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Yi.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Yi.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new dy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var F2=H2,uy=en,hy=qo.ACTIONS,fy=Lu;function Lu(n,t,e,o,r,i){if(F2.call(this,n,t,e,o,i),!uy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}Lu.prototype=Object.create(F2.prototype),Lu.prototype._message=function(){return{a:hy.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var z2=H2,my=en,gy=qo.ACTIONS,py=Mu;function Mu(n,t,e,o,r,i){if(z2.call(this,n,t,e,o,i),!my.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Mu.prototype=Object.create(z2.prototype),Mu.prototype._message=function(){return{a:gy.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Cy=Uk,by=Zk,vy=A2,U2=ly,ky=fy,yy=py,V2=co,Ar=Wl,pt=qo.ACTIONS,q2=Vi,rn=en,Qi=k2,Ki=Ar.CODES;function W2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var wy=J;function J(n){V2.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=W2(n),this.bindToSocket(n)}V2.mixin(J),J.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=W2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Qi.warn("Failed to parse message",o);return}e.debug&&Qi.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){rn.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},J.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=G2(n.error,n),delete n.error),n.a){case pt.initLegacy:return this._handleLegacyInit(n);case pt.handshake:return this._handleHandshake(t,n);case pt.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case pt.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case pt.queryUnsubscribe:return;case pt.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 pt.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case pt.bulkSubscribe:case pt.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case pt.snapshotFetch:case pt.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case pt.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case pt.subscribe:case pt.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case pt.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case pt.presence:return this._handlePresence(t,n);case pt.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case pt.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case pt.presenceRequest:return this._handlePresenceRequest(t,n);case pt.pingPong:return this._handlePingPong(t);default:Qi.warn("Ignoring unrecognized message",n)}};function G2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}J.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](G2(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Qi.error("Invalid bulk message",t)},J.prototype._reset=function(){this.agent=null},J.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 Ar(Ki.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},J.prototype.startBulk=function(){this.bulk||(this.bulk={})},J.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},J.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var c=e[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var a=r[s];this.send({a:n,c:t,d:s,v:a})}else i&&this.send({a:"b"+n,c:t,b:r})}},J.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},J.prototype.sendFetch=function(n){return this._sendActions(pt.fetch,n,n.version)},J.prototype.sendSubscribe=function(n){return this._sendActions(pt.subscribe,n,n.version)},J.prototype.sendUnsubscribe=function(n){return this._sendActions(pt.unsubscribe,n)},J.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:pt.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)},J.prototype.send=function(n){this.debug&&Qi.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},J.prototype.ping=function(){if(!this.canSend)throw new Ar(Ki.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:pt.pingPong};this.send(n)},J.prototype.close=function(){this.socket.close()},J.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},J.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new Cy(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},J.prototype._destroyDoc=function(n){!n._wantsDestroy||(rn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},J.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},J.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new by(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},J.prototype._destroyQuery=function(n){delete this.queries[n.id]},J.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(pt.queryFetch,n,t,e,o)},J.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(pt.querySubscribe,n,t,e,o)},J.prototype.hasPending=function(){return!!(this._firstDoc(Jl)||this._firstQuery(Jl)||this._firstSnapshotRequest())};function Jl(n){return n.hasPending()}J.prototype.hasWritePending=function(){return!!this._firstDoc(By)};function By(n){return n.hasWritePending()}J.prototype.whenNothingPending=function(n){var t=this._firstDoc(Jl);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Jl);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}rn.nextTick(n)},J.prototype._nothingPendingRetry=function(n){var t=this;return function(){rn.nextTick(function(){t.whenNothingPending(n)})}},J.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},J.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},J.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},J.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new ky(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new yy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},J.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},J.prototype._initializeHandshake=function(){this.send({a:pt.handshake,id:this.id})},J.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},J.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},J.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Ar(Ki.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(q2.map[n.type]!==q2.defaultType)return this.emit("error",new Ar(Ki.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Ar(Ki.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},J.prototype.getPresence=function(n){var t=this,e=rn.digOrCreate(this._presences,n,function(){return new vy(t,n)});return e._wantsDestroy=!1,e},J.prototype.getDocPresence=function(n,t){var e=U2.channel(n,t),o=this,r=rn.digOrCreate(this._presences,e,function(){return new U2(o,n,t)});return r._wantsDestroy=!1,r},J.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},J.prototype._addPresence=function(n){rn.digOrCreate(this._presences,n.channel,function(){return n})},J.prototype._handlePresenceSubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},J.prototype._handlePresenceUnsubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},J.prototype._handlePresence=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},J.prototype._handlePresenceRequest=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Z2=wy,Ey=Vi;const Xl={err:1001,msg:"user auth error",name:"AuthError"},Iy={err:1002,msg:"you don't have required permission",name:"PermissionError"},Ru={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ji={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},xy={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Sy={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Xi="x-live-editor-token",tc="x-live-editor-base-url",ae=w("auth-connection");function Ty(n){try{n()}catch(t){ae.error(t)}}class Dy{constructor(t,e){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new Ef.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Do(this.getBaseURL())}async auth(t){d(ae,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Xi]:t.token,[tc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[tc]:Do(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new E9.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Z2.prototype),d(ae,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},Z2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,ae.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){ae.error(t),setTimeout(()=>this.handleAuthError(),0)}}else ae.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Xl.msg);t.code=Xl.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ji.msg);t.code=Ji.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===Xl.err)ae.warn("auth error"),this.handleAuthError();else if(o===Ru.err)ae.warn(Ru.msg),this.emitMaxUsersError();else if(o===Ji.err){ae.warn(Ji.msg);try{this.emitRequestReloadError()}catch(r){ae.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else ae.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return d(ae,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(d(ae,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){d(ae,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){d(ae,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),Ty(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}w("utils/file");function Ly(){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}Ly();async function My(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new I9.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return Do(i)}const kn=w("sharedb-doc/client");class Ry{constructor(t,e,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(kn,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),kn.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;Ey.register(Zs.type),this.connection=new Dy(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(kn,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[Xi]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=C=>{kn.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await My(e),a=await this.getFileUrlByHash(t,c,e.name,e.size,o);if(a)return r(-1),a;let u=t;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${e.size}`),f.append("file-hash",c),f.append("file",e,e.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return kn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(kn,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Xi]:this.connection.token},e,o);return d(kn,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),d(kn,o,"no token"),c.headers={...c.headers,[Xi]:o,[tc]:this.connection.getBase64BaseURL()};try{return await w9.default(t,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(kn,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions`,o=await this.request(e),r=o.data.versions,i=o.data.latest;return i&&r.findIndex(s=>s.version===i)===-1&&r.unshift({version:-1,tag:"",published:!1}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=B9.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(kn,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${Do(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function Oy(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const Ou=w("block-ids");class Ay{constructor(){h(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);d(Ou,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);d(Ou,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=N(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class _y{constructor(){h(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new Ay,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(Ou,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Y2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Nt=w("op-parser");function _r(n){return n==="blocks"?"root":n}class Ny{constructor(t,e){h(this,"updatingBlockDataDeltaMap",new Map);h(this,"blockIds",new _y);this.handler=t,this.local=e}onDeleteBlock(t,e){const o=this.blockIds.getBlockId(t,e);this.blockIds.onDeleteBlock(t,e);const r=this.updatingBlockDataDeltaMap.get(o);r&&(Nt.debug(`ignore update object data before delete block: ${JSON.stringify(r)}`),this.updatingBlockDataDeltaMap.delete(o)),this.handler.onDeleteBlock(_r(t),e,this.local)}onInsertBlock(t,e,o){this.blockIds.onInsertBlock(t,e),this.handler.onInsertBlock(_r(t),e,o,this.local)}onUpdateBlockText(t,e,o){this.handler.onUpdateBlockText(_r(t),e,o,this.local)}onDeleteBlockData(t,e,o){const r=this.blockIds.getBlockId(t,e);let i=this.updatingBlockDataDeltaMap.get(r);i||(i=new Y2,this.updatingBlockDataDeltaMap.set(r,i)),i.delete(o)}onInsertBlockData(t,e,o,r){const i=this.blockIds.getBlockId(t,e);let s=this.updatingBlockDataDeltaMap.get(i);s||(s=new Y2,this.updatingBlockDataDeltaMap.set(i,s)),s.insert(o,r)}executeUpdateBlockDataActions(){Array.from(this.updatingBlockDataDeltaMap.entries()).forEach(([t,e])=>{const{containerId:o,blockIndex:r}=this.blockIds.getBlockIndexById(t);this.handler.onUpdateBlockData(_r(o),r,e.toDocBlockDelta(),this.local)})}}class Q2{}class Au{constructor(t){h(this,"key");this.key=t}}function Py(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d(Nt,s.id,"block id is required"),d(Nt,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return e.onInsertBlock(n,r,s),!0}function _u(n,t,e,o){if(e==="upsert"&&Py(n,t,o))return;d(Nt,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d(Nt,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),d(Nt,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d(Nt,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(Nt,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(Nt,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(Nt,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&e==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&e==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&e==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else e==="remove"&&a.r&&s.push(new Au(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new Q2),e==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(Nt,typeof l=="string","data is not string"),d(Nt,l!=="text","data !== 'text'"),d(Nt,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];e==="remove"&&a.r&&s.push(new Au(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Q2?o.onDeleteBlock(n,i):l instanceof Au?o.onDeleteBlockData(n,i,l.key):d(Nt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function $y(n,t,e,o){Nt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function jy(n,t,e,o){const r=n[1],i=n[2];d(Nt,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(Nt,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?Nt.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&o.onUpdateComment(r,e.local):i.i?t==="upsert"&&o.onCreateComment(r,e.local):i.r?t==="remove"&&o.onDeleteComment(r,e.local):Nt.error(`unknown comment op, ${JSON.stringify(n)}`)}function Nu(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Nu(l,t,e,o)});return}const i=r;if(d(Nt,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){$y(n);return}if(i==="comments"){jy(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{_u(s,l,t,e)}):n.slice(1).forEach(l=>{_u(s,l,t,e)});else if(typeof n[1]=="object"){const l=n[1];l.r&&t==="remove"&&o.onDeleteContainer(_r(s),e.local),l.i&&t==="upsert"&&o.onCreateContainer(_r(s),l.i,e.local)}else d(Nt,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),_u(s,n.slice(1),t,e)}function K2(n,t,e){const o=new Ny(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Y.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Nu(c,i,o,t)}):Nu(s,i,o,t)}o.executeUpdateBlockDataActions()}const Hy=w("sharedb-comments");function Pu(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(Hy,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),Y.default(e)}function J2(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function $u(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const Bt=w("sharedb-doc/doc-container"),X2="ot-json1";Zs.type.registerSubtype(Ik.type),Zs.type.name=X2,Zs.type.invert=null;class ts extends vi{constructor(e,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new Bk);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});h(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});h(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,c])=>{if(!Gs.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){Bt.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(Bt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),Bt.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(Bt.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));h(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,X2,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(e,o)=>{const r=[lo(e),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async e=>{const o=[lo(e),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(e,o,r)=>{const i=[lo(e),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(e,o)=>{const r=[lo(e),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[lo(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(e,o,r)=>{const i=[lo(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(e,o,r)=>{if(this.destroyed){Bt.warn("handleOp: destroyed");return}K2(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(Bt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new Ry(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new ts(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||Oy())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw Bt.error(o),Bt.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return zi(this.data())}getContainerBlocks(e){const o=this.data();d(Bt,o,"no doc data");const r=o[lo(e)];return d(Bt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=this.data();d(Bt,r,"no doc data");const i=r[lo(e)];d(Bt,i,`no container data: ${e}`);const s=i[o];return d(Bt,s,`no block data: ${o}`),Y.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Bt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=oe.apply(s,r);return d(Bt,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=Y.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>J2(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Pu(o)}localCreateComment(e,o){const r=$u(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=$u(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Rr(e),o,r)})}onInsertBlock(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockData(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockText(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Rr(e),o,r,i)})}onDeleteContainer(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Rr(e),o)})}onCreateContainer(e,o,r){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Rr(e),o,r)})}onDeleteComment(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return zi(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return zi(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:zi(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:zi(r),versionData:i}}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){K2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class t0{constructor(t){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",Qt.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));h(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const e0=w("remote-cursor-decorator");class ju{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];d(e0,typeof s=="string","invalid path containerId"),d(e0,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),a=ce(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const C=f.map(y=>({id:N(),type:"remote-cursor",name:y.user.displayName,time:y.time,rainbowIndex:y.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class n0 extends Wt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Ct(Cr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=z(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function Fy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).addListener("change",t)}function zy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).removeListener("change",t)}const KH="",Uy={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Vy={colorPalette:{colorDesc:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};S.mergeLang({"zh-CN":Uy,"en-US":Vy});const JH="";w("button");function Vn(n,t,e,o,r){const i=b("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&M(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function o0(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const uo=w("filterable-list");function qy(n){var e;const t=b("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(b("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&M(t,"selected"),t}function r0(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(qy(e))}),t}function i0(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Wy(n,t){const e=b("div",["filterable-list"],null),o=b("div",["filter"],e),r=b("div",["filter-container"],o),i=b("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=b("div",["list"],e),l=r0(i0(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function s0(n,t,e){const o=n.querySelector(".list");d(uo,o,"no list root");const r=r0(i0(t,e)),i=o.querySelector(".list-root");if(d(uo,i,"no exists menu"),Ii(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(uo,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class Gy{constructor(t,e){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",t=>{this.processKeyDown(t)});h(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");d(uo,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});h(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=Wy(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,s0(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),s0(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(t){var e;if(t.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class Zy extends Gy{constructor(e,o,r){super(e,r);h(this,"tippyInstance");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.tippyInstance=Sf.default(o,{interactive:!0,content:this.root,trigger:"manual",triggerTarget:null,hideOnClick:!0,arrow:!1,theme:"dropdown-list",offset:[0,0],onHide:this.handleHide,onShow:this.handleShow,onShown:this.handleShown})}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.tippyInstance.setProps({getReferenceClientRect:()=>e.getBoundingClientRect()}),this.reset(),this.tippyInstance.show(),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.tippyInstance.hide()}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.tippyInstance.hide()}}const XH="",tF="";function Yy(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const eF="",Nr=w("ui-command-bar-base"),Qy={itemElementTag:"div",tippyArrow:!1},nf=class extends Wt.TypedEmitter{constructor(e,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"options");h(this,"id");h(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close();return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close();else if(e.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",e=>{e.target instanceof Element&&(this.isInCommandBar(e.target)||this.close())});h(this,"handleHidden",()=>{this.close(),this.emit("close",this),sm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&M(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&im(this.id)});h(this,"handleItemMouseEnter",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(F(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close())}});h(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=_n(r);if(!vt(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...Qy,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(){this.subBar&&this.subBar.close(),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),e}destroy(){var e;this.close(),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-1;for(;;){const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(e){let o=e+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&F(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&F(s,"selected")}const r=this.getItemElementById(e);r?(M(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close();return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=nf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,F(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),M(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&vt(o,e)||vt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=b(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?r.classList.add("section","text"):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=e.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return d(Nr,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return d(Nr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return d(Nr,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return d(Nr,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(lt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=b("div",["editor-command-bar-root"],null),r=b("div",["editor-command-bar"],o);return e.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;d(Nr,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Nr,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Pr=nf;h(Pr,"commandBarCreators",new Map),w("ui-command-bar");class ec extends Pr{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=Sf.default(e,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(){var e;super.close(),this.isVisible&&((e=this.tippyInstance)==null||e.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}function Ky(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const Jy={"insert-hr":{shortcut:"/hr"},"insert-uml":{shortcut:"/uml"},"insert-table":{shortcut:"/table"},"insert-image":{shortcut:"/image"},"insert-code":{shortcut:"/code"},"insert-link":{shortcut:"/link"},"insert-drawio":{shortcut:"/uml"},"insert-video":{shortcut:"/video"},"insert-audio":{shortcut:"/audio"},"insert-math":{shortcut:"/math"},"insert-webPage":{shortcut:"/web"},"insert-bilibili":{shortcut:"/bilibili"},"insert-youku":{shortcut:"/youku"},"insert-figma":{shortcut:"/figma"},"insert-modao":{shortcut:"/modao"},"insert-tencent":{shortcut:"/tencent"},"insert-unordered":{shortcut:"/bl"},"insert-ordered":{shortcut:"/nu"},"insert-checkbox":{shortcut:"/todo"},"insert-quote":{shortcut:"/quote"},...Ky()};function l0(n){var t,e,o;return(o=(e=n.shortcut)!=null?e:(t=Jy[n.id])==null?void 0:t.shortcut)!=null?o:""}const c0=`<?xml version="1.0" ?>
26
+ `)}function nu(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Do(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function ou(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=gb(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function pb(n,t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData||n.selection.range.isCollapsed())return;const e=Hl(n);ou(n,e);const o=tu(n,e),r=eu(n,e),i=nu(o,e);t.clipboardData.setData("text/html",i),t.clipboardData.setData("text/plain",r),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(e))}function Cb(n){if(n.selection.range.isCollapsed())return;const t=Hl(n);ou(n,t);const e=tu(n,t),o=nu(e,t),r=new Blob([o],{type:"text/html"});rl([{type:"text/html",data:r}])}async function ru(n,t){const e=Jd(n,t,!1);ou(n,e);const o=tu(n,e),r=eu(n,e),i=nu(o,e);return rl([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}const iu=w("editor-input");class bb{constructor(t,e){h(this,"editor");h(this,"composing",!1);h(this,"callbacks");h(this,"inputElement");h(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Si(t)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});h(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});h(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});h(this,"handleCompositionstart",t=>{this.composing=!0,this.callbacks.onCompositionStart(t)});h(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});h(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});h(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}setTimeout(()=>{this.composing||(this.inputElement.value="")})}});h(this,"handleCopy",t=>{pb(this.editor,t)});h(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}iu.debug("on cut")});h(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});this.editor=t,this.callbacks=e;const o=b("input",["editor-input"],t.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const t=this.inputElement;t.removeEventListener("compositionstart",this.handleCompositionstart),t.removeEventListener("compositionend",this.handleCompositionend),t.onkeydown=null,t.oninput=null,t.oncopy=null,t.onpaste=null,t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),St.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(t){this.callbacks.onChanged(t)}handleRemoteChanged(t){this.callbacks.onRemoteChanged(t)}addHandler(t){this.callbacks.addHandler(t)}removeHandler(t){this.callbacks.removeHandler(t)}defaultInsertText(t,e,o,r,i){d(iu,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(iu,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function vb(n){const e=n.rootElement.getBoundingClientRect(),o=window.innerWidth,r=window.innerHeight,i=0-e.top+r/2,s=0-e.left+o/2,l=n.input.inputElement;l.style.left=`${s}px`,l.style.top=`${i}px`}const su=w("editor-caret");class kb{constructor(t){h(this,"editor");h(this,"caretElem");h(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=b("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const t=window.getComputedStyle(this.caretElem);return t.display!=="none"&&t.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const t=this.editor.selection.range.start;if(!(t instanceof Ut))return!1;const e=this.editor.getBlockById(t.blockId);return!!H(this.editor,e)}update(){if(Pf(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",vb(this.editor);return}const{range:e}=this.editor.selection;d(su,e.isCollapsed,"range is not collapsed");const o=e.start;d(su,o instanceof Ut,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(su,H(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Io(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Ae(r,o);const l=this.editor.contentElement.getBoundingClientRect(),c=i.left-l.left,a=i.top-l.top;t.style.left=`${c}px`,t.style.top=`${a}px`,t.style.height=`${i.height}px`;const u=this.editor.input.inputElement;u.style.left=`${c}px`,u.style.top=`${a+i.height-24}px`,St.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`)}}function yb(n){Fm(n),n.selection.range.getSelectedBlocks().forEach(t=>zm(n,t.block,t.start,t.end))}function Ip(n){return _n(n.rootContainer).clientHeight}function wb(n){return n.getFirstBlock().getBoundingClientRect().top}function Bb(n){return n.getLastBlock().getBoundingClientRect().bottom}function lu(n){const t=_n(n.rootContainer);return new DOMRect(t.clientLeft,t.clientTop,t.clientWidth,t.clientHeight)}function Eb(n,t){const e=lu(n),o=n.getBlockById(t.blockId),i=Ze(n,o,t);return So(e,i.x,i.y)&&So(e,i.right,i.bottom)}function Ib(n,t){const e=lu(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function xb(n,t){const e=lu(n),o=t.getBoundingClientRect();return So(e,o.x,o.y)||So(e,o.right,o.bottom)}function Sb(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,u=n.getContainerById(a.childContainerId);xb(n,u)||u.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(De(a)&&Ib(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(Eb(n,o))return;const i=Ze(n,r,o),s=r.getBoundingClientRect(),l=At(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,Bi(c),setTimeout(()=>{c.remove()})}function Tb(n,t){if(t.isCollapsed())return!1;const e=Kt(n.rootContainer),o=Gt(n.rootContainer),{start:r,end:i}=t;return r.blockId===G(e)&&r.offset===0&&i.blockId===G(o)&&i.offset===Z(n,o)}const Fl=w("editor-selection");class Db{constructor(t){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(lp(e,i)){Fl.debug("adjust selection because remote deleted current block");const s=cp(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=G(e);this.caret=new kb(t);const r=$(o,0,"normal");this._range=Vt(t,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=$(t,e,"normal");let i;o&&(i=$(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=Vt(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),lt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!Tb(this.editor,r))&&F(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),yb(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!vr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ze(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){Sb(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=Z(this.editor,e)||d(Fl,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||d(Fl,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&lt(e,"focused")&&(F(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{F(t,"focused"),F(t,"child-focused")})}setBlockFocused(t){if(lt(t,"focused"))return!1;M(t,"focused");let e=j(t);for(;We(e);){const o=z(e);d(Fl,o,"parent block not found"),M(o,"child-focused"),e=j(o)}return!0}}const xp=w("line-offset");function cu(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!H(n,e))return $(e,0,"home");let r=fg(e,t).start;const{next:i}=ml(e,r);return i&&Re(i)&&xi(i)==="br"&&(r+=1),$(e,r,"home")}function au(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===Z(n,e)||!H(n,e))return $(e,0,"end");const o=fg(e,t);return $(e,o.end,"end")}function Lb(n){if(!n.selection.range.focus.isSimple())return;const e=cu(n),o=au(n);!e||!o||n.selection.setSelection(e,o)}const Ne=w("block-text");function Sp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>0&&e<=Z(n,t),`invalid offset: ${e}`);const o=Po(t,e),r=e-o;r===0&&d(Ne,!1,`no text before offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,o,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return yd(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:Xs(l.insert)?"space":"text",offset:o,length:l.insert.length}}function Tp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>=0&&e<Z(n,t),`invalid offset: ${e}`);const r=Er(t,e)-e;r===0&&d(Ne,!1,`no text after offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,e,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return yd(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:Xs(l.insert)?"space":"text",offset:e,length:l.insert.length}}function Dp(n,t,e,o){let r=e;for(;r>0;){const i=Sp(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function Lp(n,t,e,o){const r=Z(n,t);let i=e;for(;i<r;){const s=Tp(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function Mp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Sp(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=Dp(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=Dp(n,t,r,"text");return i?i.offset+i.length:0}function Rp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Tp(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=Lp(n,t,r,"space");if(!s||s.offset===0)return Z(n,t);if(s.charType==="box")return s.offset;r=s.offset}const i=Lp(n,t,r,"text");return i?i.offset:Z(n,t)}const Op=w("word-offset");function du(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"home");if(e.offset===0||!H(n,o)){const s=gt(o);if(!s)return null;const l=$(s,Z(n,s),"end");if(t==="select"&&H(n,s)){const c=Mp(n,s,l.offset);return $(s,c,"normal")}return l}const r=Mp(n,o,e.offset);return $(o,r,"normal")}function uu(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"end");if(e.offset===Z(n,o)||!H(n,o)){const s=ht(o);if(!s)return null;const l=$(s,0,"home");if(t==="select"&&H(n,s)){const c=Rp(n,s,l.offset);return $(s,c,"end")}return l}const r=Rp(n,o,e.offset);return $(o,r,"normal")}function Mb(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!H(n,e))return;const o=du(n,"select"),r=uu(n,"select");!o||!r||n.selection.setSelection(o,r)}const ge=w("adjust-selection-pos");function Ap(n){const t=[];for(;n;){const e=j(n);if(t.unshift(e),Ct(e))return t;const o=z(e);d(ge,o,"child container has not parent container"),n=o}d(ge,!1,"should not come here: getParentContainers")}function _p(n,t){for(;t;){const e=j(t);if(e===n)return t;const o=z(e);d(ge,o,"could not find parent block for a child container"),t=o}d(ge,!1,"no parent block in specified container")}function Rb(n,t){const e=Ap(n),o=Ap(t);d(ge,e.length>0&&o.length>0,"block has not parent container"),d(ge,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=_p(r,n),s=_p(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Np(n,t){let e=z(t);for(d(ge,e,"element is not in a block");e;){const o=j(e);d(ge,We(o),"not a child container");const r=z(o);if(d(ge,r,"child container has not parent block"),r===n)return o;e=r}d(ge,!1,"failed to find parent container in complex block")}function zl(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ut&&e instanceof Ut?{anchor:t,focus:e}:(d(ge,t instanceof Ye&&e instanceof Ye,"both start and end are not simple or complex"),fl(n,o,t,e));const i=j(o),s=j(r);if(i===s)return t instanceof Ye&&(t=$(o,0,"home")),e instanceof Ye&&(e=$(r,Z(n,r),"end")),d(ge,t instanceof Ut,"not valid position type"),d(ge,e instanceof Ut,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ut&&e instanceof Ye){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const y=z(i);if(y&&y===z(v)){const E=bt(y,U(i)),L=bt(y,U(v));return fl(n,y,E,L)}}return null}const l=Js(o,r)>0,{newBlock1:c,newBlock2:a}=Rb(o,r);if(c===a){const v=c,y=Np(v,o),E=Np(v,r);return t=bt(c,U(y)),e=bt(c,U(E)),ge.debug(`select in complex block: ${y.id}, ${E.id}`),fl(n,v,t,e)}let u=l?Z(n,c):0;c===o&&t instanceof Ut&&(u=t.offset);let m=l?0:Z(n,a);return a===r&&e instanceof Ut&&(m=e.offset),t=$(c,u,l?"end":"home"),e=$(a,m,l?"home":"end"),{anchor:t,focus:e}}const Ob=w("range-from-point");function Pp(n,t,e){const o=[0,-12,12];for(let r=0;r<o.length;r++){const i=document.elementsFromPoint(t,e+o[r])[0];if(!i||!n.rootContainer.contains(i))continue;const s=z(i);if(!s||!n.contains(s))continue;const l=kt(n,s).getRangeFromPoint(n,s,t,e+o[r]);if(l)return l}return null}function $p(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Kt(t),c=$(l,0,"home");return new se(n,{anchor:c,focus:c})}const i=Gt(t),s=$(i,Z(n,i),"end");return new se(n,{anchor:s,focus:s})}function Ab(n,t,e){const o=Pp(n,t,e);if(o){if(o instanceof se)return o;d(Ob,o instanceof Qe,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return $p(n,a,t,e)}const r=document.elementsFromPoint(t,e)[0];if(!r)return null;const{children:i}=r,s=Array.from(i).filter(c=>mn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const u=c.getBoundingClientRect(),f=a.getBoundingClientRect();return fn(u,t,e)>fn(f,t,e)?a:c});return $p(n,l,t,e)}class _b{constructor(t){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",t=>{this.mouseDownEvent=t;const e=Ab(this.editor,t.x,t.y);if(e){if(e instanceof Qe)return;const o=this.editor.selection.range;if(t.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,e.focus),this.startPos=e.start}else this.editor.selection.setSelection(e.anchor,e.focus),this.startPos=e.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=Pp(this.editor,t.x,t.y);if(!e)return;const o=zl(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",t=>{this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){Mb(this.editor)}handleTripleClick(t){Lb(this.editor)}}const Nb=w("move-complex-block-position");function Pb(n,t,e){const o=n.getBlockById(t.blockId);d(Nb,ct(n,o),"is not a complex block");const r=ye(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?bt(o,U(s)):null}const $i=w("move-simple-block-position");function jp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[0];return Kt(o)}function Hp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Gt(o)}function Fp(n,t,e){const o=e?jp(n,t):Hp(n,t);return ct(n,o)?Fp(n,o,e):o}function $b(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===0?jp(n,e):pr(e)}function jb(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===1?Hp(n,e):gr(e)}function hu(n){return n==="ArrowLeft"||n==="ArrowUp"}function fu(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);d($i,r,"child container has not parent block"),d($i,ct(n,r),"is not a complex block");const i=ye(n,r).getNextContainer(n,r,o,e);return i?hu(e)?Gt(i):Kt(i):fu(n,r,e)}function Hb(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);if(d($i,r,"child container has not parent block"),hu(e)){const l=gt(r);if(l)return l}else{const l=ht(r);if(l)return l}const i=fu(n,r,e);if(i)return i;let s=r;for(;!Ct(j(s));)s=z(j(s));return hu(e)?gt(s):ht(s)}function Fb(n,t,e){return!ct(n,t)||ye(n,t).enableKeyboardSelect?t:Fp(n,t,e==="ArrowDown"||e==="ArrowRight")}function zb(n,t,e){const o=n.getBlockById(t.blockId),i=kt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?$b(n,t):jb(n,t);if(s||(s=fu(n,o,e),s||(s=Hb(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Ct(j(o)))return null;const l=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(l,0,"home")}return null}if(s=Fb(n,s,e),H(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return k8(n,s,o,t,l);if(e==="ArrowUp")return v8(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?$(s,Z(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?$(s,0,"home"):null}function Ub(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(H(n,r))return o;const i=ht(r);if(i)return $(i,0,"home");if(!Ct(j(r))||n.readonly)return o;const s=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(s,0,"home")}function Vb(n,t,e){const o=n.selection.range;let r;if(o instanceof se)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=Ub(n,t,o):r=zb(n,o.getFocusedPos(),t);else if(r=Pb(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Gt(s);r=$(l,0,"home")}else{const l=Kt(s);r=$(l,Z(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:zl(n,o.anchor,r):null}function so(n,t,e){const o=Vb(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function qb(n){return so(n,"ArrowLeft","move"),!0}function Wb(n){return so(n,"ArrowRight","move"),!0}function Gb(n){return so(n,"ArrowUp","move"),!0}function Zb(n){if(so(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=j(t);if(Ct(e)||Gt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",U(o),Ve(o)),!0}function Yb(n){return so(n,"ArrowDown","select"),!0}function Qb(n){return so(n,"ArrowLeft","select"),!0}function Kb(n){return so(n,"ArrowRight","select"),!0}function Jb(n){return so(n,"ArrowUp","select"),!0}function Xb(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function tv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ev(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function nv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function mu(n,t){if(!ct(n,t))return t;const o=ye(n,t).getChildContainers(n,t)[0],i=Ot(o)[0];return mu(n,i)}function gu(n,t){if(!ct(n,t))return t;const e=ye(n,t).getChildContainers(n,t),o=e[e.length-1],r=Ot(o),i=r[r.length-1];return gu(n,i)}function ov(n){const t=gu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(e),!0}function rv(n){const t=mu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(e),!0}function iv(n){const t=mu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function sv(n){const t=gu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function lv(n){if(!n.selection.range.focus.isSimple())return!1;const e=cu(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function av(n){if(!n.selection.range.focus.isSimple())return!1;const e=cu(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function dv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const zp=w("find-block-position");function uv(n,t,e,o){d(zp,ct(n,t),"is not a complex block");const r=ye(n,t).getChildContainers(n,t);d(zp,r.length>0,"complex block has not any child container");const i=Ze(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=ig(n,t,s,l);return pu(n,c,e,o)}function pu(n,t,e,o){if(ct(n,t))return uv(n,t,e,o);const r=G(t);let i=Number.MAX_SAFE_INTEGER;const s=Ze(n,e,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=$(r,0,"home");const u=Z(n,t);for(let f=0;f<=u;f++){const m=$(r,f,"normal"),C=Ze(n,t,m),v=fn(C,l,c);v<i&&(i=v,a=m)}return a}const Up=w("page-offset");function hv(n,t){const e=Ip(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<wb(n))return n.getFirstBlock();const i=gt(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=gt(s)}return n.getFirstBlock()}function fv(n,t){const e=Ip(n)*.9,o=t.getBoundingClientRect(),r=Bb(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=ht(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=ht(l)}return n.getLastBlock()}function Vp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=hv(n,e);let r;return o===n.getFirstBlock()?r=$(o,0,"home"):r=pu(n,o,e,t),r}function qp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=fv(n,e);let r;return o===n.getLastBlock()?r=$(o,Z(n,o),"end"):r=pu(n,o,e,t),r}function mv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function gv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function pv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);if(!e)return!1;const o=zl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function Cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);if(!e)return!1;const o=zl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const ji=w("select-all");function bv(n,t){const e=t.getEditor(),o=ye(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=G(n);return t.start.blockId===s&&t.start.childContainerId===U(r)&&t.end.blockId===s&&t.end.childContainerId===U(i)}function vv(n,t){d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block");const e=ye(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Vt(n,{anchor:bt(t,U(o)),focus:bt(t,U(r))}))}function Wp(n,t){const e=j(t),o=Ot(e),r=o[0],i=o[o.length-1],s=$(r,0,"home"),l=$(i,Z(n,i),"end");n.selection.setSelection(s,l,{noScroll:!0})}function kv(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&H(n,t)){const r=e.start,i=e.end,s=Z(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return M(n.rootContainer,"select-all"),Wp(n,Kt(n.rootContainer)),!1}return d(ji,!e.isSimple(),"invalid range type"),bv(t,e)?(Wp(n,t),!1):(d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block"),vv(n,t),!0)}function yv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function wv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const Gp=w("delete-text");function Zp(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ut||d(Gp,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(Gp,H(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!me(s,l-e)){const c=Po(s,l);e=l-c}}else if(t==="forward"&&l+e>Z(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function Yp(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const Bv=w("handle-backspace");function Cu(n,t){if(!yt(n,t))return;const e=j(t);Ve(e)!==1&&n.deleteBlock(t)}function Ev(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===0){if(Yp(n,o))return;const r=gt(o);if(r)if(H(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ct(n,r)){Cu(n,o);const i=yr(n,r);i?n.selection.selectBlock(i,Z(n,i)):n.selection.selectBlock(r,0,Z(n,r))}else Cu(n,o),d(Bv,De(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=j(o);if(We(i)){const s=ng(n,i);s&&(Cu(n,o),n.selection.selectBlock(s,Z(n,s)))}}}else Zp(n,"backward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function Iv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===Z(n,o)){const r=ht(o);r&&(H(n,r)?n.mergeTextBlock(o,r,{focus:!0}):yt(n,o)?n.deleteBlock(o,Lt(n,r,0)):n.deleteBlock(r))}else Zp(n,"forward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function xv(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(H(n,e)){if(yt(n,e)&&Yp(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function Sv(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!H(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const Tv=w("input-handler-actions");function Dv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(xv(n),!0))}function Lv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Iv(n),!0))}function Mv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Ev(n),!0))}function Rv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Sv(n),!0))}function Ov(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{const e=n.selection.focusedBlock,o=n.selection.range.start;d(Tv,o.isSimple(),"not simple position"),n.insertTextToBlock(e,o.offset,t)}),!0)}function Av(n){return Cb(n),qd(n),!0}const Ul={ArrowDown:Zb,ArrowUp:Gb,ArrowLeft:qb,ArrowRight:Wb,"Shift+ArrowDown":Yb,"Shift+ArrowUp":Jb,"Shift+ArrowLeft":Qb,"Shift+ArrowRight":Kb,"CtrlOrCmd+ArrowLeft":Xb,"CtrlOrCmd+ArrowRight":tv,"CtrlOrCmd+Shift+ArrowLeft":ev,"CtrlOrCmd+Shift+ArrowRight":nv,"CtrlOrCmd+ArrowUp":rv,"CtrlOrCmd+ArrowDown":ov,"CtrlOrCmd+Shift+ArrowUp":iv,"CtrlOrCmd+Shift+ArrowDown":sv,"CtrlOrCmd+A":kv,Home:av,End:dv,"Shift+Home":lv,"Shift+End":cv,PageUp:mv,PageDown:gv,"Shift+PageUp":pv,"Shift+PageDown":Cv,"CtrlOrCmd+X":Av,"CtrlOrCmd+Z":yv,"CtrlOrCmd+Shift+Z":wv,Enter:Dv,Delete:Lv,Backspace:Mv,"Shift+Enter":Rv,"CtrlOrCmd+Shift+V":Ov};function Qp(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function Kp(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(i.src=l)}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{Kp(n,l,e)})})}function Jp(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):Kp(t,r,e)})}async function _v(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function Nv(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function Pv(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(Nv(n,t)){const s=Array.from(Object.keys(o));r=await _v(n,s),Jp(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&Jp(n,t,i)}async function $v(n,t){await Pv(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Sr(n);n.insertDoc(e,o,t)})}const jv=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function Hv(n){let t;for(const e of jv)if(t=n[e],t)break;return t||null}class Fv{constructor(t){h(this,"editor");h(this,"handlers",[]);this.editor=t}onInsertText(t,e){if(!H(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Sr(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e))}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=Sr(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Sr(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{if(!o)return;for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,t,o))return}const r=Hv(o);if(!!r){await this.pasteDoc(r);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,t,o))return}}})}onFocus(){M(this.editor.rootElement,"active")}onBlur(){F(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t)}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){jd(this.editor,i)}defaultHandleKeydown(t,e){return Qp(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleBeforePasteDoc&&await o.handleBeforePasteDoc(this.editor,t))return}await $v(this.editor,t);for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleAfterPasteDoc&&await o.handleAfterPasteDoc(this.editor,t))return}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function zv(n,t,e){const o=fr(t,e);return o.remove(),o}w("copy-dom-attributes");const Xp=["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 Uv(n,t){for(let l=0;l<Xp.length;l++){const c=Xp[l];t[c]=n[c]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const c=e[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];e.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function t2(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function e2(n,t,e){var a;const o=n.getContainerById(t),r=fr(o,e),i=Ro(r),s=n.doc.getBlockData(t,e),l=kt(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=t2(u);t2(r),f.forEach(C=>r.appendChild(C));const m=cl(u);if(m){const C=cl(r);C&&C.remove(),r.appendChild(m)}Uv(u,r)}Vm(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const Vv=w("transform-selection");function n2(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(Vv,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=oe.transformCursor(i.offset,e,o);l=$(t,a,"normal")}let c=s;if(s.blockId===t){const a=oe.transformCursor(s.offset,e,o);c=$(t,a,"normal")}return Vt(n,{anchor:l,focus:c})}const qv=w("handle-block-text-changed");function Wv(n,t,e,o,r){const i=n.getContainerById(t),s=fr(i,e),l=n.doc.getBlockData(t,e);if(d(qv,l.text,"no block text"),Hm(n,s).setBlockText(n,s,l.text),!r){const c=n2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Gv(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function o2(n,t,e,o){const r=kt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function Zv(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{o2(n,i,o,{child:!0})}),o2(n,r,o,{child:!1})}const Hn=w("editor-doc");class Yv extends vi{constructor(e,o,r){super();h(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}localUpdateBlockText(e,o,r,i){d(Hn,this.editor.isWritable(),"editor is readonly");const s=this.getBlockData(e,o),l=s.text;d(Hn,l,`no text, ${e}, ${o}`);const c=n2(this.editor,s.id,r,!0),a=oe.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(e,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(e,o,r,i){d(Hn,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Gv(s,r));this.localEvents.forEach(a=>a.onBeforeUpdateBlockData(e,s.id,s,l,i));const c=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(oo(this.editor,i)),c}localInsertBlock(e,o,r,i,s){d(Hn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(oo(this.editor,i),s),l}localDeleteBlock(e,o,r){d(Hn,this.editor.isWritable(),"editor is readonly");const i=Y.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(oo(this.editor,r)),s}localDeleteChildContainers(e){return d(Hn,this.editor.isWritable(),"editor is readonly"),e.forEach(o=>{const r=Y.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return d(Hn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Hn.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),Wv(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),e2(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);w7(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){Zv(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);zv(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Hn.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function r2(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 bu=w("undo-action");class Mr{constructor(t,e,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return d(bu,t,"no other action"),!1}combine(t){d(bu,!1,"no other")}setAfterRange(t){this.afterRange&&bu.warn("after range has already set"),this.afterRange=t}}const Qv=w("block-action");class i2 extends Mr{constructor(e,o,r,i,s){super(e,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Y.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(d(Qv,this.blockIndex===K(i),"invalid block index"),zd(e,i,oo(e,o)),!0):!1}insertBlock(e,o){return Tr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Kv extends i2{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class Jv extends i2{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class Xv extends Mr{constructor(e){super(e,U(e.rootContainer),e.selection.range.toDocRange());h(this,"actions",[])}addAction(e){r2(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Mr&&(o.afterRange||o.setAfterRange(e))}}const zo=w("update-block-data-action");class Vl extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(zo,this.blockId===i.id,"invalid block id"),d(zo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Y.default(i),this.afterBlockData=Y.default(s),d(zo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),Pl(e,o,Vl.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),Pl(e,o,Vl.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const vu=w("update-block-text-action");class Hi extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Y.default(i),this.afterRichTextData=Y.default(s),this.type=Hi.calType(i,s)}static calType(e,o){d(vu,e,"no old data"),d(vu,o,"no new data");const i=oe.diff(e,o),s=new Set;let l=!1;const c=u=>Yf(u)?`cjk_${u}`:Gf(u)?"number":Xs(u)?"space":Zf(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Nl(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Nl(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Hi)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){d(vu,e instanceof Hi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class s2 extends Mr{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainer(this.containerId,Y.default(this.blocks)),!0}}class tk extends s2{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class ek extends s2{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Xe=w("undo");class nk{constructor(t){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(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):(r2(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(Xe,!this.currentGroup,"current group already exists"),this.currentGroup=new Xv(this.editor),this.groupCounter=1):(d(Xe,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(Xe,this.currentGroup,"current group not exists"),d(Xe,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Xe.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 Xe.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(oo(this.editor,t.beforeRange))}catch(e){Xe.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(oo(this.editor,e)):Xe.warn("no after range")}catch(e){Xe.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),oe.diff(o,r).length!==0&&this.addAction(new Hi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Vl(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(Xe,e>=0,"invalid block index"),d(Xe,o,"no block data"),this.addAction(new Kv(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Jv(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new tk(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ek(this.editor,t,e)))}}class ok{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class rk{constructor(){h(this,"converters",[]);this.addConverter(new ok)}async fromData(t,e){let o={};for(const r of this.converters){const i=await r.fromData(t,e);i&&(o={...o,...i})}return o}addConverter(t){this.converters.push(t)}}class ik{constructor(t){h(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class _t extends Wt.TypedEmitter{constructor(e){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=z(o);if((!r||!vt(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?G(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&vt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&F(s,"hover"),e&&M(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new _t(e))}getParentTextContentChild(e,o){if(!H(this.editor,e))return null;const r=rt(e);return o.parentElement===r?o:od(o)}}const l2="style-color-",c2="style-bg-color-";class sk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(l2)?i["data-style-color"]=s.substring(l2.length):s.startsWith(c2)?i["data-style-bg-color"]=s.substring(c2.length):s.startsWith("style")&&r.push(s):typeof l=="string"&&s==="link"&&(r.push("link"),i.link=l)}),{classes:r,attributes:i}}renderBlock(t,e,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=t.selection)==null?void 0:l.range)==null?void 0:c.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),_t.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&M(o,"focused"),_t.get(t).hoveringBlockId()===r.id&&M(o,"hover")}}function lk(n){n.editorBlocks.registerBlockClass(Ai),n.editorBlocks.registerBlockClass(eg),n.editorBoxes.registerBoxClass(Fg),n.editorBoxes.registerBoxClass(zg),n.editorInsertions.registerInsertionClass(qg),n.editorBlockRenders.registerRender(new sk)}function ck(n,t){lk(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 a2=w("range-commands");function d2(n,t){n.forEach(e=>{e.source=t,e.children&&d2(e.children,t)})}function u2(n,t,e){const o=G(t);d(a2,o===e.start.blockId,"invalid start range"),d(a2,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);d2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),ct(n,t)&&kr(n,t,e.start,e.end).forEach(l=>{Ot(l).forEach(a=>{const u=Z(n,a),f=Vt(n,{anchor:$(a,0,"home"),focus:$(a,u,"end")}),m=u2(n,a,f);i.push(...m)})}),i}function h2(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Vt(t,{anchor:r.start,focus:r.end});u2(t,r.block,i).forEach(l=>{o.push(l)})}),o}function f2(n,t,e,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,t,e,o,r,{}))return i[G(t)]=c,!0;let a=!1;return ct(n,t)&&kr(n,t,e.start,e.end).forEach(m=>{Ot(m).forEach(v=>{const y=Z(n,v),E=Vt(n,{anchor:$(v,0,"home"),focus:$(v,y,"end")});f2(n,v,E,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function m2(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const c=Vt(o,{anchor:l.start,focus:l.end});f2(o,l.block,c,t,e,r)}),r}const ak=w("command-providers");class g2{constructor(t){h(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return d(ak,e,`no command provider, id=${t}`),e}getCommands(t){return h2(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>m2(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function dk(n,t){const e=j(t),o=U(e),r=K(t);e2(n,o,r)}const uk=w("table-scroll");class p2{constructor(t,e,o,r,i){h(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class hk{constructor(t){h(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){uk.warn(`event has already registered: ${e}`);return}i.push(new p2(this.editor,t,e,o,r))}else{const s=new p2(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const C2=w("update-block-text");function fk(n,t){const e=n.getBoxById(t.id),o=z(e);d(C2,o,"no parent block"),d(C2,H(n,o),"not a text block");const r=n.getBlockText(o),i=Rg(r,"id",t.id,t);fp(n,o,i)}function mk(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function gk(n){return n.readonly?!1:!Ke(n).find(o=>!n.isBlockWritable(o.block))}class pk{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}async getItem(t){return window.localStorage.getItem(this.getKey(t))}async setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}async removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class Ck{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(An(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Fn=w("editor");class bk extends Wt.TypedEmitter{constructor(e,o,r){var i,s,l,c,a,u,f;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Ck);h(this,"dataConverter",new rk);h(this,"editorBlocks",new Km(this));h(this,"editorBoxes",new Vg(this));h(this,"editorInsertions",new Gg(this));h(this,"editorEmbeds",new Xm(this));h(this,"editorDecorators",new Zg(this));h(this,"editorCommandProviders",new g2(this));h(this,"editorBlockRenders",new ik(this));h(this,"blockHooks",[]);h(this,"domEvents",new hk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new Fv(this));h(this,"settingsProvider");h(this,"_readonly",!1);Fn.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(c=r==null?void 0:r.settingsProvider)!=null?c:new pk(this),ck(this,r==null?void 0:r.components),this.blockHooks.push(...(u=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?u:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new nk(this),this.doc=new Yv(this,o,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=Pm(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new bb(this,this.inputHandlers),this.selection=new Db(this),this.selectionHandler=new _b(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),St.isMobile&&M(this.rootElement,"mobile"),St.isSafari&&M(this.rootElement,"safari"),this._readonly&&M(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?M(this.rootElement,"readonly"):F(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:_n(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return d(Fn,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){Fn.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,o){Wd(this,e,o)}isWritable(){return gk(this)}isBlockWritable(e){return mk(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return d(Fn,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),d(Fn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return $m(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,mr(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,nd(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return d(Fn,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return d(Fn,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return fr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return K(o)}return K(e)}getContainerById(e){return Cr(this,e)}getParentContainer(e){return j(e)}reloadBlock(e){dk(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Tr(this,e,o,r,i!=null?i:c,s)}insertEmbed(e,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Ud(this,e,o)}mergeTextBlock(e,o){return dp(this,e,o)}breakTextBlock(e,o,r){return Dr(this,e,o,r).newBlock}getTextPosition(){return Sr(this)}getBlockString(e,o){const r=this.getBlockText(e);return wt(r,o)}getBlockData(e){return io(this,e)}getBoxData(e){return Jg(this,e)}getBlockText(e){return we(this,e)}setBlockText(e,o){fp(this,e,o)}deleteTextFromBlock(e,o,r,i){return Hd(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return tp(this,e,o,r,i)}insertBoxToBlock(e,o,r){return ep(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){pp(this,e,o,r,i)}insertDocAt(e,o,r,i){return Yd(this,e,o,r,i)}deleteChildContainers(e){ap(this,e)}replaceBlockText(e,o){return Nl(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...c}=i;return Pl(this,e,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return mp(this,e,o,r)}updateBoxData(e){fk(this,e)}getSelectedText(){const e=Hl(this);return eu(this,e)}clearSelectedContents(){qd(this)}insertTextBlock(e,o,r,i){const s=jn(e!=null?e:"");return ip(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){op(this);return}o?(this.compositingText="",Wa()||jd(this,e)):(this.compositingText=e,np(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Fi(n,t,e){return new bk(n,t,e)}function vk(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=$a.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const kk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class ql extends Wt.TypedEmitter{constructor(e){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=e&&e.length>0?e:kk}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&Gs.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&xl(r.range)&&Ng(r.range)).forEach(r=>{const i=r.range.anchor.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(xl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=oe.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=oe.transformCursor(a.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xt=w("local-doc");class ku extends vi{constructor(e,o){super();h(this,"doc");h(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[jn("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Y.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);d(Xt,r,`no container data: ${e}`);const i=r[o];return d(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Xt,i.text,"no text for data");const s=oe.apply(i.text,r);return i.text=s,d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return d(Xt,i,`no container data: ${e}`),d(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);d(Xt,r,`no container data: ${e}`),d(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainer(e,o){this.doc.blocks[e]=o,d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!0)})}localDeleteChildContainers(e){Xt.debug(`delete child containers: ${e}`),e.forEach(o=>{d(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(Xt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){d(Xt,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(Xt,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ql}setDoc(e){this.doc=Y.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}function Uo(n){return Ct(j(n))}class yk{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function yu(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new yk(o)})}const wk=w("remote-cursor");class Bk{constructor(){h(this,"remoteUsers",new ql)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):wk.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 Ek(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function zi(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=Ek(Y.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function lo(n){return n==="root"?"blocks":n}function Rr(n){return n==="blocks"?"root":n}const Ik={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ne.default(n)},apply(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},compose(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},diff(n,t){const e=new ne.default(n),o=new ne.default(t);return e.diff(o).ops},transform(n,t,e){const o=new ne.default(n);return new ne.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new ne.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var Ui=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},co={},wu=xf.default.EventEmitter;co.EventEmitter=wu,co.mixin=xk;function xk(n){for(var t in wu.prototype)n.prototype[t]=wu.prototype[t]}var b2=["info","warn","error"];function v2(){var n={};b2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var Sk=v2;v2.prototype.setMethods=function(n){n=n||{};var t=this;b2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var Tk=Sk,Dk=new Tk,k2=Dk;function Vo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Vo):this.stack=new Error().stack}Vo.prototype=Object.create(Error.prototype),Vo.prototype.constructor=Vo,Vo.prototype.name="ShareDBError",Vo.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 Wl=Vo,Vi={},y2=Lk;function Lk(n,t,e,o){var r=function(s,l,c,a){t(c,s,l,"left"),t(a,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var C=[];if(r(s[m],u,f,C),m++,C.length===1)u=C[0];else if(C.length===0){for(var v=m;v<s.length;v++)o(f,s[v]);u=null;break}else{for(var y=i(s.slice(m),C),E=0;E<y[0].length;E++)o(f,y[0][E]);for(var L=0;L<y[1].length;L++)o(c,y[1][L]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var w2={exports:{}},ao=w2.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||""}},Bu=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Eu=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")},Gl=function(n){for(var t=0;t<n.length;t++)Eu(n[t])};ao.apply=function(n,t){var e;Gl(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=Bu(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var zn=ao._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:Bu(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:Bu(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};ao.compose=function(n,t){Gl(n),Gl(t);for(var e=n.slice(),o=0;o<t.length;o++)zn(e,t[o]);return e},ao.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),zn(t,o)}return t};var Iu=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};ao.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=Iu(n,t[r],o);return n};var Mk=ao._tc=function(n,t,e,o){if(Eu(t),Eu(e),t.i!=null)zn(n,{i:t.i,p:Iu(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(zn(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&zn(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)zn(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)zn(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),a=e.d.slice(s-e.p,l-e.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=Iu(i.p,e),zn(n,i))}return n},Rk=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};ao.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=Rk(n[t]);return n},y2(ao,Mk,Gl,zn);var Zl=function(n){return Object.prototype.toString.call(n)=="[object Array]"},Ok=function(n){return!!n&&n.constructor===Object},tn=function(n){return JSON.parse(JSON.stringify(n))},tt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Un={};tt.registerSubtype=function(n){Un[n.name]=n},tt.create=function(n){return n===void 0?null:tn(n)},tt.invertComponent=function(n){var t={p:n.p};return n.t&&Un[n.t]&&(t.t=n.t,t.o=Un[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},tt.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(tt.invertComponent(t[o]));return e},tt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Zl(n[t].p))throw new Error("Missing path")},tt.checkList=function(n){if(!Zl(n))throw new Error("Referenced element not a list")},tt.checkObj=function(n){if(!Ok(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function qi(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 Wi(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}tt.apply=function(n,t){tt.checkValidOp(t),t=tn(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&qi(r);for(var i=null,s=e,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Un[r.t])s[l]=Un[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)tt.checkList(s),s[l]=r.li;else if(r.li!==void 0)tt.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)tt.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(tt.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)tt.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)tt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},tt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},tt.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=tt.apply(n,r),e(r,n)}return n};var Ak=tt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};tt.append=function(n,t){if(t=tn(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)&&(qi(t),qi(e)),Ak(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Un[t.t]){if(e.o=Un[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),Wi(t),n.push(t);Wi(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)&&(Wi(t),Wi(e)),n.push(t)},tt.compose=function(n,t){tt.checkValidOp(n),tt.checkValidOp(t);for(var e=tn(n),o=0;o<t.length;o++)tt.append(e,t[o]);return e},tt.normalize=function(n){var t=[];n=Zl(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),tt.append(t,o)}return t},tt.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},tt.canOpAffectPath=function(n,t){return tt.commonLengthForOps({p:t},n)!=null},tt.transformComponent=function(n,t,e,o){t=tn(t);var r=tt.commonLengthForOps(e,t),i=tt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var c=tn(e);c.p=c.p.slice(s),t.ld=tt.apply(tn(t.ld),[c])}else if(t.od!==void 0){var c=tn(e);c.p=c.p.slice(s),t.od=tt.apply(tn(t.od),[c])}}if(r!=null){var a=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(qi(t),c=tn(e),qi(c)),c.t&&Un[c.t]){if(t.t&&t.t===c.t){var u=Un[t.t].transform(t.o,c.o,o);if(t.si!=null||t.sd!=null)for(var f=t.p,m=0;m<u.length;m++)t.o=[u[m]],t.p=f.slice(),Wi(t),tt.append(n,t);else(!Zl(u)||u.length>0)&&(t.o=u,tt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(a){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=tn(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&a&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&a&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&a){if(e.p[r]===t.p[r])return n;var f=e.p[r],C=t.p[r],v=t.lm;(f<v||f===v&&C<v)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var C=t.p[r],v=t.lm,y=e.p[r],E=e.lm;if(y!==E)if(C===y)if(o==="left")t.p[r]=E,C===v&&(t.lm=E);else return n;else C>y&&t.p[r]--,C>E?t.p[r]++:C===E&&y>E&&(t.p[r]++,C===v&&t.lm++),(v>y||v===y&&v>C)&&t.lm--,v>E?t.lm++:v===E&&(E>y&&v>C||E<y&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===y&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&a){var C=e.p[r],v=e.lm;f=t.p[r],f>C&&t.p[r]--,f>v&&t.p[r]++}else{var C=e.p[r],v=e.lm;f=t.p[r],f===C?t.p[r]=v:(f>C&&t.p[r]--,(f>v||f===v&&C>v)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&a){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")tt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!a)return n;if(t.oi!==void 0)delete t.od;else return n}}}return tt.append(n,t),n},y2(tt,tt.transformComponent,tt.checkValidOp,tt.append);var _k=w2.exports;tt.registerSubtype(_k);var Nk=tt,Pk={type:Nk};(function(n){n.defaultType=Pk.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)})(Vi);var en={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(en);var B2=Array.isArray,E2=Object.keys,$k=Object.prototype.hasOwnProperty,jk=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=B2(t),r=B2(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var c=t instanceof Date,a=e instanceof Date;if(c!=a)return!1;if(c&&a)return t.getTime()==e.getTime();var u=t instanceof RegExp,f=e instanceof RegExp;if(u!=f)return!1;if(u&&f)return t.toString()==e.toString();var m=E2(t);if(s=m.length,s!==E2(e).length)return!1;for(i=s;i--!==0;)if(!$k.call(e,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},I2=co,Hk=k2,Be=Wl,Yl=Vi,nn=en,Fk=nn.clone,zk=jk,pe=Be.CODES,Uk=st;function st(n,t,e){I2.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}I2.mixin(st),st.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())})},st.prototype._setType=function(n){if(typeof n=="string"&&(n=Yl.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Be(pe.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},st.prototype._setData=function(n){this.data=n,this._dataStateVersion++},st.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Be(pe.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 Be(pe.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?Yl.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},st.prototype.whenNothingPending=function(n){var t=this;nn.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},st.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},st.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},st.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},st.prototype._emitResponseError=function(n,t){if(n&&n.code===pe.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)},st.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){nn.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},st.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){nn.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},st.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===pe.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=Ql(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Ql(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},st.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))},st.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()},st.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);Vk(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},st.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},st.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},st.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=qk([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},st.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;nn.nextTick(function(){n._handleSubscribe()})}}};function Vk(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function qk(n){return n=n.filter(nn.truthy),n.length?function(t){nn.callEach(n,t)}:null}st.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Wk(n){delete n.op,delete n.create,delete n.del}function Ql(n,t){if(n.del)return Wk(t);if(t.del)return new Be(pe.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}st.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Be(pe.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===Yl.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Ql(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},st.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 Be(pe.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>=nn.MAX_SAFE_INTEGER)return this.emit("error",new Be(pe.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)}},st.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Be(pe.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;nn.nextTick(function(){r.flush()})},st.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},st.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},st.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!zk(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}}},st.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},st.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=Yl.defaultType.uri),this.type){var r=new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},st.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Be(pe.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},st.prototype.pause=function(){this.paused=!0},st.prototype.resume=function(){this.paused=!1,this.flush()},st.prototype.toSnapshot=function(){return{v:this.version,data:Fk(this.data),type:this.type.uri}},st.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return Hk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},st.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=Ql(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},st.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=nn.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},st.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=nn.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var qo={};qo.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 x2=co,S2=qo.ACTIONS,Gk=en,Zk=Ce;function Ce(n,t,e,o,r,i,s){x2.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}x2.mixin(Ce),Ce.prototype.hasPending=function(){return!this.ready},Ce.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Ce.prototype.destroy=function(n){this.connection.canSend&&this.action===S2.querySubscribe&&this.connection.send({a:S2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Gk.nextTick(n)},Ce.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ce.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ce.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ce.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var c=t[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},Ce.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Ce.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)},Ce.prototype._handleError=function(n){this.emit("error",n)},Ce.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Ce.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var T2=co,Yk=qo.ACTIONS,Qk=en,D2=vn;function vn(n,t){if(T2.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={}}T2.mixin(vn),vn.prototype.submit=function(n,t){this.value=n,this.send(t)},vn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},vn.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()})},vn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},vn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},vn.prototype._message=function(){return{a:Yk.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},vn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},vn.prototype._callbackOrEmit=function(n,t){if(t)return Qk.nextTick(t,n);n&&this.emit("error",n)};var Kk=en,L2=xu;function xu(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}xu.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},xu.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Kk.nextTick(n)};var Su={exports:{}};(function(n,t){(function(e,o){o(t)})(Ui,function(e){function o(p,k){k=k|0;for(var B=Math.max(p.length-k,0),I=Array(B),D=0;D<B;D++)I[D]=p[k+D];return I}var r=function(p){var k=o(arguments,1);return function(){var B=o(arguments);return p.apply(null,k.concat(B))}},i=function(p){return function(){var k=o(arguments),B=k.pop();p.call(this,k,B)}};function s(p){var k=typeof p;return p!=null&&(k=="object"||k=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(p){setTimeout(p,0)}function u(p){return function(k){var B=o(arguments,1);p(function(){k.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function C(p){return i(function(k,B){var I;try{I=p.apply(this,k)}catch(D){return B(D)}s(I)&&typeof I.then=="function"?I.then(function(D){v(B,null,D)},function(D){v(B,D.message?D:new Error(D))}):B(null,I)})}function v(p,k,B){try{p(k,B)}catch(I){m(y,I)}}function y(p){throw p}var E=typeof Symbol=="function";function L(p){return E&&p[Symbol.toStringTag]==="AsyncFunction"}function x(p){return L(p)?C(p):p}function O(p){return function(k){var B=o(arguments,1),I=i(function(D,T){var R=this;return p(k,function(_,q){x(_).apply(R,D.concat(q))},T)});return B.length?I.apply(this,B):I}}var A=typeof Ui=="object"&&Ui&&Ui.Object===Object&&Ui,P=typeof self=="object"&&self&&self.Object===Object&&self,V=A||P||Function("return this")(),nt=V.Symbol,ot=Object.prototype,ut=ot.hasOwnProperty,dt=ot.toString,Et=nt?nt.toStringTag:void 0;function re(p){var k=ut.call(p,Et),B=p[Et];try{p[Et]=void 0;var I=!0}catch{}var D=dt.call(p);return I&&(k?p[Et]=B:delete p[Et]),D}var Xn=Object.prototype,te=Xn.toString;function Fe(p){return te.call(p)}var bo="[object Null]",cr="[object Undefined]",ar=nt?nt.toStringTag:void 0;function vo(p){return p==null?p===void 0?cr:bo:ar&&ar in Object(p)?re(p):Fe(p)}var ua="[object AsyncFunction]",IP="[object Function]",xP="[object GeneratorFunction]",SP="[object Proxy]";function TP(p){if(!s(p))return!1;var k=vo(p);return k==IP||k==xP||k==ua||k==SP}var DP=9007199254740991;function $3(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=DP}function Ps(p){return p!=null&&$3(p.length)&&!TP(p)}var rf={};function ft(){}function ko(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var sf=typeof Symbol=="function"&&Symbol.iterator,LP=function(p){return sf&&p[sf]&&p[sf]()};function MP(p,k){for(var B=-1,I=Array(p);++B<p;)I[B]=k(B);return I}function ha(p){return p!=null&&typeof p=="object"}var RP="[object Arguments]";function j3(p){return ha(p)&&vo(p)==RP}var H3=Object.prototype,OP=H3.hasOwnProperty,AP=H3.propertyIsEnumerable,_P=j3(function(){return arguments}())?j3:function(p){return ha(p)&&OP.call(p,"callee")&&!AP.call(p,"callee")},un=Array.isArray;function NP(){return!1}var F3=typeof e=="object"&&e&&!e.nodeType&&e,z3=F3&&!0&&n&&!n.nodeType&&n,PP=z3&&z3.exports===F3,U3=PP?V.Buffer:void 0,$P=U3?U3.isBuffer:void 0,jP=$P||NP,HP=9007199254740991,FP=/^(?:0|[1-9]\d*)$/;function zP(p,k){var B=typeof p;return k=k==null?HP:k,!!k&&(B=="number"||B!="symbol"&&FP.test(p))&&p>-1&&p%1==0&&p<k}var UP="[object Arguments]",VP="[object Array]",qP="[object Boolean]",WP="[object Date]",GP="[object Error]",ZP="[object Function]",YP="[object Map]",QP="[object Number]",KP="[object Object]",JP="[object RegExp]",XP="[object Set]",t$="[object String]",e$="[object WeakMap]",n$="[object ArrayBuffer]",o$="[object DataView]",r$="[object Float32Array]",i$="[object Float64Array]",s$="[object Int8Array]",l$="[object Int16Array]",c$="[object Int32Array]",a$="[object Uint8Array]",d$="[object Uint8ClampedArray]",u$="[object Uint16Array]",h$="[object Uint32Array]",It={};It[r$]=It[i$]=It[s$]=It[l$]=It[c$]=It[a$]=It[d$]=It[u$]=It[h$]=!0,It[UP]=It[VP]=It[n$]=It[qP]=It[o$]=It[WP]=It[GP]=It[ZP]=It[YP]=It[QP]=It[KP]=It[JP]=It[XP]=It[t$]=It[e$]=!1;function f$(p){return ha(p)&&$3(p.length)&&!!It[vo(p)]}function m$(p){return function(k){return p(k)}}var V3=typeof e=="object"&&e&&!e.nodeType&&e,$s=V3&&!0&&n&&!n.nodeType&&n,g$=$s&&$s.exports===V3,lf=g$&&A.process,q3=function(){try{var p=$s&&$s.require&&$s.require("util").types;return p||lf&&lf.binding&&lf.binding("util")}catch{}}(),W3=q3&&q3.isTypedArray,p$=W3?m$(W3):f$,C$=Object.prototype,b$=C$.hasOwnProperty;function v$(p,k){var B=un(p),I=!B&&_P(p),D=!B&&!I&&jP(p),T=!B&&!I&&!D&&p$(p),R=B||I||D||T,_=R?MP(p.length,String):[],q=_.length;for(var Q in p)(k||b$.call(p,Q))&&!(R&&(Q=="length"||D&&(Q=="offset"||Q=="parent")||T&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||zP(Q,q)))&&_.push(Q);return _}var k$=Object.prototype;function y$(p){var k=p&&p.constructor,B=typeof k=="function"&&k.prototype||k$;return p===B}function w$(p,k){return function(B){return p(k(B))}}var B$=w$(Object.keys,Object),E$=Object.prototype,I$=E$.hasOwnProperty;function x$(p){if(!y$(p))return B$(p);var k=[];for(var B in Object(p))I$.call(p,B)&&B!="constructor"&&k.push(B);return k}function cf(p){return Ps(p)?v$(p):x$(p)}function S$(p){var k=-1,B=p.length;return function(){return++k<B?{value:p[k],key:k}:null}}function T$(p){var k=-1;return function(){var I=p.next();return I.done?null:(k++,{value:I.value,key:k})}}function D$(p){var k=cf(p),B=-1,I=k.length;return function D(){var T=k[++B];return T==="__proto__"?D():B<I?{value:p[T],key:T}:null}}function L$(p){if(Ps(p))return S$(p);var k=LP(p);return k?T$(k):D$(p)}function Dn(p){return function(){if(p===null)throw new Error("Callback was already called.");var k=p;p=null,k.apply(this,arguments)}}function fa(p){return function(k,B,I){if(I=ko(I||ft),p<=0||!k)return I(null);var D=L$(k),T=!1,R=0,_=!1;function q(W,X){if(R-=1,W)T=!0,I(W);else{if(X===rf||T&&R<=0)return T=!0,I(null);_||Q()}}function Q(){for(_=!0;R<p&&!T;){var W=D();if(W===null){T=!0,R<=0&&I(null);return}R+=1,B(W.value,W.key,Dn(q))}_=!1}Q()}}function dr(p,k,B,I){fa(k)(p,x(B),I)}function ee(p,k){return function(B,I,D){return p(B,k,I,D)}}function M$(p,k,B){B=ko(B||ft);var I=0,D=0,T=p.length;T===0&&B(null);function R(_,q){_?B(_):(++D===T||q===rf)&&B(null)}for(;I<T;I++)k(p[I],I,Dn(R))}var R$=ee(dr,1/0),yo=function(p,k,B){var I=Ps(p)?M$:R$;I(p,x(k),B)};function ai(p){return function(k,B,I){return p(yo,k,x(B),I)}}function G3(p,k,B,I){I=I||ft,k=k||[];var D=[],T=0,R=x(B);p(k,function(_,q,Q){var W=T++;R(_,function(X,xt){D[W]=xt,Q(X)})},function(_){I(_,D)})}var ma=ai(G3),Z3=O(ma);function di(p){return function(k,B,I,D){return p(fa(B),k,x(I),D)}}var ui=di(G3),af=ee(ui,1),Y3=O(af);function ga(p,k){for(var B=-1,I=p==null?0:p.length;++B<I&&k(p[B],B,p)!==!1;);return p}function O$(p){return function(k,B,I){for(var D=-1,T=Object(k),R=I(k),_=R.length;_--;){var q=R[p?_:++D];if(B(T[q],q,T)===!1)break}return k}}var A$=O$();function js(p,k){return p&&A$(p,k,cf)}function _$(p,k,B,I){for(var D=p.length,T=B+(I?1:-1);I?T--:++T<D;)if(k(p[T],T,p))return T;return-1}function N$(p){return p!==p}function P$(p,k,B){for(var I=B-1,D=p.length;++I<D;)if(p[I]===k)return I;return-1}function pa(p,k,B){return k===k?P$(p,k,B):_$(p,N$,B)}var df=function(p,k,B){typeof k=="function"&&(B=k,k=null),B=ko(B||ft);var I=cf(p),D=I.length;if(!D)return B(null);k||(k=D);var T={},R=0,_=!1,q=Object.create(null),Q=[],W=[],X={};js(p,function(Tt,Dt){if(!un(Tt)){xt(Dt,[Tt]),W.push(Dt);return}var Yt=Tt.slice(0,Tt.length-1),to=Yt.length;if(to===0){xt(Dt,Tt),W.push(Dt);return}X[Dt]=to,ga(Yt,function(gi){if(!p[gi])throw new Error("async.auto task `"+Dt+"` has a non-existent dependency `"+gi+"` in "+Yt.join(", "));Ln(gi,function(){to--,to===0&&xt(Dt,Tt)})})}),Dj(),ie();function xt(Tt,Dt){Q.push(function(){Mn(Tt,Dt)})}function ie(){if(Q.length===0&&R===0)return B(null,T);for(;Q.length&&R<k;){var Tt=Q.shift();Tt()}}function Ln(Tt,Dt){var Yt=q[Tt];Yt||(Yt=q[Tt]=[]),Yt.push(Dt)}function ze(Tt){var Dt=q[Tt]||[];ga(Dt,function(Yt){Yt()}),ie()}function Mn(Tt,Dt){if(!_){var Yt=Dn(function(gi,wf){if(R--,arguments.length>2&&(wf=o(arguments,1)),gi){var Bf={};js(T,function(Mj,Rj){Bf[Rj]=Mj}),Bf[Tt]=wf,_=!0,q=Object.create(null),B(gi,Bf)}else T[Tt]=wf,ze(Tt)});R++;var to=x(Dt[Dt.length-1]);Dt.length>1?to(T,Yt):to(Yt)}}function Dj(){for(var Tt,Dt=0;W.length;)Tt=W.pop(),Dt++,ga(Lj(Tt),function(Yt){--X[Yt]===0&&W.push(Yt)});if(Dt!==D)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Lj(Tt){var Dt=[];return js(p,function(Yt,to){un(Yt)&&pa(Yt,Tt,0)>=0&&Dt.push(to)}),Dt}};function hi(p,k){for(var B=-1,I=p==null?0:p.length,D=Array(I);++B<I;)D[B]=k(p[B],B,p);return D}var $$="[object Symbol]";function j$(p){return typeof p=="symbol"||ha(p)&&vo(p)==$$}var H$=1/0,Q3=nt?nt.prototype:void 0,K3=Q3?Q3.toString:void 0;function uf(p){if(typeof p=="string")return p;if(un(p))return hi(p,uf)+"";if(j$(p))return K3?K3.call(p):"";var k=p+"";return k=="0"&&1/p==-H$?"-0":k}function F$(p,k,B){var I=-1,D=p.length;k<0&&(k=-k>D?0:D+k),B=B>D?D:B,B<0&&(B+=D),D=k>B?0:B-k>>>0,k>>>=0;for(var T=Array(D);++I<D;)T[I]=p[I+k];return T}function z$(p,k,B){var I=p.length;return B=B===void 0?I:B,!k&&B>=I?p:F$(p,k,B)}function U$(p,k){for(var B=p.length;B--&&pa(k,p[B],0)>-1;);return B}function V$(p,k){for(var B=-1,I=p.length;++B<I&&pa(k,p[B],0)>-1;);return B}function q$(p){return p.split("")}var W$="\\ud800-\\udfff",G$="\\u0300-\\u036f",Z$="\\ufe20-\\ufe2f",Y$="\\u20d0-\\u20ff",Q$=G$+Z$+Y$,K$="\\ufe0e\\ufe0f",J$="\\u200d",X$=RegExp("["+J$+W$+Q$+K$+"]");function tj(p){return X$.test(p)}var J3="\\ud800-\\udfff",ej="\\u0300-\\u036f",nj="\\ufe20-\\ufe2f",oj="\\u20d0-\\u20ff",rj=ej+nj+oj,ij="\\ufe0e\\ufe0f",sj="["+J3+"]",hf="["+rj+"]",ff="\\ud83c[\\udffb-\\udfff]",lj="(?:"+hf+"|"+ff+")",X3="[^"+J3+"]",tC="(?:\\ud83c[\\udde6-\\uddff]){2}",eC="[\\ud800-\\udbff][\\udc00-\\udfff]",cj="\\u200d",nC=lj+"?",oC="["+ij+"]?",aj="(?:"+cj+"(?:"+[X3,tC,eC].join("|")+")"+oC+nC+")*",dj=oC+nC+aj,uj="(?:"+[X3+hf+"?",hf,tC,eC,sj].join("|")+")",hj=RegExp(ff+"(?="+ff+")|"+uj+dj,"g");function fj(p){return p.match(hj)||[]}function rC(p){return tj(p)?fj(p):q$(p)}function mj(p){return p==null?"":uf(p)}var gj=/^\s+|\s+$/g;function pj(p,k,B){if(p=mj(p),p&&(B||k===void 0))return p.replace(gj,"");if(!p||!(k=uf(k)))return p;var I=rC(p),D=rC(k),T=V$(I,D),R=U$(I,D)+1;return z$(I,T,R).join("")}var Cj=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,bj=/,/,vj=/(=.+)?(\s*)$/,kj=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function yj(p){return p=p.toString().replace(kj,""),p=p.match(Cj)[2].replace(" ",""),p=p?p.split(bj):[],p=p.map(function(k){return pj(k.replace(vj,""))}),p}function iC(p,k){var B={};js(p,function(I,D){var T,R=L(I),_=!R&&I.length===1||R&&I.length===0;if(un(I))T=I.slice(0,-1),I=I[I.length-1],B[D]=T.concat(T.length>0?q:I);else if(_)B[D]=I;else{if(T=yj(I),I.length===0&&!R&&T.length===0)throw new Error("autoInject task functions require explicit parameters.");R||T.pop(),B[D]=T.concat(q)}function q(Q,W){var X=hi(T,function(xt){return Q[xt]});X.push(W),x(I).apply(null,X)}}),df(B,k)}function hn(){this.head=this.tail=null,this.length=0}function sC(p,k){p.length=1,p.head=p.tail=k}hn.prototype.removeLink=function(p){return p.prev?p.prev.next=p.next:this.head=p.next,p.next?p.next.prev=p.prev:this.tail=p.prev,p.prev=p.next=null,this.length-=1,p},hn.prototype.empty=function(){for(;this.head;)this.shift();return this},hn.prototype.insertAfter=function(p,k){k.prev=p,k.next=p.next,p.next?p.next.prev=k:this.tail=k,p.next=k,this.length+=1},hn.prototype.insertBefore=function(p,k){k.prev=p.prev,k.next=p,p.prev?p.prev.next=k:this.head=k,p.prev=k,this.length+=1},hn.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):sC(this,p)},hn.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):sC(this,p)},hn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},hn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},hn.prototype.toArray=function(){for(var p=Array(this.length),k=this.head,B=0;B<this.length;B++)p[B]=k.data,k=k.next;return p},hn.prototype.remove=function(p){for(var k=this.head;k;){var B=k.next;p(k)&&this.removeLink(k),k=B}return this};function lC(p,k,B){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var I=x(p),D=0,T=[],R=!1;function _(X,xt,ie){if(ie!=null&&typeof ie!="function")throw new Error("task callback must be a function");if(W.started=!0,un(X)||(X=[X]),X.length===0&&W.idle())return m(function(){W.drain()});for(var Ln=0,ze=X.length;Ln<ze;Ln++){var Mn={data:X[Ln],callback:ie||ft};xt?W._tasks.unshift(Mn):W._tasks.push(Mn)}R||(R=!0,m(function(){R=!1,W.process()}))}function q(X){return function(xt){D-=1;for(var ie=0,Ln=X.length;ie<Ln;ie++){var ze=X[ie],Mn=pa(T,ze,0);Mn===0?T.shift():Mn>0&&T.splice(Mn,1),ze.callback.apply(ze,arguments),xt!=null&&W.error(xt,ze.data)}D<=W.concurrency-W.buffer&&W.unsaturated(),W.idle()&&W.drain(),W.process()}}var Q=!1,W={_tasks:new hn,concurrency:k,payload:B,saturated:ft,unsaturated:ft,buffer:k/4,empty:ft,drain:ft,error:ft,started:!1,paused:!1,push:function(X,xt){_(X,!1,xt)},kill:function(){W.drain=ft,W._tasks.empty()},unshift:function(X,xt){_(X,!0,xt)},remove:function(X){W._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!W.paused&&D<W.concurrency&&W._tasks.length;){var X=[],xt=[],ie=W._tasks.length;W.payload&&(ie=Math.min(ie,W.payload));for(var Ln=0;Ln<ie;Ln++){var ze=W._tasks.shift();X.push(ze),T.push(ze),xt.push(ze.data)}D+=1,W._tasks.length===0&&W.empty(),D===W.concurrency&&W.saturated();var Mn=Dn(q(X));I(xt,Mn)}Q=!1}},length:function(){return W._tasks.length},running:function(){return D},workersList:function(){return T},idle:function(){return W._tasks.length+D===0},pause:function(){W.paused=!0},resume:function(){W.paused!==!1&&(W.paused=!1,m(W.process))}};return W}function cC(p,k){return lC(p,1,k)}var fi=ee(dr,1);function wo(p,k,B,I){I=ko(I||ft);var D=x(B);fi(p,function(T,R,_){D(k,T,function(q,Q){k=Q,_(q)})},function(T){I(T,k)})}function mf(){var p=hi(arguments,x);return function(){var k=o(arguments),B=this,I=k[k.length-1];typeof I=="function"?k.pop():I=ft,wo(p,k,function(D,T,R){T.apply(B,D.concat(function(_){var q=o(arguments,1);R(_,q)}))},function(D,T){I.apply(B,[D].concat(T))})}}var aC=function(){return mf.apply(null,o(arguments).reverse())},wj=Array.prototype.concat,Ca=function(p,k,B,I){I=I||ft;var D=x(B);ui(p,k,function(T,R){D(T,function(_){return _?R(_):R(null,o(arguments,1))})},function(T,R){for(var _=[],q=0;q<R.length;q++)R[q]&&(_=wj.apply(_,R[q]));return I(T,_)})},dC=ee(Ca,1/0),uC=ee(Ca,1),hC=function(){var p=o(arguments),k=[null].concat(p);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Hs(p){return p}function mi(p,k){return function(B,I,D,T){T=T||ft;var R=!1,_;B(I,function(q,Q,W){D(q,function(X,xt){X?W(X):p(xt)&&!_?(R=!0,_=k(!0,q),W(null,rf)):W()})},function(q){q?T(q):T(null,R?_:k(!1))})}}function fC(p,k){return k}var ba=ai(mi(Hs,fC)),Fs=di(mi(Hs,fC)),va=ee(Fs,1);function mC(p){return function(k){var B=o(arguments,1);B.push(function(I){var D=o(arguments,1);typeof console=="object"&&(I?console.error&&console.error(I):console[p]&&ga(D,function(T){console[p](T)}))}),x(k).apply(null,B)}}var gC=mC("dir");function pC(p,k,B){B=Dn(B||ft);var I=x(p),D=x(k);function T(_){if(_)return B(_);var q=o(arguments,1);q.push(R),D.apply(this,q)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}R(null,!0)}function gf(p,k,B){B=Dn(B||ft);var I=x(p),D=function(T){if(T)return B(T);var R=o(arguments,1);if(k.apply(this,R))return I(D);B.apply(null,[null].concat(R))};I(D)}function CC(p,k,B){gf(p,function(){return!k.apply(this,arguments)},B)}function bC(p,k,B){B=Dn(B||ft);var I=x(k),D=x(p);function T(_){if(_)return B(_);D(R)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}D(R)}function vC(p){return function(k,B,I){return p(k,I)}}function ka(p,k,B){yo(p,vC(x(k)),B)}function zs(p,k,B,I){fa(k)(p,vC(x(B)),I)}var Us=ee(zs,1);function pf(p){return L(p)?p:i(function(k,B){var I=!0;k.push(function(){var D=arguments;I?m(function(){B.apply(null,D)}):B.apply(null,D)}),p.apply(this,k),I=!1})}function ya(p){return!p}var wa=ai(mi(ya,ya)),Vs=di(mi(ya,ya)),Ba=ee(Vs,1);function kC(p){return function(k){return k==null?void 0:k[p]}}function Bj(p,k,B,I){var D=new Array(k.length);p(k,function(T,R,_){B(T,function(q,Q){D[R]=!!Q,_(q)})},function(T){if(T)return I(T);for(var R=[],_=0;_<k.length;_++)D[_]&&R.push(k[_]);I(null,R)})}function Ej(p,k,B,I){var D=[];p(k,function(T,R,_){B(T,function(q,Q){q?_(q):(Q&&D.push({index:R,value:T}),_())})},function(T){T?I(T):I(null,hi(D.sort(function(R,_){return R.index-_.index}),kC("value")))})}function Cf(p,k,B,I){var D=Ps(k)?Bj:Ej;D(p,k,x(B),I||ft)}var Ea=ai(Cf),qs=di(Cf),Ia=ee(qs,1);function yC(p,k){var B=Dn(k||ft),I=x(pf(p));function D(T){if(T)return B(T);I(D)}D()}var xa=function(p,k,B,I){I=I||ft;var D=x(B);ui(p,k,function(T,R){D(T,function(_,q){return _?R(_):R(null,{key:q,val:T})})},function(T,R){for(var _={},q=Object.prototype.hasOwnProperty,Q=0;Q<R.length;Q++)if(R[Q]){var W=R[Q].key,X=R[Q].val;q.call(_,W)?_[W].push(X):_[W]=[X]}return I(T,_)})},wC=ee(xa,1/0),BC=ee(xa,1),EC=mC("log");function Sa(p,k,B,I){I=ko(I||ft);var D={},T=x(B);dr(p,k,function(R,_,q){T(R,_,function(Q,W){if(Q)return q(Q);D[_]=W,q()})},function(R){I(R,D)})}var IC=ee(Sa,1/0),xC=ee(Sa,1);function SC(p,k){return k in p}function TC(p,k){var B=Object.create(null),I=Object.create(null);k=k||Hs;var D=x(p),T=i(function(_,q){var Q=k.apply(null,_);SC(B,Q)?m(function(){q.apply(null,B[Q])}):SC(I,Q)?I[Q].push(q):(I[Q]=[q],D.apply(null,_.concat(function(){var W=o(arguments);B[Q]=W;var X=I[Q];delete I[Q];for(var xt=0,ie=X.length;xt<ie;xt++)X[xt].apply(null,W)})))});return T.memo=B,T.unmemoized=p,T}var Ta;c?Ta=process.nextTick:l?Ta=setImmediate:Ta=a;var DC=u(Ta);function bf(p,k,B){B=B||ft;var I=Ps(k)?[]:{};p(k,function(D,T,R){x(D)(function(_,q){arguments.length>2&&(q=o(arguments,1)),I[T]=q,R(_)})},function(D){B(D,I)})}function LC(p,k){bf(yo,p,k)}function MC(p,k,B){bf(fa(k),p,B)}var vf=function(p,k){var B=x(p);return lC(function(I,D){B(I[0],D)},k,1)},RC=function(p,k){var B=vf(p,k);return B.push=function(I,D,T){if(T==null&&(T=ft),typeof T!="function")throw new Error("task callback must be a function");if(B.started=!0,un(I)||(I=[I]),I.length===0)return m(function(){B.drain()});D=D||0;for(var R=B._tasks.head;R&&D>=R.priority;)R=R.next;for(var _=0,q=I.length;_<q;_++){var Q={data:I[_],priority:D,callback:T};R?B._tasks.insertBefore(R,Q):B._tasks.push(Q)}m(B.process)},delete B.unshift,B};function OC(p,k){if(k=ko(k||ft),!un(p))return k(new TypeError("First argument to race must be an array of functions"));if(!p.length)return k();for(var B=0,I=p.length;B<I;B++)x(p[B])(k)}function Da(p,k,B,I){var D=o(p).reverse();wo(D,k,B,I)}function La(p){var k=x(p);return i(function(I,D){return I.push(function(R,_){if(R)D(null,{error:R});else{var q;arguments.length<=2?q=_:q=o(arguments,1),D(null,{value:q})}}),k.apply(this,I)})}function AC(p){var k;return un(p)?k=hi(p,La):(k={},js(p,function(B,I){k[I]=La.call(this,B)})),k}function _C(p,k,B,I){Cf(p,k,function(D,T){B(D,function(R,_){T(R,!_)})},I)}var NC=ai(_C),kf=di(_C),PC=ee(kf,1);function $C(p){return function(){return p}}function Ma(p,k,B){var I=5,D=0,T={times:I,intervalFunc:$C(D)};function R(W,X){if(typeof X=="object")W.times=+X.times||I,W.intervalFunc=typeof X.interval=="function"?X.interval:$C(+X.interval||D),W.errorFilter=X.errorFilter;else if(typeof X=="number"||typeof X=="string")W.times=+X||I;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof p=="function"?(B=k||ft,k=p):(R(T,p),B=B||ft),typeof k!="function")throw new Error("Invalid arguments for async.retry");var _=x(k),q=1;function Q(){_(function(W){W&&q++<T.times&&(typeof T.errorFilter!="function"||T.errorFilter(W))?setTimeout(Q,T.intervalFunc(q)):B.apply(null,arguments)})}Q()}var jC=function(p,k){k||(k=p,p=null);var B=x(k);return i(function(I,D){function T(R){B.apply(null,I.concat(R))}p?Ma(p,T,D):Ma(T,D)})};function HC(p,k){bf(fi,p,k)}var Ra=ai(mi(Boolean,Hs)),Ws=di(mi(Boolean,Hs)),Oa=ee(Ws,1);function FC(p,k,B){var I=x(k);ma(p,function(T,R){I(T,function(_,q){if(_)return R(_);R(null,{value:T,criteria:q})})},function(T,R){if(T)return B(T);B(null,hi(R.sort(D),kC("value")))});function D(T,R){var _=T.criteria,q=R.criteria;return _<q?-1:_>q?1:0}}function zC(p,k,B){var I=x(p);return i(function(D,T){var R=!1,_;function q(){var Q=p.name||"anonymous",W=new Error('Callback function "'+Q+'" timed out.');W.code="ETIMEDOUT",B&&(W.info=B),R=!0,T(W)}D.push(function(){R||(T.apply(null,arguments),clearTimeout(_))}),_=setTimeout(q,k),I.apply(null,D)})}var Ij=Math.ceil,xj=Math.max;function Sj(p,k,B,I){for(var D=-1,T=xj(Ij((k-p)/(B||1)),0),R=Array(T);T--;)R[I?T:++D]=p,p+=B;return R}function Aa(p,k,B,I){var D=x(B);ui(Sj(0,p,1),k,D,I)}var UC=ee(Aa,1/0),VC=ee(Aa,1);function qC(p,k,B,I){arguments.length<=3&&(I=B,B=k,k=un(p)?[]:{}),I=ko(I||ft);var D=x(B);yo(p,function(T,R,_){D(k,T,R,_)},function(T){I(T,k)})}function WC(p,k){var B=null,I;k=k||ft,Us(p,function(D,T){x(D)(function(R,_){arguments.length>2?I=o(arguments,1):I=_,B=R,T(!R)})},function(){k(B,I)})}function GC(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function yf(p,k,B){B=Dn(B||ft);var I=x(k);if(!p())return B(null);var D=function(T){if(T)return B(T);if(p())return I(D);var R=o(arguments,1);B.apply(null,[null].concat(R))};I(D)}function ZC(p,k,B){yf(function(){return!p.apply(this,arguments)},k,B)}var YC=function(p,k){if(k=ko(k||ft),!un(p))return k(new Error("First argument to waterfall must be an array of functions"));if(!p.length)return k();var B=0;function I(T){var R=x(p[B++]);T.push(Dn(D)),R.apply(null,T)}function D(T){if(T||B===p.length)return k.apply(null,arguments);I(o(arguments,1))}I([])},Tj={apply:r,applyEach:Z3,applyEachSeries:Y3,asyncify:C,auto:df,autoInject:iC,cargo:cC,compose:aC,concat:dC,concatLimit:Ca,concatSeries:uC,constant:hC,detect:ba,detectLimit:Fs,detectSeries:va,dir:gC,doDuring:pC,doUntil:CC,doWhilst:gf,during:bC,each:ka,eachLimit:zs,eachOf:yo,eachOfLimit:dr,eachOfSeries:fi,eachSeries:Us,ensureAsync:pf,every:wa,everyLimit:Vs,everySeries:Ba,filter:Ea,filterLimit:qs,filterSeries:Ia,forever:yC,groupBy:wC,groupByLimit:xa,groupBySeries:BC,log:EC,map:ma,mapLimit:ui,mapSeries:af,mapValues:IC,mapValuesLimit:Sa,mapValuesSeries:xC,memoize:TC,nextTick:DC,parallel:LC,parallelLimit:MC,priorityQueue:RC,queue:vf,race:OC,reduce:wo,reduceRight:Da,reflect:La,reflectAll:AC,reject:NC,rejectLimit:kf,rejectSeries:PC,retry:Ma,retryable:jC,seq:mf,series:HC,setImmediate:m,some:Ra,someLimit:Ws,someSeries:Oa,sortBy:FC,timeout:zC,times:UC,timesLimit:Aa,timesSeries:VC,transform:qC,tryEach:WC,unmemoize:GC,until:ZC,waterfall:YC,whilst:yf,all:wa,allLimit:Vs,allSeries:Ba,any:Ra,anyLimit:Ws,anySeries:Oa,find:ba,findLimit:Fs,findSeries:va,forEach:ka,forEachSeries:Us,forEachLimit:zs,forEachOf:yo,forEachOfSeries:fi,forEachOfLimit:dr,inject:wo,foldl:wo,foldr:Da,select:Ea,selectLimit:qs,selectSeries:Ia,wrapSync:C};e.default=Tj,e.apply=r,e.applyEach=Z3,e.applyEachSeries=Y3,e.asyncify=C,e.auto=df,e.autoInject=iC,e.cargo=cC,e.compose=aC,e.concat=dC,e.concatLimit=Ca,e.concatSeries=uC,e.constant=hC,e.detect=ba,e.detectLimit=Fs,e.detectSeries=va,e.dir=gC,e.doDuring=pC,e.doUntil=CC,e.doWhilst=gf,e.during=bC,e.each=ka,e.eachLimit=zs,e.eachOf=yo,e.eachOfLimit=dr,e.eachOfSeries=fi,e.eachSeries=Us,e.ensureAsync=pf,e.every=wa,e.everyLimit=Vs,e.everySeries=Ba,e.filter=Ea,e.filterLimit=qs,e.filterSeries=Ia,e.forever=yC,e.groupBy=wC,e.groupByLimit=xa,e.groupBySeries=BC,e.log=EC,e.map=ma,e.mapLimit=ui,e.mapSeries=af,e.mapValues=IC,e.mapValuesLimit=Sa,e.mapValuesSeries=xC,e.memoize=TC,e.nextTick=DC,e.parallel=LC,e.parallelLimit=MC,e.priorityQueue=RC,e.queue=vf,e.race=OC,e.reduce=wo,e.reduceRight=Da,e.reflect=La,e.reflectAll=AC,e.reject=NC,e.rejectLimit=kf,e.rejectSeries=PC,e.retry=Ma,e.retryable=jC,e.seq=mf,e.series=HC,e.setImmediate=m,e.some=Ra,e.someLimit=Ws,e.someSeries=Oa,e.sortBy=FC,e.timeout=zC,e.times=UC,e.timesLimit=Aa,e.timesSeries=VC,e.transform=qC,e.tryEach=WC,e.unmemoize=GC,e.until=ZC,e.waterfall=YC,e.whilst=yf,e.all=wa,e.allLimit=Vs,e.allSeries=Ba,e.any=Ra,e.anyLimit=Ws,e.anySeries=Oa,e.find=ba,e.findLimit=Fs,e.findSeries=va,e.forEach=ka,e.forEachSeries=Us,e.forEachLimit=zs,e.forEachOf=yo,e.forEachOfSeries=fi,e.forEachOfLimit=dr,e.inject=wo,e.foldl=wo,e.foldr=Da,e.select=Ea,e.selectLimit=qs,e.selectSeries=Ia,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(Su,Su.exports);var M2={exports:{}},Tu=M2.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var c=parseInt(i,t);return c!==1/0&&c>=Math.pow(2,n)?Tu(n,t):i};Tu.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Tu(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var R2=co,Jk=D2,Xk=L2,Kl=en,Du=Su.exports,ty=M2.exports,O2=qo.ACTIONS,A2=Pt;function Pt(n,t){if(R2.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}R2.mixin(Pt),Pt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Pt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Pt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||ty();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Pt.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);Du.parallel([function(i){Du.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Du.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Pt.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?O2.presenceSubscribe:O2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Pt.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._receiveUpdate=function(n,t){var e=Kl.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Kl.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Pt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Pt.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()}},Pt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Pt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Pt.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Pt.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Pt.prototype._callbackOrEmit=function(n,t){if(t)return Kl.nextTick(t,n);n&&this.emit("error",n)},Pt.prototype._createLocalPresence=function(n){return new Jk(this,n)},Pt.prototype._createRemotePresence=function(n){return new Xk(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=Kl.callEach(n,t);!e&&t&&this.emit("error",t)};var Gi=D2,_2=Wl,ey=en,N2=_2.CODES,ny=on;function on(n,t){Gi.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()}on.prototype=Object.create(Gi.prototype),on.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:N2.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,Gi.prototype.submit.call(this,n,t)},on.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),Gi.prototype.destroy.call(this,n)},on.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={})})}},on.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)},on.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},on.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},on.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},on.prototype._message=function(){var n=Gi.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},on.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!ey.supportsPresence(o))throw new _2(N2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var P2={};(function(n){var t=Vi,e=Wl,o=en,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=t.map[c];if(a==null||typeof a!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=t.map[a.type];if(!u)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=t.map[l.type];if(!a)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new e(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=t.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var C=m.p,v=u,y=0;y<C.length;y++){var E=C[y];Object.prototype.toString.call(v)=="[object Array]"?C[y]=+E:v.constructor===Object&&(C[y]=E.toString()),v=v[E]}f<a.length-1&&(u=t.defaultType.apply(u,[m]))}}}}})(P2);var Zi=L2,oy=P2,ry=Pe;function Pe(n,t){Zi.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()}Pe.prototype=Object.create(Zi.prototype),Pe.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},Pe.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),Zi.prototype.destroy.call(this,n)},Pe.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)},Pe.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))}})}},Pe.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},Zi.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Zi.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},Pe.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)}},Pe.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++):oy.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},Pe.prototype._startCachingOps=function(){this._opCache=[]},Pe.prototype._stopCachingOps=function(){this._opCache=null},Pe.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var $2=A2,iy=ny,sy=ry;function Or(n,t,e){var o=Or.channel(t,e);$2.call(this,n,o),this.collection=t,this.id=e}var ly=Or;Or.prototype=Object.create($2.prototype),Or.channel=function(n,t){return n+"."+t},Or.prototype._createLocalPresence=function(n){return new iy(this,n)},Or.prototype._createRemotePresence=function(n){return new sy(this,n)};var cy=ay;function ay(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var dy=cy,j2=co,H2=Yi;function Yi(n,t,e,o,r){if(j2.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}j2.mixin(Yi),Yi.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Yi.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Yi.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new dy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var F2=H2,uy=en,hy=qo.ACTIONS,fy=Lu;function Lu(n,t,e,o,r,i){if(F2.call(this,n,t,e,o,i),!uy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}Lu.prototype=Object.create(F2.prototype),Lu.prototype._message=function(){return{a:hy.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var z2=H2,my=en,gy=qo.ACTIONS,py=Mu;function Mu(n,t,e,o,r,i){if(z2.call(this,n,t,e,o,i),!my.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Mu.prototype=Object.create(z2.prototype),Mu.prototype._message=function(){return{a:gy.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Cy=Uk,by=Zk,vy=A2,U2=ly,ky=fy,yy=py,V2=co,Ar=Wl,pt=qo.ACTIONS,q2=Vi,rn=en,Qi=k2,Ki=Ar.CODES;function W2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var wy=J;function J(n){V2.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=W2(n),this.bindToSocket(n)}V2.mixin(J),J.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=W2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Qi.warn("Failed to parse message",o);return}e.debug&&Qi.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){rn.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},J.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=G2(n.error,n),delete n.error),n.a){case pt.initLegacy:return this._handleLegacyInit(n);case pt.handshake:return this._handleHandshake(t,n);case pt.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case pt.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case pt.queryUnsubscribe:return;case pt.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 pt.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case pt.bulkSubscribe:case pt.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case pt.snapshotFetch:case pt.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case pt.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case pt.subscribe:case pt.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case pt.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case pt.presence:return this._handlePresence(t,n);case pt.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case pt.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case pt.presenceRequest:return this._handlePresenceRequest(t,n);case pt.pingPong:return this._handlePingPong(t);default:Qi.warn("Ignoring unrecognized message",n)}};function G2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}J.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](G2(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Qi.error("Invalid bulk message",t)},J.prototype._reset=function(){this.agent=null},J.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 Ar(Ki.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},J.prototype.startBulk=function(){this.bulk||(this.bulk={})},J.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},J.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var c=e[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var a=r[s];this.send({a:n,c:t,d:s,v:a})}else i&&this.send({a:"b"+n,c:t,b:r})}},J.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},J.prototype.sendFetch=function(n){return this._sendActions(pt.fetch,n,n.version)},J.prototype.sendSubscribe=function(n){return this._sendActions(pt.subscribe,n,n.version)},J.prototype.sendUnsubscribe=function(n){return this._sendActions(pt.unsubscribe,n)},J.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:pt.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)},J.prototype.send=function(n){this.debug&&Qi.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},J.prototype.ping=function(){if(!this.canSend)throw new Ar(Ki.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:pt.pingPong};this.send(n)},J.prototype.close=function(){this.socket.close()},J.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},J.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new Cy(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},J.prototype._destroyDoc=function(n){!n._wantsDestroy||(rn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},J.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},J.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new by(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},J.prototype._destroyQuery=function(n){delete this.queries[n.id]},J.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(pt.queryFetch,n,t,e,o)},J.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(pt.querySubscribe,n,t,e,o)},J.prototype.hasPending=function(){return!!(this._firstDoc(Jl)||this._firstQuery(Jl)||this._firstSnapshotRequest())};function Jl(n){return n.hasPending()}J.prototype.hasWritePending=function(){return!!this._firstDoc(By)};function By(n){return n.hasWritePending()}J.prototype.whenNothingPending=function(n){var t=this._firstDoc(Jl);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Jl);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}rn.nextTick(n)},J.prototype._nothingPendingRetry=function(n){var t=this;return function(){rn.nextTick(function(){t.whenNothingPending(n)})}},J.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},J.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},J.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},J.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new ky(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new yy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},J.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},J.prototype._initializeHandshake=function(){this.send({a:pt.handshake,id:this.id})},J.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},J.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},J.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Ar(Ki.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(q2.map[n.type]!==q2.defaultType)return this.emit("error",new Ar(Ki.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Ar(Ki.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},J.prototype.getPresence=function(n){var t=this,e=rn.digOrCreate(this._presences,n,function(){return new vy(t,n)});return e._wantsDestroy=!1,e},J.prototype.getDocPresence=function(n,t){var e=U2.channel(n,t),o=this,r=rn.digOrCreate(this._presences,e,function(){return new U2(o,n,t)});return r._wantsDestroy=!1,r},J.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},J.prototype._addPresence=function(n){rn.digOrCreate(this._presences,n.channel,function(){return n})},J.prototype._handlePresenceSubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},J.prototype._handlePresenceUnsubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},J.prototype._handlePresence=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},J.prototype._handlePresenceRequest=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Z2=wy,Ey=Vi;const Xl={err:1001,msg:"user auth error",name:"AuthError"},Iy={err:1002,msg:"you don't have required permission",name:"PermissionError"},Ru={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ji={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},xy={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Sy={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Xi="x-live-editor-token",tc="x-live-editor-base-url",ae=w("auth-connection");function Ty(n){try{n()}catch(t){ae.error(t)}}class Dy{constructor(t,e){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new Ef.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return Do(this.getBaseURL())}async auth(t){d(ae,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Xi]:t.token,[tc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[tc]:Do(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new E9.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Z2.prototype),d(ae,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},Z2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,ae.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){ae.error(t),setTimeout(()=>this.handleAuthError(),0)}}else ae.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(Xl.msg);t.code=Xl.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ji.msg);t.code=Ji.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===Xl.err)ae.warn("auth error"),this.handleAuthError();else if(o===Ru.err)ae.warn(Ru.msg),this.emitMaxUsersError();else if(o===Ji.err){ae.warn(Ji.msg);try{this.emitRequestReloadError()}catch(r){ae.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else ae.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return d(ae,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(d(ae,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){d(ae,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){d(ae,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),Ty(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}w("utils/file");function Ly(){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}Ly();async function My(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new I9.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return Do(i)}const kn=w("sharedb-doc/client");class Ry{constructor(t,e,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(kn,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),kn.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;Ey.register(Zs.type),this.connection=new Dy(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(kn,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[Xi]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=C=>{kn.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await My(e),a=await this.getFileUrlByHash(t,c,e.name,e.size,o);if(a)return r(-1),a;let u=t;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${e.size}`),f.append("file-hash",c),f.append("file",e,e.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return kn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(kn,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Xi]:this.connection.token},e,o);return d(kn,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),d(kn,o,"no token"),c.headers={...c.headers,[Xi]:o,[tc]:this.connection.getBase64BaseURL()};try{return await w9.default(t,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(kn,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions`,o=await this.request(e),r=o.data.versions,i=o.data.latest;return i&&r.findIndex(s=>s.version===i)===-1&&r.unshift({version:-1,tag:"",published:!1}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=B9.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(kn,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${Do(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function Oy(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const Ou=w("block-ids");class Ay{constructor(){h(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);d(Ou,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);d(Ou,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=N(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class _y{constructor(){h(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new Ay,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(Ou,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Y2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Nt=w("op-parser");function _r(n){return n==="blocks"?"root":n}class Ny{constructor(t,e){h(this,"updatingBlockDataDeltaMap",new Map);h(this,"blockIds",new _y);this.handler=t,this.local=e}onDeleteBlock(t,e){const o=this.blockIds.getBlockId(t,e);this.blockIds.onDeleteBlock(t,e);const r=this.updatingBlockDataDeltaMap.get(o);r&&(Nt.debug(`ignore update object data before delete block: ${JSON.stringify(r)}`),this.updatingBlockDataDeltaMap.delete(o)),this.handler.onDeleteBlock(_r(t),e,this.local)}onInsertBlock(t,e,o){this.blockIds.onInsertBlock(t,e),this.handler.onInsertBlock(_r(t),e,o,this.local)}onUpdateBlockText(t,e,o){this.handler.onUpdateBlockText(_r(t),e,o,this.local)}onDeleteBlockData(t,e,o){const r=this.blockIds.getBlockId(t,e);let i=this.updatingBlockDataDeltaMap.get(r);i||(i=new Y2,this.updatingBlockDataDeltaMap.set(r,i)),i.delete(o)}onInsertBlockData(t,e,o,r){const i=this.blockIds.getBlockId(t,e);let s=this.updatingBlockDataDeltaMap.get(i);s||(s=new Y2,this.updatingBlockDataDeltaMap.set(i,s)),s.insert(o,r)}executeUpdateBlockDataActions(){Array.from(this.updatingBlockDataDeltaMap.entries()).forEach(([t,e])=>{const{containerId:o,blockIndex:r}=this.blockIds.getBlockIndexById(t);this.handler.onUpdateBlockData(_r(o),r,e.toDocBlockDelta(),this.local)})}}class Q2{}class Au{constructor(t){h(this,"key");this.key=t}}function Py(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d(Nt,s.id,"block id is required"),d(Nt,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return e.onInsertBlock(n,r,s),!0}function _u(n,t,e,o){if(e==="upsert"&&Py(n,t,o))return;d(Nt,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d(Nt,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),d(Nt,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d(Nt,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(Nt,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(Nt,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(Nt,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&e==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&e==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&e==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else e==="remove"&&a.r&&s.push(new Au(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new Q2),e==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(Nt,typeof l=="string","data is not string"),d(Nt,l!=="text","data !== 'text'"),d(Nt,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];e==="remove"&&a.r&&s.push(new Au(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Q2?o.onDeleteBlock(n,i):l instanceof Au?o.onDeleteBlockData(n,i,l.key):d(Nt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function $y(n,t,e,o){Nt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function jy(n,t,e,o){const r=n[1],i=n[2];d(Nt,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(Nt,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?Nt.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&o.onUpdateComment(r,e.local):i.i?t==="upsert"&&o.onCreateComment(r,e.local):i.r?t==="remove"&&o.onDeleteComment(r,e.local):Nt.error(`unknown comment op, ${JSON.stringify(n)}`)}function Nu(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Nu(l,t,e,o)});return}const i=r;if(d(Nt,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){$y(n);return}if(i==="comments"){jy(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{_u(s,l,t,e)}):n.slice(1).forEach(l=>{_u(s,l,t,e)});else if(typeof n[1]=="object"){const l=n[1];l.r&&t==="remove"&&o.onDeleteContainer(_r(s),e.local),l.i&&t==="upsert"&&o.onCreateContainer(_r(s),l.i,e.local)}else d(Nt,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),_u(s,n.slice(1),t,e)}function K2(n,t,e){const o=new Ny(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Y.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Nu(c,i,o,t)}):Nu(s,i,o,t)}o.executeUpdateBlockDataActions()}const Hy=w("sharedb-comments");function Pu(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(Hy,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),Y.default(e)}function J2(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function $u(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const Bt=w("sharedb-doc/doc-container"),X2="ot-json1";Zs.type.registerSubtype(Ik.type),Zs.type.name=X2,Zs.type.invert=null;class ts extends vi{constructor(e,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new Bk);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});h(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});h(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,c])=>{if(!Gs.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){Bt.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(Bt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),Bt.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(Bt.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));h(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,X2,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(e,o)=>{const r=[lo(e),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async e=>{const o=[lo(e),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(e,o,r)=>{const i=[lo(e),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(e,o)=>{const r=[lo(e),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[lo(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(e,o,r)=>{const i=[lo(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(e,o,r)=>{if(this.destroyed){Bt.warn("handleOp: destroyed");return}K2(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(Bt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new Ry(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new ts(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||Oy())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw Bt.error(o),Bt.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return zi(this.data())}getContainerBlocks(e){const o=this.data();d(Bt,o,"no doc data");const r=o[lo(e)];return d(Bt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=this.data();d(Bt,r,"no doc data");const i=r[lo(e)];d(Bt,i,`no container data: ${e}`);const s=i[o];return d(Bt,s,`no block data: ${o}`),Y.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Bt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=oe.apply(s,r);return d(Bt,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=Y.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>J2(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Pu(o)}localCreateComment(e,o){const r=$u(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=$u(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Rr(e),o,r)})}onInsertBlock(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockData(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockText(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Rr(e),o,r,i)})}onDeleteContainer(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Rr(e),o)})}onCreateContainer(e,o,r){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Rr(e),o,r)})}onDeleteComment(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return zi(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return zi(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:zi(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:zi(r),versionData:i}}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){K2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class t0{constructor(t){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",Qt.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));h(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const e0=w("remote-cursor-decorator");class ju{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];d(e0,typeof s=="string","invalid path containerId"),d(e0,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),a=ce(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const C=f.map(y=>({id:N(),type:"remote-cursor",name:y.user.displayName,time:y.time,rainbowIndex:y.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class n0 extends Wt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Ct(Cr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=z(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function Fy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).addListener("change",t)}function zy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).removeListener("change",t)}const KH="",Uy={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Vy={colorPalette:{colorDesc:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};S.mergeLang({"zh-CN":Uy,"en-US":Vy});const JH="";w("button");function Vn(n,t,e,o,r){const i=b("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&M(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function o0(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const uo=w("filterable-list");function qy(n){var e;const t=b("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(b("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&M(t,"selected"),t}function r0(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(qy(e))}),t}function i0(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Wy(n,t){const e=b("div",["filterable-list"],null),o=b("div",["filter"],e),r=b("div",["filter-container"],o),i=b("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=b("div",["list"],e),l=r0(i0(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function s0(n,t,e){const o=n.querySelector(".list");d(uo,o,"no list root");const r=r0(i0(t,e)),i=o.querySelector(".list-root");if(d(uo,i,"no exists menu"),Ii(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(uo,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class Gy{constructor(t,e){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",t=>{this.processKeyDown(t)});h(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");d(uo,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});h(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=Wy(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,s0(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),s0(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(t){var e;if(t.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class Zy extends Gy{constructor(e,o,r){super(e,r);h(this,"tippyInstance");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.tippyInstance=Sf.default(o,{interactive:!0,content:this.root,trigger:"manual",triggerTarget:null,hideOnClick:!0,arrow:!1,theme:"dropdown-list",offset:[0,0],onHide:this.handleHide,onShow:this.handleShow,onShown:this.handleShown})}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.tippyInstance.setProps({getReferenceClientRect:()=>e.getBoundingClientRect()}),this.reset(),this.tippyInstance.show(),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.tippyInstance.hide()}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.tippyInstance.hide()}}const XH="",tF="";function Yy(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const eF="",Nr=w("ui-command-bar-base"),Qy={itemElementTag:"div",tippyArrow:!1},nf=class extends Wt.TypedEmitter{constructor(e,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"options");h(this,"id");h(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close();return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close();else if(e.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",e=>{e.target instanceof Element&&(this.isInCommandBar(e.target)||this.close())});h(this,"handleHidden",()=>{this.close(),this.emit("close",this),sm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&M(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&im(this.id)});h(this,"handleItemMouseEnter",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(F(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close())}});h(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=_n(r);if(!vt(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...Qy,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(){this.subBar&&this.subBar.close(),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),e}destroy(){var e;this.close(),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-1;for(;;){const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(e){let o=e+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&F(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&F(s,"selected")}const r=this.getItemElementById(e);r?(M(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close();return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=nf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,F(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),M(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&vt(o,e)||vt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=b(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=e.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return d(Nr,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return d(Nr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return d(Nr,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return d(Nr,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(lt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=b("div",["editor-command-bar-root"],null),r=b("div",["editor-command-bar"],o);return e.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;d(Nr,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Nr,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Pr=nf;h(Pr,"commandBarCreators",new Map),w("ui-command-bar");class ec extends Pr{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=Sf.default(e,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(){var e;super.close(),this.isVisible&&((e=this.tippyInstance)==null||e.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}function Ky(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const Jy={"insert-hr":{shortcut:"/hr"},"insert-uml":{shortcut:"/uml"},"insert-table":{shortcut:"/table"},"insert-image":{shortcut:"/image"},"insert-code":{shortcut:"/code"},"insert-link":{shortcut:"/link"},"insert-drawio":{shortcut:"/uml"},"insert-video":{shortcut:"/video"},"insert-audio":{shortcut:"/audio"},"insert-math":{shortcut:"/math"},"insert-webPage":{shortcut:"/web"},"insert-bilibili":{shortcut:"/bilibili"},"insert-youku":{shortcut:"/youku"},"insert-figma":{shortcut:"/figma"},"insert-modao":{shortcut:"/modao"},"insert-tencent":{shortcut:"/tencent"},"insert-unordered":{shortcut:"/bl"},"insert-ordered":{shortcut:"/nu"},"insert-checkbox":{shortcut:"/todo"},"insert-quote":{shortcut:"/quote"},...Ky()};function l0(n){var t,e,o;return(o=(e=n.shortcut)!=null?e:(t=Jy[n.id])==null?void 0:t.shortcut)!=null?o:""}const c0=`<?xml version="1.0" ?>
27
27
  <svg
28
28
  fill="currentColor"
29
29
  xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">