@ones-editor/editor 0.0.3-beta.22 → 0.0.3-beta.24

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 Fb(n,t){return t.blocks.root.map(r=>e2(n,r,t)).join(`
24
24
  `)}const Ll=y("action-helper");function ro(n,t){const e=H(t),o=V(e),r=K(t);return n.doc.getBlockData(o,r)}function ke(n,t){d(Ll,j(n,t),"not a text kind block");const o=ro(n,t).text;return d(Ll,o,"no text in block"),o}function Ml(n,t,e){return Ae(ke(n,t),e).left}function r2(n,t){const e=z(t);d(Ll,e,"no parent block");const o=ke(n,e),r=Dm(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 zb=y("get-text-position");function Tr(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Vt||d(zb,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=K(r),s=H(r),l=V(s),{offset:c}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const Ni=y("insert-text");function i2(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(d(Ni,r,"no block data"),d(Ni,r.text,"no block text"),ce(r.text)===0)return d(Ni,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Kt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function Vb(n,t,e){const o=H(t),r=V(o),i=K(t);return i2(n,r,i,e)}function s2(n,t,e,o){const r=H(t),i=V(r),s=K(t),l=Vb(n,t,e),c=kl(e,o,l!=null?l:null);return n.doc.localUpdateBlockText(i,s,c),ke(n,t)}function l2(n,t,e,o){const r=H(t),i=V(r),s=K(t),l=kl(e," ",o);return n.doc.localUpdateBlockText(i,s,l),ke(n,t)}function z1(n,t,e,o,r){const i=n.doc.getBlockData(e,o);d(Ni,i,"no block data"),d(Ni,i.text,"no block text");const s=i2(n,e,o,r),l=kl(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),ke(n,n.getBlockById(i.id))}function V1(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Tr(n);z1(n,t,e,o,r)}const Rl=y("update-composition-text");function c2(n){const t=n.selection.range.start;t instanceof Vt||d(Rl,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);d(Rl,j(n,o),"not a text kind block");const r=H(o),i=V(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);pl(n,Ro(o),e,c,l.text)}function a2(n){UC(n)}function Dr(n,t,e,o,r){return n.doc.localInsertBlock(t,e,o,r),n.getBlockById(o.id)}const Al=y("delete-block-text");function U1(n,t,e,o){d(Al,j(n,t),"block is not a text kind block");const r=H(t),i=V(r),s=K(t),l=n.doc.getBlockData(i,s);d(Al,l,"no block data in doc"),d(Al,l.text,"no text data in text block");let c=e;fe(t,e)||(c=Po(t,c));let a=e+o;d(Al,a<=Z(n,t),`invalid offset and count: ${e}, ${o}`),fe(t,a)||(a=Ir(t,a));const u=a-c,f=Eg(c,u);return n.doc.localUpdateBlockText(i,s,f),u}const q1=y("break-text-block");function d2(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Pi(n,t,e,o){d(q1,j(n,t),`block is not a text kind block: ${it(t)}`),d(q1,e>=0&&e<=Z(n,t),`invalid offset: ${e}`);const r=H(t),i=V(r),s=K(t),l=o!=null&&o.copyBlockAttributes?d2(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},w=Ot(n,t.id,0),E=Dr(n,i,C,v,w);return{block:t,newBlock:E}}d(q1,fe(t,e),"not a valid offset");const c=ke(n,t),{right:a}=Ae(c,e),u=ce(a);u>0&&U1(n,t,e,u);const f={...jn(a),...l,...o==null?void 0:o.newBlockData},m=Dr(n,i,s+1,f,Ot(n,f.id,0));return{block:t,newBlock:m}}const Ub=y("prepare-insert-new-block");function qb(n,t,e){if(t&&e!==void 0&&e!==null){const a=n.getContainerById(t),u=Rt(a);return d(Ub,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=V(H(r)),e=K(r),!j(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=Pi(n,r,s).newBlock;return{containerId:t,blockIndex:K(c)}}const Wb=y("auto-insert-block");function u2(n,t,e,o,r){const i=qb(n,e,o);d(Wb,i,`not an valid insert position: ${n.selection.range}`);const s={blockId:t.id,offset:0},l={anchor:s,focus:s};return Dr(n,i.containerId,i.blockIndex,t,r!=null?r:l)}const Gb=y("range-in-block");function h2(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 f2(n,t){let e;const o=gt(t);if(o)e=Ot(n,o,Z(n,o));else{const r=ht(t);d(Gb,r,"no prev and next block while deleting a block"),e=Ot(n,r,0)}return e}const Zb=y("delete-block");function Ol(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Ol(n,i,e)})}))}function W1(n,t,e){const o=H(t),r=V(o),i=K(t),s=n.doc.getBlockData(r,i);return d(Zb,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ut(n,{anchor:e.start,focus:e.end})),s}function G1(n,t,e){const o=H(t);Ve(o)===1&&n.insertTextBlock("",V(o),0);let r=e?no(n,e):null;if(!r){const l=n.selection.range;h2(t,l)?r=f2(n,t):r=l}const i=W1(n,t,r),s=[];return Ol(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i}function Yb(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Ol(n,r,e)}),n.doc.localDeleteChildContainers(e)}function m2(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Ol(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Z1=y("merge-text-block");function g2(n,t,e){d(Z1,j(n,t),"only text block can be merged"),d(Z1,j(n,e),"only text block can be merged");const o=ro(n,t),r=ro(n,e),i=o.text,s=r.text;d(Z1,i&&s,"block data has no text");const l=H(t),c=V(l),a=K(t),u=Z(n,t),f=z1(n,s,c,a,u),m=Ot(n,t,ce(i));return G1(n,e,m),f}const Cn=y("clear-selected-contents");function _l(n,t){d(Cn,j(n,t.block),"not a text kind block");const{start:e,end:o}=t;d(Cn,e.isSimple(),"not a simple block position"),d(Cn,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;d(Cn,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function p2(n,t,e){const o=V(t),r=Rt(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 Qb(n,t){const{block:e,start:o,end:r}=t;if(j(n,e)){_l(n,t);return}if(Te(e)||o.isSimple()){d(Cn,r.isSimple(),"invalid range");const s=H(e),l=K(e),c=n.insertTextBlock("",V(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}d(Cn,ct(n,e),"invalid block kind"),d(Cn,!o.isSimple()&&!r.isSimple(),"invalid range"),yr(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{p2(n,s,{focus:l===0})})}function Kb(n){const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(d(Cn,e.length>0,"no selected block"),e.length===1){Qb(n,e[0]);return}const o=e[0],r=o.block,i=H(r);d(Cn,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(j(n,r)){_l(n,o);const u=Ot(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),j(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(j(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)){p2(n,i,{focus:!0});return}const c=gt(r),a=ht(l);d(Cn,c||a,"no prev or next block"),e.forEach(u=>n.deleteBlock(u.block))}function Y1(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n),Kb(n),n.emit("afterClearSelection",n)})}function C2(n,t,e){const o=H(t),r=V(o),i=K(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),ke(n,t)}function b2(n,t,e){const o=n.getBlockText(t),r=ne.diff(o,e);C2(n,t,r)}function Nl(n,t,e){const o=ke(n,t),r=typeof e=="string"?Oi(e):e,i=ne.diff(o,r);return C2(n,t,i)}const $i=y("update-block-data");function Pl(n,t,e,o){const r=H(t),i=V(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;$i.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(e).forEach(([m,C])=>{d($i,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const v=l[m];if(C==null){v!=null&&($i.debug(`delete key: ${m}`),c.delete.push(m));return}v!==C&&(Zs.default(v,C)||m==="text"&&ne.diff(v,C).length===0||(a.has(m)?($i.debug(`replace key: ${m}`),c.delete.push(m)):$i.debug(`insert key: ${m}`),c.insert[m]=C))}),n.doc.localUpdateBlockData(i,s,c,o),ro(n,t)}function v2(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Q1(n,t,e){if(!ct(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=ve(n,t).getChildContainers(n,t)[0],i=Qt(r);Q1(n,i,e)}function jo(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=y("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=jo(C),{root:w,...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 w=u.substring(v.length),E=`${C}/${w}`;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 K1(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 jo(i)}function J1(n,t,e){const o=t.blocks.root.map(r=>Fo(n.editorBlocks,t,r,e));return Y.default(jo(o))}const k2=y("insert-doc");function y2(n,t,e,o,r){if(ct(n,t)){k2.warn("failed to insert doc into a complex block");return}const i=J1(n,o,r),s=H(t),l=K(t),c=V(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var x,A,O;Object.entries(i.blocks).forEach(([P,U])=>{P!=="root"&&n.doc.localInsertChildContainer(P,U)});const a=i.blocks.root;if(Te(t)){n.deleteBlock(t);let P;a.reverse().forEach(U=>{const tt=n.insertBlock(c,l,U);P||(P=tt)}),P&&n.selection.selectBlock(P,Z(n,P));return}if(d(k2,j(n,t),"not a text block"),wt(n,t)){const P=K(t);let U;a.forEach((tt,ot)=>{const ut=n.insertBlock(c,P+ot,tt);ot===a.length-1&&(U=ut)}),U&&n.selection.selectBlock(U,Z(n,U));return}if(a.length===1){const P=a[0];if(Di(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 w=f?l:l+1;u?(v=n.insertBlock(c,l+1,C),n.selection.selectBlock(v,Z(n,v))):(n.selection.selectBlock(v,0),Di(n,C.type)?n.insertTextToBlock(v,0,(A=C.text)!=null?A:[]):n.insertBlock(c,w,C));const E=n.selection.range;let L=w;Di(n,m.type)?f?(n.insertBlock(c,w,m),L+=1):n.insertTextToBlock(t,e,(O=m.text)!=null?O:[]):(n.insertBlock(c,w,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 X1(n,t,e,o,r){const i=J1(n,o,r),s=V(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 w2(n,t,e){const o=Ve(t);X1(n,t,o,e);for(let r=0;r<o;r++){const i=Qt(t);n.deleteBlock(i)}}const Hi=y("add-text-attribute");function Jb(n,t,e,o){const{start:r,end:i}=e;d(Hi,r.blockId===i.blockId&&r.blockId===G(t),"invalid range"),d(Hi,o,"invalid attribute name");const s=n.getBlockText(t),l=Sr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function B2(n,t,e,o,r){const{start:i,end:s}=e;d(Hi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range"),d(Hi,o,"invalid attribute name");const l=n.getBlockText(t),c=wl(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(Hi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range");const l=n.getBlockText(t),c=Ag(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function E2(n,t,e,o){const r=Qe(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!j(n,s))return;if(wt(n,s)){o(n,G(s),t,e);return}const a=Ut(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 I2(n,t,e){const o=Qe(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!j(n,i))return;if(wt(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=Ut(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 td(n,t){const e=Qe(n,{simpleBlockOnly:!0}).filter(s=>j(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 Ng(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 x2(n){let t=Gt(n.rootContainer);if(ct(n,t)){const e=wr(n,t);e&&(t=e)}n.selection.selectBlock(t,Z(n,t))}function S2(n){x2(n),n.focus()}const ed=y("selected-block-to-doc");function T2(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{T2(n,i,e)}),e.blocks[o]=Y.default(r)})}function Hl(n,t,e={ignoreLockInfo:!0}){const o=kt(n,t.block);if(o.selectionToDoc)return o.selectionToDoc(n,t);const r=Y.default(ro(n,t.block));if(!e.ignoreLockInfo&&r.lock&&delete r.lock,j(n,t.block)){const s=t.start,l=t.end;if(d(ed,r.text,"no block text"),s.offset===l.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:c}=Kt(r.text,s.offset,l.offset-s.offset);return{blocks:{root:[{...r,text:c}]},meta:{},comments:{}}}if(Te(t.block))return{blocks:{root:[r]},meta:{},comments:{}};d(ed,ct(n,t.block),"not complex block"),d(ed,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return T2(n,r,i),i}function nd(n,t,e=!0){const o=$(t,0,"normal"),r=$(t,Z(n,t),"end");return Hl(n,{block:t,start:o,end:r},{ignoreLockInfo:e})}const Xb=y("block-to-doc");function tv(n,t){d(Xb,t.length>0,"invalid params, no blocks");const e=t.map(o=>nd(n,o));return jo(e)}function jl(n){const e=n.selection.range.getSelectedBlocks().map(o=>Hl(n,o));return jo(e)}function od(n,t){const e=n.getContainerById(t),i=Rt(e).map(s=>({start:$(s,0,"home"),end:$(s,Z(n,s),"end"),block:s})).map(s=>Hl(n,s));return jo(i)}function D2(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=>{D2(n,l,e)})})}function ev(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)}):D2(t,r,e)}),Array.from(e)}function rd(n,t){return t.blocks.root.map(r=>F1(n,r,t)).join(`
25
25
  `)}function id(n,t){return t.blocks.root.map(r=>Dl(n,r,t)).join(`
26
- `)}function sd(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Lo(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function ld(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=ev(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function nv(n,t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData||n.selection.range.isCollapsed())return;const e=jl(n);ld(n,e);const o=rd(n,e),r=id(n,e),i=sd(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 ov(n){if(n.selection.range.isCollapsed())return;const t=jl(n);ld(n,t);const e=rd(n,t),o=sd(e,t),r=new Blob([o],{type:"text/html"});il([{type:"text/html",data:r}])}async function cd(n,t){const e=nd(n,t,!1);ld(n,e);const o=rd(n,e),r=id(n,e),i=sd(o,e);return il([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}const ad=y("editor-input");class rv{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)&&!Ti(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=>{nv(this.editor,t)});h(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}ad.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(),It.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(ad,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(ad,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function iv(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 dd=y("editor-caret");class sv{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 Vt))return!1;const e=this.editor.getBlockById(t.blockId);return!!j(this.editor,e)}update(){if(Vf(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",iv(this.editor);return}const{range:e}=this.editor.selection;d(dd,e.isCollapsed,"range is not collapsed");const o=e.start;d(dd,o instanceof Vt,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(dd,j(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=xo(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Oe(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`,It.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`)}}function lv(n){Wm(n),n.selection.range.getSelectedBlocks().forEach(t=>Gm(n,t.block,t.start,t.end))}function L2(n){return Nn(n.rootContainer).clientHeight}function cv(n){return n.getFirstBlock().getBoundingClientRect().top}function av(n){return n.getLastBlock().getBoundingClientRect().bottom}function ud(n){const t=Nn(n.rootContainer);return new DOMRect(t.clientLeft,t.clientTop,t.clientWidth,t.clientHeight)}function dv(n,t){const e=ud(n),o=n.getBlockById(t.blockId),i=Ge(n,o,t);return To(e,i.x,i.y)&&To(e,i.right,i.bottom)}function uv(n,t){const e=ud(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function hv(n,t){const e=ud(n),o=t.getBoundingClientRect();return To(e,o.x,o.y)||To(e,o.right,o.bottom)}function fv(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,u=n.getContainerById(a.childContainerId);hv(n,u)||u.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(Te(a)&&uv(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(dv(n,o))return;const i=Ge(n,r,o),s=r.getBoundingClientRect(),l=At(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,Ei(c),setTimeout(()=>{c.remove()})}function mv(n,t){if(t.isCollapsed())return!1;const e=Qt(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=y("editor-selection");class gv{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(h2(e,i)){Fl.debug("adjust selection because remote deleted current block");const s=f2(t,e);this.setRange(s)}});this.editor=t;const e=t.getFirstBlock(),o=G(e);this.caret=new sv(t);const r=$(o,0,"normal");this._range=Ut(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=Ut(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()||!mv(this.editor,r))&&F(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t){return this.setSelection(t.anchor,t.focus)}updateSelection(){this.caret.update(),lv(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(!kr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ge(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){fv(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=H(t);for(;qe(e);){const o=z(e);d(Fl,o,"parent block not found"),M(o,"child-focused"),e=H(o)}return!0}}const M2=y("line-offset");function hd(n){const t=n.selection.range.focus;d(M2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!j(n,e))return $(e,0,"home");let r=vg(e,t).start;const{next:i}=gl(e,r);return i&&Me(i)&&Si(i)==="br"&&(r+=1),$(e,r,"home")}function fd(n){const t=n.selection.range.focus;d(M2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===Z(n,e)||!j(n,e))return $(e,0,"end");const o=vg(e,t);return $(e,o.end,"end")}function pv(n){if(!n.selection.range.focus.isSimple())return;const e=hd(n),o=fd(n);!e||!o||n.selection.setSelection(e,o)}const Ne=y("block-text");function R2(n,t,e){d(Ne,j(n,t),"not a text kind block"),d(Ne,fe(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=ke(n,t),{middle:s}=Kt(i,o,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return E1(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:o,length:l.insert.length}}function A2(n,t,e){d(Ne,j(n,t),"not a text kind block"),d(Ne,fe(t,e),"not a valid offset"),d(Ne,e>=0&&e<Z(n,t),`invalid offset: ${e}`);const r=Ir(t,e)-e;r===0&&d(Ne,!1,`no text after offset: ${e}`);const i=ke(n,t),{middle:s}=Kt(i,e,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return E1(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:e,length:l.insert.length}}function O2(n,t,e,o){let r=e;for(;r>0;){const i=R2(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function _2(n,t,e,o){const r=Z(n,t);let i=e;for(;i<r;){const s=A2(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function N2(n,t,e){if(d(Ne,j(n,t),"invalid blok type"),wt(n,t))return 0;const o=R2(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=O2(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=O2(n,t,r,"text");return i?i.offset+i.length:0}function P2(n,t,e){if(d(Ne,j(n,t),"invalid blok type"),wt(n,t))return 0;const o=A2(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=_2(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=_2(n,t,r,"text");return i?i.offset:Z(n,t)}const $2=y("word-offset");function md(n,t){const e=n.selection.range.focus;d($2,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(wt(n,o))return $(o,0,"home");if(e.offset===0||!j(n,o)){const s=gt(o);if(!s)return null;const l=$(s,Z(n,s),"end");if(t==="select"&&j(n,s)){const c=N2(n,s,l.offset);return $(s,c,"normal")}return l}const r=N2(n,o,e.offset);return $(o,r,"normal")}function gd(n,t){const e=n.selection.range.focus;d($2,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(wt(n,o))return $(o,0,"end");if(e.offset===Z(n,o)||!j(n,o)){const s=ht(o);if(!s)return null;const l=$(s,0,"home");if(t==="select"&&j(n,s)){const c=P2(n,s,l.offset);return $(s,c,"end")}return l}const r=P2(n,o,e.offset);return $(o,r,"normal")}function Cv(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!j(n,e))return;const o=md(n,"select"),r=gd(n,"select");!o||!r||n.selection.setSelection(o,r)}const me=y("adjust-selection-pos");function H2(n){const t=[];for(;n;){const e=H(n);if(t.unshift(e),Ct(e))return t;const o=z(e);d(me,o,"child container has not parent container"),n=o}d(me,!1,"should not come here: getParentContainers")}function j2(n,t){for(;t;){const e=H(t);if(e===n)return t;const o=z(e);d(me,o,"could not find parent block for a child container"),t=o}d(me,!1,"no parent block in specified container")}function bv(n,t){const e=H2(n),o=H2(t);d(me,e.length>0&&o.length>0,"block has not parent container"),d(me,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=j2(r,n),s=j2(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function F2(n,t){let e=z(t);for(d(me,e,"element is not in a block");e;){const o=H(e);d(me,qe(o),"not a child container");const r=z(o);if(d(me,r,"child container has not parent block"),r===n)return o;e=r}d(me,!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 Vt&&e instanceof Vt?{anchor:t,focus:e}:(d(me,t instanceof Ze&&e instanceof Ze,"both start and end are not simple or complex"),ml(n,o,t,e));const i=H(o),s=H(r);if(i===s)return t instanceof Ze&&(t=$(o,0,"home")),e instanceof Ze&&(e=$(r,Z(n,r),"end")),d(me,t instanceof Vt,"not valid position type"),d(me,e instanceof Vt,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Vt&&e instanceof Ze){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const w=z(i);if(w&&w===z(v)){const E=bt(w,V(i)),L=bt(w,V(v));return ml(n,w,E,L)}}return null}const l=Xs(o,r)>0,{newBlock1:c,newBlock2:a}=bv(o,r);if(c===a){const v=c,w=F2(v,o),E=F2(v,r);return t=bt(c,V(w)),e=bt(c,V(E)),me.debug(`select in complex block: ${w.id}, ${E.id}`),ml(n,v,t,e)}let u=l?Z(n,c):0;c===o&&t instanceof Vt&&(u=t.offset);let m=l?0:Z(n,a);return a===r&&e instanceof Vt&&(m=e.offset),t=$(c,u,l?"end":"home"),e=$(a,m,l?"home":"end"),{anchor:t,focus:e}}const vv=y("range-from-point");function z2(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 V2(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Qt(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 kv(n,t,e){const o=z2(n,t,e);if(o){if(o instanceof se)return o;d(vv,o instanceof Ye,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return V2(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=>fn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const u=c.getBoundingClientRect(),f=a.getBoundingClientRect();return hn(u,t,e)>hn(f,t,e)?a:c});return V2(n,l,t,e)}class yv{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=kv(this.editor,t.x,t.y);if(e){if(e instanceof Ye)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=z2(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){Cv(this.editor)}handleTripleClick(t){pv(this.editor)}}const wv=y("move-complex-block-position");function Bv(n,t,e){const o=n.getBlockById(t.blockId);d(wv,ct(n,o),"is not a complex block");const r=ve(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?bt(o,V(s)):null}const ji=y("move-simple-block-position");function U2(n,t){const e=Le(n,t);d(ji,e.length>0,"complex block has not any child container");const o=e[0];return Qt(o)}function q2(n,t){const e=Le(n,t);d(ji,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Gt(o)}function W2(n,t,e){const o=e?U2(n,t):q2(n,t);return ct(n,o)?W2(n,o,e):o}function Ev(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===0?U2(n,e):Cr(e)}function Iv(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===1?q2(n,e):pr(e)}function pd(n){return n==="ArrowLeft"||n==="ArrowUp"}function Cd(n,t,e){const o=H(t);if(Ct(o))return null;const r=z(o);d(ji,r,"child container has not parent block"),d(ji,ct(n,r),"is not a complex block");const i=ve(n,r).getNextContainer(n,r,o,e);return i?pd(e)?Gt(i):Qt(i):Cd(n,r,e)}function xv(n,t,e){const o=H(t);if(Ct(o))return null;const r=z(o);if(d(ji,r,"child container has not parent block"),pd(e)){const l=gt(r);if(l)return l}else{const l=ht(r);if(l)return l}const i=Cd(n,r,e);if(i)return i;let s=r;for(;!Ct(H(s));)s=z(H(s));return pd(e)?gt(s):ht(s)}function Sv(n,t,e){return!ct(n,t)||ve(n,t).enableKeyboardSelect?t:W2(n,t,e==="ArrowDown"||e==="ArrowRight")}function Tv(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"?Ev(n,t):Iv(n,t);if(s||(s=Cd(n,o,e),s||(s=xv(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Ct(H(o)))return null;const l=n.insertTextBlock("",V(n.rootContainer),Ve(n.rootContainer));return $(l,0,"home")}return null}if(s=Sv(n,s,e),j(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return ib(n,s,o,t,l);if(e==="ArrowUp")return rb(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?$(s,Z(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?$(s,0,"home"):null}function Dv(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(j(n,r))return o;const i=ht(r);if(i)return $(i,0,"home");if(!Ct(H(r))||n.readonly)return o;const s=n.insertTextBlock("",V(n.rootContainer),Ve(n.rootContainer));return $(s,0,"home")}function Lv(n,t,e){const o=n.selection.range;let r;if(o instanceof se)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=Dv(n,t,o):r=Tv(n,o.getFocusedPos(),t);else if(r=Bv(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=Qt(s);r=$(l,Z(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:zl(n,o.anchor,r):null}function io(n,t,e){const o=Lv(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 Mv(n){return io(n,"ArrowLeft","move"),!0}function Rv(n){return io(n,"ArrowRight","move"),!0}function Av(n){return io(n,"ArrowUp","move"),!0}function Ov(n){if(io(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=H(t);if(Ct(e)||Gt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",V(o),Ve(o)),!0}function _v(n){return io(n,"ArrowDown","select"),!0}function Nv(n){return io(n,"ArrowLeft","select"),!0}function Pv(n){return io(n,"ArrowRight","select"),!0}function $v(n){return io(n,"ArrowUp","select"),!0}function Hv(n){if(!n.selection.range.focus.isSimple())return!1;const e=md(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function jv(n){if(!n.selection.range.focus.isSimple())return!1;const e=gd(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Fv(n){if(!n.selection.range.focus.isSimple())return!1;const e=md(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function zv(n){if(!n.selection.range.focus.isSimple())return!1;const e=gd(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}y("find-block");function bd(n,t){if(!ct(n,t))return t;const o=ve(n,t).getChildContainers(n,t)[0],i=Rt(o)[0];return bd(n,i)}function vd(n,t){if(!ct(n,t))return t;const e=ve(n,t).getChildContainers(n,t),o=e[e.length-1],r=Rt(o),i=r[r.length-1];return vd(n,i)}function Vv(n){const t=vd(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(e),!0}function Uv(n){const t=bd(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(e),!0}function qv(n){const t=bd(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Wv(n){const t=vd(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Gv(n){if(!n.selection.range.focus.isSimple())return!1;const e=hd(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function Zv(n){if(!n.selection.range.focus.isSimple())return!1;const e=fd(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function Yv(n){if(!n.selection.range.focus.isSimple())return!1;const e=hd(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Qv(n){if(!n.selection.range.focus.isSimple())return!1;const e=fd(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const G2=y("find-block-position");function Kv(n,t,e,o){d(G2,ct(n,t),"is not a complex block");const r=ve(n,t).getChildContainers(n,t);d(G2,r.length>0,"complex block has not any child container");const i=Ge(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=ug(n,t,s,l);return kd(n,c,e,o)}function kd(n,t,e,o){if(ct(n,t))return Kv(n,t,e,o);const r=G(t);let i=Number.MAX_SAFE_INTEGER;const s=Ge(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=Ge(n,t,m),v=hn(C,l,c);v<i&&(i=v,a=m)}return a}const Z2=y("page-offset");function Jv(n,t){const e=L2(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<cv(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 Xv(n,t){const e=L2(n)*.9,o=t.getBoundingClientRect(),r=av(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 Y2(n){const t=n.selection.range.focus;d(Z2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Jv(n,e);let r;return o===n.getFirstBlock()?r=$(o,0,"home"):r=kd(n,o,e,t),r}function Q2(n){const t=n.selection.range.focus;d(Z2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Xv(n,e);let r;return o===n.getLastBlock()?r=$(o,Z(n,o),"end"):r=kd(n,o,e,t),r}function tk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Y2(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ek(n){if(!n.selection.range.focus.isSimple())return!1;const e=Q2(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function nk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Y2(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 ok(n){if(!n.selection.range.focus.isSimple())return!1;const e=Q2(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 Fi=y("select-all");function rk(n,t){const e=t.getEditor(),o=ve(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=G(n);return t.start.blockId===s&&t.start.childContainerId===V(r)&&t.end.blockId===s&&t.end.childContainerId===V(i)}function ik(n,t){d(Fi,t,"no parent block"),d(Fi,ct(n,t),"not a complex block");const e=ve(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Ut(n,{anchor:bt(t,V(o)),focus:bt(t,V(r))}))}function K2(n,t){const e=H(t),o=Rt(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 sk(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&j(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"),K2(n,Qt(n.rootContainer)),!1}return d(Fi,!e.isSimple(),"invalid range type"),rk(t,e)?(K2(n,t),!1):(d(Fi,t,"no parent block"),d(Fi,ct(n,t),"not a complex block"),ik(n,t),!0)}function lk(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function ck(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const J2=y("delete-text");function X2(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Vt||d(J2,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(J2,j(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!fe(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 t0(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const ak=y("handle-backspace");function yd(n,t){if(!wt(n,t))return;const e=H(t);Ve(e)!==1&&n.deleteBlock(t)}function dk(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===0){if(t0(n,o))return;const r=gt(o);if(r)if(j(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ct(n,r)){yd(n,o);const i=wr(n,r);i?n.selection.selectBlock(i,Z(n,i)):n.selection.selectBlock(r,0,Z(n,r))}else yd(n,o),d(ak,Te(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=H(o);if(qe(i)){const s=cg(n,i);s&&(yd(n,o),n.selection.selectBlock(s,Z(n,s)))}}}else X2(n,"backward",1,null);else{const r=K(o),i=H(o);n.insertTextBlock("",V(i),r),n.deleteBlock(o)}}function uk(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===Z(n,o)){const r=ht(o);r&&(j(n,r)?n.mergeTextBlock(o,r,{focus:!0}):wt(n,o)?n.deleteBlock(o,Ot(n,r,0)):n.deleteBlock(r))}else X2(n,"forward",1,null);else{const r=K(o),i=H(o);n.insertTextBlock("",V(i),r),n.deleteBlock(o)}}function hk(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(j(n,e)){if(wt(n,e)&&t0(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 fk(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!j(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 mk=y("input-handler-actions");function gk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(hk(n),!0))}function pk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(uk(n),!0))}function Ck(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(dk(n),!0))}function bk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(fk(n),!0))}function vk(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(mk,o.isSimple(),"not simple position"),n.insertTextToBlock(e,o.offset,t)}),!0)}function kk(n){return ov(n),Y1(n),!0}const Vl={ArrowDown:Ov,ArrowUp:Av,ArrowLeft:Mv,ArrowRight:Rv,"Shift+ArrowDown":_v,"Shift+ArrowUp":$v,"Shift+ArrowLeft":Nv,"Shift+ArrowRight":Pv,"CtrlOrCmd+ArrowLeft":Hv,"CtrlOrCmd+ArrowRight":jv,"CtrlOrCmd+Shift+ArrowLeft":Fv,"CtrlOrCmd+Shift+ArrowRight":zv,"CtrlOrCmd+ArrowUp":Uv,"CtrlOrCmd+ArrowDown":Vv,"CtrlOrCmd+Shift+ArrowUp":qv,"CtrlOrCmd+Shift+ArrowDown":Wv,"CtrlOrCmd+A":sk,Home:Yv,End:Qv,"Shift+Home":Gv,"Shift+End":Zv,PageUp:tk,PageDown:ek,"Shift+PageUp":nk,"Shift+PageDown":ok,"CtrlOrCmd+X":kk,"CtrlOrCmd+Z":lk,"CtrlOrCmd+Shift+Z":ck,Enter:gk,Delete:pk,Backspace:Ck,"Shift+Enter":bk,"CtrlOrCmd+Shift+V":vk};function e0(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function n0(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=>{n0(n,l,e)})})}function o0(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):n0(t,r,e)})}async function yk(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 wk(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 Bk(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(wk(n,t)){const s=Array.from(Object.keys(o));r=await yk(n,s),o0(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&&o0(n,t,i)}async function Ek(n,t){await Bk(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Tr(n);n.insertDoc(e,o,t)})}const Ik=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function xk(n){let t;for(const e of Ik)if(t=n[e],t)break;return t||null}class Sk{constructor(t){h(this,"editor");h(this,"handlers",[]);this.editor=t}onInsertText(t,e){if(!j(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Tr(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}=Tr(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}=Tr(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=xk(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){V1(this.editor,i)}defaultHandleKeydown(t,e){return e0(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 Ek(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 Tk(n,t,e){const o=mr(t,e);return o.remove(),o}const wd=y("copy-dom-attributes"),r0=["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 Dk(n,t){for(let l=0;l<r0.length;l++){const c=r0[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=>{wd.debug(`add attribute: ${l.name}, ${l.value}`),t.setAttribute(l.name,l.value)}),i.forEach(l=>{wd.debug(`copy attribute: ${l.name}, ${l.value}`),t.setAttribute(l.name,l.value)}),s.forEach(l=>{wd.debug(`delete attribute: ${l.name}`),t.removeAttribute(l.name)})}function i0(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function s0(n,t,e){var a;const o=n.getContainerById(t),r=mr(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=i0(u);i0(r),f.forEach(C=>r.appendChild(C));const m=al(u);if(m){const C=al(r);C&&C.remove(),r.appendChild(m)}Dk(u,r)}Ym(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 Lk=y("transform-selection");function l0(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(Lk,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=ne.transformCursor(i.offset,e,o);l=$(t,a,"normal")}let c=s;if(s.blockId===t){const a=ne.transformCursor(s.offset,e,o);c=$(t,a,"normal")}return Ut(n,{anchor:l,focus:c})}const Mk=y("handle-block-text-changed");function Rk(n,t,e,o,r){const i=n.getContainerById(t),s=mr(i,e),l=n.doc.getBlockData(t,e);if(d(Mk,l.text,"no block text"),qm(n,s).setBlockText(n,s,l.text),!r){const c=l0(n,l.id,o,r);n.selection.setRange(c)}}function Ak(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function c0(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 Ok(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{c0(n,i,o,{child:!0})}),c0(n,r,o,{child:!1})}const so=y("editor-doc");class _k extends ki{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){d(so,this.editor.isWritable(),"editor is readonly");const i=this.getBlockData(e,o),s=i.text;d(so,s,`no text, ${e}, ${o}`);const l=l0(this.editor,i.id,r,!0),c=ne.apply(s,r);this.localEvents.forEach(u=>u.onBeforeUpdateBlockText(e,i.id,s,c,l.toDocRange()));const a=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(l),a}localUpdateBlockData(e,o,r,i){d(so,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Ak(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(no(this.editor,i)),c}localInsertBlock(e,o,r,i){d(so,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(l=>l.onBeforeInsertBlock(e,o,r,i));const s=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(no(this.editor,i)),s}localDeleteBlock(e,o,r){d(so,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(no(this.editor,r)),s}localDeleteChildContainers(e){return d(so,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(so,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){so.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})}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)}),Rk(this.editor,e,o,r,i),i&&this.editor.emit("docChanged",this.editor)}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)}),s0(this.editor,e,o),i&&this.editor.emit("docChanged",this.editor)}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);lC(this.editor,s,o,r),i&&this.editor.emit("docChanged",this.editor)}onDeleteBlock(e,o,r){Ok(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);Tk(this.editor,i,o),r&&this.editor.emit("docChanged",this.editor)}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:{}}}function a0(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 Bd=y("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(Bd,t,"no other action"),!1}combine(t){d(Bd,!1,"no other")}setAfterRange(t){this.afterRange&&Bd.warn("after range has already set"),this.afterRange=t}}const Nk=y("block-action");class d0 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(Nk,this.blockIndex===K(i),"invalid block index"),W1(e,i,no(e,o)),!0):!1}insertBlock(e,o){return Dr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Pk extends d0{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class $k extends d0{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class Hk extends Mr{constructor(e){super(e,V(e.rootContainer),e.selection.range.toDocRange());h(this,"actions",[])}addAction(e){a0(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=y("update-block-data-action");class Ul 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,Ul.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,Ul.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const Ed=y("update-block-text-action");class zi 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=zi.calType(i,s)}static calType(e,o){d(Ed,e,"no old data"),d(Ed,o,"no new data");const i=ne.diff(e,o),s=new Set;let l=!1;const c=u=>em(u)?`cjk_${u}`:Xf(u)?"number":tl(u)?"space":tm(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 zi)||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(Ed,e instanceof zi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class u0 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 jk extends u0{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class Fk extends u0{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Je=y("undo");class zk{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):(a0(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(Je,!this.currentGroup,"current group already exists"),this.currentGroup=new Hk(this.editor),this.groupCounter=1):(d(Je,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(Je,this.currentGroup,"current group not exists"),d(Je,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Je.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 Je.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(no(this.editor,t.beforeRange))}catch(e){Je.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(no(this.editor,e)):Je.warn("no after range")}catch(e){Je.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(),ne.diff(o,r).length!==0&&this.addAction(new zi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Ul(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(Je,e>=0,"invalid block index"),d(Je,o,"no block data"),this.addAction(new Pk(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new $k(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new jk(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Fk(this.editor,t,e)))}}class Vk{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 Uk{constructor(){h(this,"converters",[]);this.addConverter(new Vk)}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 qk{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(!j(this.editor,e))return null;const r=rt(e);return o.parentElement===r?o:l1(o)}}const h0="style-color-",f0="style-bg-color-";class Wk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(h0)?i["data-style-color"]=s.substring(h0.length):s.startsWith(f0)?i["data-style-bg-color"]=s.substring(f0.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 Gk(n){n.editorBlocks.registerBlockClass(_i),n.editorBlocks.registerBlockClass(lg),n.editorBoxes.registerBoxClass(Gg),n.editorBoxes.registerBoxClass(Zg),n.editorInsertions.registerInsertionClass(Kg),n.editorBlockRenders.registerRender(new Wk)}function Zk(n,t){Gk(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 m0=y("range-commands");function g0(n,t){n.forEach(e=>{e.source=t,e.children&&g0(e.children,t)})}function p0(n,t,e){const o=G(t);d(m0,o===e.start.blockId,"invalid start range"),d(m0,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);g0(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)&&yr(n,t,e.start,e.end).forEach(l=>{Rt(l).forEach(a=>{const u=Z(n,a),f=Ut(n,{anchor:$(a,0,"home"),focus:$(a,u,"end")}),m=p0(n,a,f);i.push(...m)})}),i}function C0(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ut(t,{anchor:r.start,focus:r.end});p0(t,r.block,i).forEach(l=>{o.push(l)})}),o}function b0(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)&&yr(n,t,e.start,e.end).forEach(m=>{Rt(m).forEach(v=>{const w=Z(n,v),E=Ut(n,{anchor:$(v,0,"home"),focus:$(v,w,"end")});b0(n,v,E,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function v0(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=Ut(o,{anchor:l.start,focus:l.end});b0(o,l.block,c,t,e,r)}),r}const Yk=y("command-providers");class k0{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(Yk,e,`no command provider, id=${t}`),e}getCommands(t){return C0(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>v0(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 Qk(n,t){const e=H(t),o=V(e),r=K(t);s0(n,o,r)}const Kk=y("table-scroll");class y0{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 Jk{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)){Kk.warn(`event has already registered: ${e}`);return}i.push(new y0(this.editor,t,e,o,r))}else{const s=new y0(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 w0=y("update-block-text");function Xk(n,t){const e=n.getBoxById(t.id),o=z(e);d(w0,o,"no parent block"),d(w0,j(n,o),"not a text block");const r=n.getBlockText(o),i=$g(r,"id",t.id,t);b2(n,o,i)}function ty(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 ey(n){return n.readonly?!1:!Qe(n).find(o=>!n.isBlockWritable(o.block))}class ny{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 oy{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(_n(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Fn=y("editor");class ry 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 oy);h(this,"dataConverter",new Uk);h(this,"editorBlocks",new og(this));h(this,"editorBoxes",new Qg(this));h(this,"editorInsertions",new Xg(this));h(this,"editorEmbeds",new ig(this));h(this,"editorDecorators",new t2(this));h(this,"editorCommandProviders",new k0(this));h(this,"editorBlockRenders",new qk(this));h(this,"blockHooks",[]);h(this,"domEvents",new Jk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new Sk(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 ny(this),Zk(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 zk(this),this.doc=new _k(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=zm(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new rv(this,this.inputHandlers),this.selection=new gv(this),this.selectionHandler=new yv(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),It.isMobile&&M(this.rootElement,"mobile"),It.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:Nn(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){Q1(this,e,o)}isWritable(){return ey(this)}isBlockWritable(e){return ty(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 Vm(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,gr(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,s1(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 mr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return K(o)}return K(e)}getContainerById(e){return br(this,e)}getParentContainer(e){return H(e)}reloadBlock(e){Qk(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){const s={blockId:r.id,offset:0},l={anchor:s,focus:s};return Dr(this,e,o,r,i!=null?i:l)}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){G1(this,e,o)}mergeTextBlock(e,o){return g2(this,e,o)}breakTextBlock(e,o,r){return Pi(this,e,o,r).newBlock}getTextPosition(){return Tr(this)}getBlockString(e,o){const r=this.getBlockText(e);return Tt(r,o)}getBlockData(e){return ro(this,e)}getBoxData(e){return r2(this,e)}getBlockText(e){return ke(this,e)}setBlockText(e,o){b2(this,e,o)}deleteTextFromBlock(e,o,r){return U1(this,e,o,r)}insertTextToBlock(e,o,r){return s2(this,e,o,r)}insertBoxToBlock(e,o,r){return l2(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){y2(this,e,o,r,i)}insertDocAt(e,o,r,i){return X1(this,e,o,r,i)}deleteChildContainers(e){m2(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 v2(this,e,o,r)}updateBoxData(e){Xk(this,e)}getSelectedText(){const e=jl(this);return id(this,e)}clearSelectedContents(){Y1(this)}insertTextBlock(e,o,r,i){const s=jn(e!=null?e:"");return u2(this,s,o,r,i==null?void 0:i.newRange)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){a2(this);return}o?(this.compositingText="",Qa()||V1(this,e)):(this.compositingText=e,c2(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Vi(n,t,e){return new ry(n,t,e)}function iy(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=Fa.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const sy=["#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:sy}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&Zs.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&&Sl(r.range)&&zg(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(Sl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=ne.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=ne.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 Jt=y("local-doc");class Id extends ki{constructor(e){super();h(this,"doc");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[jn("")]}}}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(Jt,r,`no container data: ${e}`);const i=r[o];return d(Jt,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Jt,i.text,"no text for data");const s=ne.apply(i.text,r);return i.text=s,d(Jt,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(Jt,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(Jt,i,`no container data: ${e}`),d(Jt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(Jt,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(Jt,r,`no container data: ${e}`),d(Jt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(Jt,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(Jt,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){Jt.debug(`delete child containers: ${e}`),e.forEach(o=>{d(Jt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(Jt,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(Jt,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(Jt,!1,"not implemented")}broadcastMessage(e){}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 Vo(n){return Ct(H(n))}class ly{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function xd(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new ly(o)})}const B0=y("remote-cursor");class cy{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"?(B0.debug(`remote caret received: ${e}`),this.handleUpdateCaret(e)):B0.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 ay(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function Ui(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=ay(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 dy={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ee.default(n)},apply(n,t){const e=new ee.default(n),o=new ee.default(t);return e.compose(o).ops},compose(n,t){const e=new ee.default(n),o=new ee.default(t);return e.compose(o).ops},diff(n,t){const e=new ee.default(n),o=new ee.default(t);return e.diff(o).ops},transform(n,t,e){const o=new ee.default(n);return new ee.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 ee.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 qi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},co={},Sd=Af.default.EventEmitter;co.EventEmitter=Sd,co.mixin=uy;function uy(n){for(var t in Sd.prototype)n.prototype[t]=Sd.prototype[t]}var E0=["info","warn","error"];function I0(){var n={};E0.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var hy=I0;I0.prototype.setMethods=function(n){n=n||{};var t=this;E0.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var fy=hy,my=new fy,x0=my;function Uo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Uo):this.stack=new Error().stack}Uo.prototype=Object.create(Error.prototype),Uo.prototype.constructor=Uo,Uo.prototype.name="ShareDBError",Uo.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=Uo,Wi={},S0=gy;function gy(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 w=i(s.slice(m),C),E=0;E<w[0].length;E++)o(f,w[0][E]);for(var L=0;L<w[1].length;L++)o(c,w[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 T0={exports:{}},ao=T0.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||""}},Td=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Dd=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++)Dd(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=Td(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:Td(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:Td(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 Ld=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=Ld(n,t[r],o);return n};var py=ao._tc=function(n,t,e,o){if(Dd(t),Dd(e),t.i!=null)zn(n,{i:t.i,p:Ld(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=Ld(i.p,e),zn(n,i))}return n},Cy=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]=Cy(n[t]);return n},S0(ao,py,Gl,zn);var Zl=function(n){return Object.prototype.toString.call(n)=="[object Array]"},by=function(n){return!!n&&n.constructor===Object},Xe=function(n){return JSON.parse(JSON.stringify(n))},et={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Vn={};et.registerSubtype=function(n){Vn[n.name]=n},et.create=function(n){return n===void 0?null:Xe(n)},et.invertComponent=function(n){var t={p:n.p};return n.t&&Vn[n.t]&&(t.t=n.t,t.o=Vn[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},et.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(et.invertComponent(t[o]));return e},et.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Zl(n[t].p))throw new Error("Missing path")},et.checkList=function(n){if(!Zl(n))throw new Error("Referenced element not a list")},et.checkObj=function(n){if(!by(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Gi(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 Zi(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}et.apply=function(n,t){et.checkValidOp(t),t=Xe(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&Gi(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&&Vn[r.t])s[l]=Vn[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)et.checkList(s),s[l]=r.li;else if(r.li!==void 0)et.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)et.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(et.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)et.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)et.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},et.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},et.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=et.apply(n,r),e(r,n)}return n};var vy=et.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};et.append=function(n,t){if(t=Xe(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)&&(Gi(t),Gi(e)),vy(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Vn[t.t]){if(e.o=Vn[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(),Zi(t),n.push(t);Zi(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)&&(Zi(t),Zi(e)),n.push(t)},et.compose=function(n,t){et.checkValidOp(n),et.checkValidOp(t);for(var e=Xe(n),o=0;o<t.length;o++)et.append(e,t[o]);return e},et.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=[]),et.append(t,o)}return t},et.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},et.canOpAffectPath=function(n,t){return et.commonLengthForOps({p:t},n)!=null},et.transformComponent=function(n,t,e,o){t=Xe(t);var r=et.commonLengthForOps(e,t),i=et.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=Xe(e);c.p=c.p.slice(s),t.ld=et.apply(Xe(t.ld),[c])}else if(t.od!==void 0){var c=Xe(e);c.p=c.p.slice(s),t.od=et.apply(Xe(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)&&(Gi(t),c=Xe(e),Gi(c)),c.t&&Vn[c.t]){if(t.t&&t.t===c.t){var u=Vn[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(),Zi(t),et.append(n,t);else(!Zl(u)||u.length>0)&&(t.o=u,et.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=Xe(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,w=e.p[r],E=e.lm;if(w!==E)if(C===w)if(o==="left")t.p[r]=E,C===v&&(t.lm=E);else return n;else C>w&&t.p[r]--,C>E?t.p[r]++:C===E&&w>E&&(t.p[r]++,C===v&&t.lm++),(v>w||v===w&&v>C)&&t.lm--,v>E?t.lm++:v===E&&(E>w&&v>C||E<w&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===w&&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")et.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 et.append(n,t),n},S0(et,et.transformComponent,et.checkValidOp,et.append);var ky=T0.exports;et.registerSubtype(ky);var yy=et,wy={type:yy};(function(n){n.defaultType=wy.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)})(Wi);var tn={};(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))}})(tn);var D0=Array.isArray,L0=Object.keys,By=Object.prototype.hasOwnProperty,Ey=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=D0(t),r=D0(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=L0(t);if(s=m.length,s!==L0(e).length)return!1;for(i=s;i--!==0;)if(!By.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},M0=co,Iy=x0,ye=Wl,Yl=Wi,en=tn,xy=en.clone,Sy=Ey,ge=ye.CODES,Ty=st;function st(n,t,e){M0.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}M0.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 ye(ge.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 ye(ge.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 ye(ge.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;en.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===ge.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){en.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){en.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===ge.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);Dy(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=Ly([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;en.nextTick(function(){n._handleSubscribe()})}}};function Dy(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function Ly(n){return n=n.filter(en.truthy),n.length?function(t){en.callEach(n,t)}:null}st.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function My(n){delete n.op,delete n.create,delete n.del}function Ql(n,t){if(n.del)return My(t);if(t.del)return new ye(ge.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new ye(ge.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new ye(ge.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 ye(ge.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 ye(ge.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>=en.MAX_SAFE_INTEGER)return this.emit("error",new ye(ge.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 ye(ge.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;en.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&&!Sy(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 ye(ge.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 ye(ge.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:xy(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 Iy.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=en.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=en.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 R0=co,A0=qo.ACTIONS,Ry=tn,Ay=pe;function pe(n,t,e,o,r,i,s){R0.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}R0.mixin(pe),pe.prototype.hasPending=function(){return!this.ready},pe.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}},pe.prototype.destroy=function(n){this.connection.canSend&&this.action===A0.querySubscribe&&this.connection.send({a:A0.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Ry.nextTick(n)},pe.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},pe.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},pe.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},pe.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()},pe.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},pe.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)},pe.prototype._handleError=function(n){this.emit("error",n)},pe.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)},pe.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var O0=co,Oy=qo.ACTIONS,_y=tn,_0=bn;function bn(n,t){if(O0.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={}}O0.mixin(bn),bn.prototype.submit=function(n,t){this.value=n,this.send(t)},bn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},bn.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()})},bn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},bn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},bn.prototype._message=function(){return{a:Oy.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},bn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},bn.prototype._callbackOrEmit=function(n,t){if(t)return _y.nextTick(t,n);n&&this.emit("error",n)};var Ny=tn,N0=Md;function Md(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Md.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Md.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Ny.nextTick(n)};var Rd={exports:{}};(function(n,t){(function(e,o){o(t)})(qi,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(w,I)}}function w(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 A(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 O=typeof qi=="object"&&qi&&qi.Object===Object&&qi,P=typeof self=="object"&&self&&self.Object===Object&&self,U=O||P||Function("return this")(),tt=U.Symbol,ot=Object.prototype,ut=ot.hasOwnProperty,dt=ot.toString,yt=tt?tt.toStringTag:void 0;function oe(p){var k=ut.call(p,yt),B=p[yt];try{p[yt]=void 0;var I=!0}catch{}var D=dt.call(p);return I&&(k?p[yt]=B:delete p[yt]),D}var Jn=Object.prototype,Xt=Jn.toString;function Fe(p){return Xt.call(p)}var vo="[object Null]",ar="[object Undefined]",dr=tt?tt.toStringTag:void 0;function ko(p){return p==null?p===void 0?ar:vo:dr&&dr in Object(p)?oe(p):Fe(p)}var ma="[object AsyncFunction]",$P="[object Function]",HP="[object GeneratorFunction]",jP="[object Proxy]";function FP(p){if(!s(p))return!1;var k=ko(p);return k==$P||k==HP||k==ma||k==jP}var zP=9007199254740991;function B9(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=zP}function $s(p){return p!=null&&B9(p.length)&&!FP(p)}var hf={};function ft(){}function yo(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var ff=typeof Symbol=="function"&&Symbol.iterator,VP=function(p){return ff&&p[ff]&&p[ff]()};function UP(p,k){for(var B=-1,I=Array(p);++B<p;)I[B]=k(B);return I}function ga(p){return p!=null&&typeof p=="object"}var qP="[object Arguments]";function E9(p){return ga(p)&&ko(p)==qP}var I9=Object.prototype,WP=I9.hasOwnProperty,GP=I9.propertyIsEnumerable,ZP=E9(function(){return arguments}())?E9:function(p){return ga(p)&&WP.call(p,"callee")&&!GP.call(p,"callee")},dn=Array.isArray;function YP(){return!1}var x9=typeof e=="object"&&e&&!e.nodeType&&e,S9=x9&&!0&&n&&!n.nodeType&&n,QP=S9&&S9.exports===x9,T9=QP?U.Buffer:void 0,KP=T9?T9.isBuffer:void 0,JP=KP||YP,XP=9007199254740991,t$=/^(?:0|[1-9]\d*)$/;function e$(p,k){var B=typeof p;return k=k==null?XP:k,!!k&&(B=="number"||B!="symbol"&&t$.test(p))&&p>-1&&p%1==0&&p<k}var n$="[object Arguments]",o$="[object Array]",r$="[object Boolean]",i$="[object Date]",s$="[object Error]",l$="[object Function]",c$="[object Map]",a$="[object Number]",d$="[object Object]",u$="[object RegExp]",h$="[object Set]",f$="[object String]",m$="[object WeakMap]",g$="[object ArrayBuffer]",p$="[object DataView]",C$="[object Float32Array]",b$="[object Float64Array]",v$="[object Int8Array]",k$="[object Int16Array]",y$="[object Int32Array]",w$="[object Uint8Array]",B$="[object Uint8ClampedArray]",E$="[object Uint16Array]",I$="[object Uint32Array]",Bt={};Bt[C$]=Bt[b$]=Bt[v$]=Bt[k$]=Bt[y$]=Bt[w$]=Bt[B$]=Bt[E$]=Bt[I$]=!0,Bt[n$]=Bt[o$]=Bt[g$]=Bt[r$]=Bt[p$]=Bt[i$]=Bt[s$]=Bt[l$]=Bt[c$]=Bt[a$]=Bt[d$]=Bt[u$]=Bt[h$]=Bt[f$]=Bt[m$]=!1;function x$(p){return ga(p)&&B9(p.length)&&!!Bt[ko(p)]}function S$(p){return function(k){return p(k)}}var D9=typeof e=="object"&&e&&!e.nodeType&&e,Hs=D9&&!0&&n&&!n.nodeType&&n,T$=Hs&&Hs.exports===D9,mf=T$&&O.process,L9=function(){try{var p=Hs&&Hs.require&&Hs.require("util").types;return p||mf&&mf.binding&&mf.binding("util")}catch{}}(),M9=L9&&L9.isTypedArray,D$=M9?S$(M9):x$,L$=Object.prototype,M$=L$.hasOwnProperty;function R$(p,k){var B=dn(p),I=!B&&ZP(p),D=!B&&!I&&JP(p),T=!B&&!I&&!D&&D$(p),R=B||I||D||T,_=R?UP(p.length,String):[],q=_.length;for(var Q in p)(k||M$.call(p,Q))&&!(R&&(Q=="length"||D&&(Q=="offset"||Q=="parent")||T&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||e$(Q,q)))&&_.push(Q);return _}var A$=Object.prototype;function O$(p){var k=p&&p.constructor,B=typeof k=="function"&&k.prototype||A$;return p===B}function _$(p,k){return function(B){return p(k(B))}}var N$=_$(Object.keys,Object),P$=Object.prototype,$$=P$.hasOwnProperty;function H$(p){if(!O$(p))return N$(p);var k=[];for(var B in Object(p))$$.call(p,B)&&B!="constructor"&&k.push(B);return k}function gf(p){return $s(p)?R$(p):H$(p)}function j$(p){var k=-1,B=p.length;return function(){return++k<B?{value:p[k],key:k}:null}}function F$(p){var k=-1;return function(){var I=p.next();return I.done?null:(k++,{value:I.value,key:k})}}function z$(p){var k=gf(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 V$(p){if($s(p))return j$(p);var k=VP(p);return k?F$(k):z$(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 pa(p){return function(k,B,I){if(I=yo(I||ft),p<=0||!k)return I(null);var D=V$(k),T=!1,R=0,_=!1;function q(W,X){if(R-=1,W)T=!0,I(W);else{if(X===hf||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 ur(p,k,B,I){pa(k)(p,x(B),I)}function te(p,k){return function(B,I,D){return p(B,k,I,D)}}function U$(p,k,B){B=yo(B||ft);var I=0,D=0,T=p.length;T===0&&B(null);function R(_,q){_?B(_):(++D===T||q===hf)&&B(null)}for(;I<T;I++)k(p[I],I,Dn(R))}var q$=te(ur,1/0),wo=function(p,k,B){var I=$s(p)?U$:q$;I(p,x(k),B)};function ai(p){return function(k,B,I){return p(wo,k,x(B),I)}}function R9(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,Et){D[W]=Et,Q(X)})},function(_){I(_,D)})}var Ca=ai(R9),A9=A(Ca);function di(p){return function(k,B,I,D){return p(pa(B),k,x(I),D)}}var ui=di(R9),pf=te(ui,1),O9=A(pf);function ba(p,k){for(var B=-1,I=p==null?0:p.length;++B<I&&k(p[B],B,p)!==!1;);return p}function W$(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 G$=W$();function js(p,k){return p&&G$(p,k,gf)}function Z$(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 Y$(p){return p!==p}function Q$(p,k,B){for(var I=B-1,D=p.length;++I<D;)if(p[I]===k)return I;return-1}function va(p,k,B){return k===k?Q$(p,k,B):Z$(p,Y$,B)}var Cf=function(p,k,B){typeof k=="function"&&(B=k,k=null),B=yo(B||ft);var I=gf(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(xt,St){if(!dn(xt)){Et(St,[xt]),W.push(St);return}var Yt=xt.slice(0,xt.length-1),Xn=Yt.length;if(Xn===0){Et(St,xt),W.push(St);return}X[St]=Xn,ba(Yt,function(gi){if(!p[gi])throw new Error("async.auto task `"+St+"` has a non-existent dependency `"+gi+"` in "+Yt.join(", "));Ln(gi,function(){Xn--,Xn===0&&Et(St,xt)})})}),zH(),re();function Et(xt,St){Q.push(function(){Mn(xt,St)})}function re(){if(Q.length===0&&R===0)return B(null,T);for(;Q.length&&R<k;){var xt=Q.shift();xt()}}function Ln(xt,St){var Yt=q[xt];Yt||(Yt=q[xt]=[]),Yt.push(St)}function ze(xt){var St=q[xt]||[];ba(St,function(Yt){Yt()}),re()}function Mn(xt,St){if(!_){var Yt=Dn(function(gi,Df){if(R--,arguments.length>2&&(Df=o(arguments,1)),gi){var Lf={};js(T,function(UH,qH){Lf[qH]=UH}),Lf[xt]=Df,_=!0,q=Object.create(null),B(gi,Lf)}else T[xt]=Df,ze(xt)});R++;var Xn=x(St[St.length-1]);St.length>1?Xn(T,Yt):Xn(Yt)}}function zH(){for(var xt,St=0;W.length;)xt=W.pop(),St++,ba(VH(xt),function(Yt){--X[Yt]===0&&W.push(Yt)});if(St!==D)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function VH(xt){var St=[];return js(p,function(Yt,Xn){dn(Yt)&&va(Yt,xt,0)>=0&&St.push(Xn)}),St}};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 K$="[object Symbol]";function J$(p){return typeof p=="symbol"||ga(p)&&ko(p)==K$}var X$=1/0,_9=tt?tt.prototype:void 0,N9=_9?_9.toString:void 0;function bf(p){if(typeof p=="string")return p;if(dn(p))return hi(p,bf)+"";if(J$(p))return N9?N9.call(p):"";var k=p+"";return k=="0"&&1/p==-X$?"-0":k}function tH(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 eH(p,k,B){var I=p.length;return B=B===void 0?I:B,!k&&B>=I?p:tH(p,k,B)}function nH(p,k){for(var B=p.length;B--&&va(k,p[B],0)>-1;);return B}function oH(p,k){for(var B=-1,I=p.length;++B<I&&va(k,p[B],0)>-1;);return B}function rH(p){return p.split("")}var iH="\\ud800-\\udfff",sH="\\u0300-\\u036f",lH="\\ufe20-\\ufe2f",cH="\\u20d0-\\u20ff",aH=sH+lH+cH,dH="\\ufe0e\\ufe0f",uH="\\u200d",hH=RegExp("["+uH+iH+aH+dH+"]");function fH(p){return hH.test(p)}var P9="\\ud800-\\udfff",mH="\\u0300-\\u036f",gH="\\ufe20-\\ufe2f",pH="\\u20d0-\\u20ff",CH=mH+gH+pH,bH="\\ufe0e\\ufe0f",vH="["+P9+"]",vf="["+CH+"]",kf="\\ud83c[\\udffb-\\udfff]",kH="(?:"+vf+"|"+kf+")",$9="[^"+P9+"]",H9="(?:\\ud83c[\\udde6-\\uddff]){2}",j9="[\\ud800-\\udbff][\\udc00-\\udfff]",yH="\\u200d",F9=kH+"?",z9="["+bH+"]?",wH="(?:"+yH+"(?:"+[$9,H9,j9].join("|")+")"+z9+F9+")*",BH=z9+F9+wH,EH="(?:"+[$9+vf+"?",vf,H9,j9,vH].join("|")+")",IH=RegExp(kf+"(?="+kf+")|"+EH+BH,"g");function xH(p){return p.match(IH)||[]}function V9(p){return fH(p)?xH(p):rH(p)}function SH(p){return p==null?"":bf(p)}var TH=/^\s+|\s+$/g;function DH(p,k,B){if(p=SH(p),p&&(B||k===void 0))return p.replace(TH,"");if(!p||!(k=bf(k)))return p;var I=V9(p),D=V9(k),T=oH(I,D),R=nH(I,D)+1;return eH(I,T,R).join("")}var LH=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,MH=/,/,RH=/(=.+)?(\s*)$/,AH=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function OH(p){return p=p.toString().replace(AH,""),p=p.match(LH)[2].replace(" ",""),p=p?p.split(MH):[],p=p.map(function(k){return DH(k.replace(RH,""))}),p}function U9(p,k){var B={};js(p,function(I,D){var T,R=L(I),_=!R&&I.length===1||R&&I.length===0;if(dn(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=OH(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(Et){return Q[Et]});X.push(W),x(I).apply(null,X)}}),Cf(B,k)}function un(){this.head=this.tail=null,this.length=0}function q9(p,k){p.length=1,p.head=p.tail=k}un.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},un.prototype.empty=function(){for(;this.head;)this.shift();return this},un.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},un.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},un.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):q9(this,p)},un.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):q9(this,p)},un.prototype.shift=function(){return this.head&&this.removeLink(this.head)},un.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},un.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},un.prototype.remove=function(p){for(var k=this.head;k;){var B=k.next;p(k)&&this.removeLink(k),k=B}return this};function W9(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,Et,re){if(re!=null&&typeof re!="function")throw new Error("task callback must be a function");if(W.started=!0,dn(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:re||ft};Et?W._tasks.unshift(Mn):W._tasks.push(Mn)}R||(R=!0,m(function(){R=!1,W.process()}))}function q(X){return function(Et){D-=1;for(var re=0,Ln=X.length;re<Ln;re++){var ze=X[re],Mn=va(T,ze,0);Mn===0?T.shift():Mn>0&&T.splice(Mn,1),ze.callback.apply(ze,arguments),Et!=null&&W.error(Et,ze.data)}D<=W.concurrency-W.buffer&&W.unsaturated(),W.idle()&&W.drain(),W.process()}}var Q=!1,W={_tasks:new un,concurrency:k,payload:B,saturated:ft,unsaturated:ft,buffer:k/4,empty:ft,drain:ft,error:ft,started:!1,paused:!1,push:function(X,Et){_(X,!1,Et)},kill:function(){W.drain=ft,W._tasks.empty()},unshift:function(X,Et){_(X,!0,Et)},remove:function(X){W._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!W.paused&&D<W.concurrency&&W._tasks.length;){var X=[],Et=[],re=W._tasks.length;W.payload&&(re=Math.min(re,W.payload));for(var Ln=0;Ln<re;Ln++){var ze=W._tasks.shift();X.push(ze),T.push(ze),Et.push(ze.data)}D+=1,W._tasks.length===0&&W.empty(),D===W.concurrency&&W.saturated();var Mn=Dn(q(X));I(Et,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 G9(p,k){return W9(p,1,k)}var fi=te(ur,1);function Bo(p,k,B,I){I=yo(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 yf(){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,Bo(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 Z9=function(){return yf.apply(null,o(arguments).reverse())},_H=Array.prototype.concat,ka=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]&&(_=_H.apply(_,R[q]));return I(T,_)})},Y9=te(ka,1/0),Q9=te(ka,1),K9=function(){var p=o(arguments),k=[null].concat(p);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Fs(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,Et){X?W(X):p(Et)&&!_?(R=!0,_=k(!0,q),W(null,hf)):W()})},function(q){q?T(q):T(null,R?_:k(!1))})}}function J9(p,k){return k}var ya=ai(mi(Fs,J9)),zs=di(mi(Fs,J9)),wa=te(zs,1);function X9(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]&&ba(D,function(T){console[p](T)}))}),x(k).apply(null,B)}}var t7=X9("dir");function e7(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 wf(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 n7(p,k,B){wf(p,function(){return!k.apply(this,arguments)},B)}function o7(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 r7(p){return function(k,B,I){return p(k,I)}}function Ba(p,k,B){wo(p,r7(x(k)),B)}function Vs(p,k,B,I){pa(k)(p,r7(x(B)),I)}var Us=te(Vs,1);function Bf(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 Ea(p){return!p}var Ia=ai(mi(Ea,Ea)),qs=di(mi(Ea,Ea)),xa=te(qs,1);function i7(p){return function(k){return k==null?void 0:k[p]}}function NH(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 PH(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}),i7("value")))})}function Ef(p,k,B,I){var D=$s(k)?NH:PH;D(p,k,x(B),I||ft)}var Sa=ai(Ef),Ws=di(Ef),Ta=te(Ws,1);function s7(p,k){var B=Dn(k||ft),I=x(Bf(p));function D(T){if(T)return B(T);I(D)}D()}var Da=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,_)})},l7=te(Da,1/0),c7=te(Da,1),a7=X9("log");function La(p,k,B,I){I=yo(I||ft);var D={},T=x(B);ur(p,k,function(R,_,q){T(R,_,function(Q,W){if(Q)return q(Q);D[_]=W,q()})},function(R){I(R,D)})}var d7=te(La,1/0),u7=te(La,1);function h7(p,k){return k in p}function f7(p,k){var B=Object.create(null),I=Object.create(null);k=k||Fs;var D=x(p),T=i(function(_,q){var Q=k.apply(null,_);h7(B,Q)?m(function(){q.apply(null,B[Q])}):h7(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 Et=0,re=X.length;Et<re;Et++)X[Et].apply(null,W)})))});return T.memo=B,T.unmemoized=p,T}var Ma;c?Ma=process.nextTick:l?Ma=setImmediate:Ma=a;var m7=u(Ma);function If(p,k,B){B=B||ft;var I=$s(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 g7(p,k){If(wo,p,k)}function p7(p,k,B){If(pa(k),p,B)}var xf=function(p,k){var B=x(p);return W9(function(I,D){B(I[0],D)},k,1)},C7=function(p,k){var B=xf(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,dn(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 b7(p,k){if(k=yo(k||ft),!dn(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 Ra(p,k,B,I){var D=o(p).reverse();Bo(D,k,B,I)}function Aa(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 v7(p){var k;return dn(p)?k=hi(p,Aa):(k={},js(p,function(B,I){k[I]=Aa.call(this,B)})),k}function k7(p,k,B,I){Ef(p,k,function(D,T){B(D,function(R,_){T(R,!_)})},I)}var y7=ai(k7),Sf=di(k7),w7=te(Sf,1);function B7(p){return function(){return p}}function Oa(p,k,B){var I=5,D=0,T={times:I,intervalFunc:B7(D)};function R(W,X){if(typeof X=="object")W.times=+X.times||I,W.intervalFunc=typeof X.interval=="function"?X.interval:B7(+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 E7=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?Oa(p,T,D):Oa(T,D)})};function I7(p,k){If(fi,p,k)}var _a=ai(mi(Boolean,Fs)),Gs=di(mi(Boolean,Fs)),Na=te(Gs,1);function x7(p,k,B){var I=x(k);Ca(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),i7("value")))});function D(T,R){var _=T.criteria,q=R.criteria;return _<q?-1:_>q?1:0}}function S7(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 $H=Math.ceil,HH=Math.max;function jH(p,k,B,I){for(var D=-1,T=HH($H((k-p)/(B||1)),0),R=Array(T);T--;)R[I?T:++D]=p,p+=B;return R}function Pa(p,k,B,I){var D=x(B);ui(jH(0,p,1),k,D,I)}var T7=te(Pa,1/0),D7=te(Pa,1);function L7(p,k,B,I){arguments.length<=3&&(I=B,B=k,k=dn(p)?[]:{}),I=yo(I||ft);var D=x(B);wo(p,function(T,R,_){D(k,T,R,_)},function(T){I(T,k)})}function M7(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 R7(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function Tf(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 A7(p,k,B){Tf(function(){return!p.apply(this,arguments)},k,B)}var O7=function(p,k){if(k=yo(k||ft),!dn(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([])},FH={apply:r,applyEach:A9,applyEachSeries:O9,asyncify:C,auto:Cf,autoInject:U9,cargo:G9,compose:Z9,concat:Y9,concatLimit:ka,concatSeries:Q9,constant:K9,detect:ya,detectLimit:zs,detectSeries:wa,dir:t7,doDuring:e7,doUntil:n7,doWhilst:wf,during:o7,each:Ba,eachLimit:Vs,eachOf:wo,eachOfLimit:ur,eachOfSeries:fi,eachSeries:Us,ensureAsync:Bf,every:Ia,everyLimit:qs,everySeries:xa,filter:Sa,filterLimit:Ws,filterSeries:Ta,forever:s7,groupBy:l7,groupByLimit:Da,groupBySeries:c7,log:a7,map:Ca,mapLimit:ui,mapSeries:pf,mapValues:d7,mapValuesLimit:La,mapValuesSeries:u7,memoize:f7,nextTick:m7,parallel:g7,parallelLimit:p7,priorityQueue:C7,queue:xf,race:b7,reduce:Bo,reduceRight:Ra,reflect:Aa,reflectAll:v7,reject:y7,rejectLimit:Sf,rejectSeries:w7,retry:Oa,retryable:E7,seq:yf,series:I7,setImmediate:m,some:_a,someLimit:Gs,someSeries:Na,sortBy:x7,timeout:S7,times:T7,timesLimit:Pa,timesSeries:D7,transform:L7,tryEach:M7,unmemoize:R7,until:A7,waterfall:O7,whilst:Tf,all:Ia,allLimit:qs,allSeries:xa,any:_a,anyLimit:Gs,anySeries:Na,find:ya,findLimit:zs,findSeries:wa,forEach:Ba,forEachSeries:Us,forEachLimit:Vs,forEachOf:wo,forEachOfSeries:fi,forEachOfLimit:ur,inject:Bo,foldl:Bo,foldr:Ra,select:Sa,selectLimit:Ws,selectSeries:Ta,wrapSync:C};e.default=FH,e.apply=r,e.applyEach=A9,e.applyEachSeries=O9,e.asyncify=C,e.auto=Cf,e.autoInject=U9,e.cargo=G9,e.compose=Z9,e.concat=Y9,e.concatLimit=ka,e.concatSeries=Q9,e.constant=K9,e.detect=ya,e.detectLimit=zs,e.detectSeries=wa,e.dir=t7,e.doDuring=e7,e.doUntil=n7,e.doWhilst=wf,e.during=o7,e.each=Ba,e.eachLimit=Vs,e.eachOf=wo,e.eachOfLimit=ur,e.eachOfSeries=fi,e.eachSeries=Us,e.ensureAsync=Bf,e.every=Ia,e.everyLimit=qs,e.everySeries=xa,e.filter=Sa,e.filterLimit=Ws,e.filterSeries=Ta,e.forever=s7,e.groupBy=l7,e.groupByLimit=Da,e.groupBySeries=c7,e.log=a7,e.map=Ca,e.mapLimit=ui,e.mapSeries=pf,e.mapValues=d7,e.mapValuesLimit=La,e.mapValuesSeries=u7,e.memoize=f7,e.nextTick=m7,e.parallel=g7,e.parallelLimit=p7,e.priorityQueue=C7,e.queue=xf,e.race=b7,e.reduce=Bo,e.reduceRight=Ra,e.reflect=Aa,e.reflectAll=v7,e.reject=y7,e.rejectLimit=Sf,e.rejectSeries=w7,e.retry=Oa,e.retryable=E7,e.seq=yf,e.series=I7,e.setImmediate=m,e.some=_a,e.someLimit=Gs,e.someSeries=Na,e.sortBy=x7,e.timeout=S7,e.times=T7,e.timesLimit=Pa,e.timesSeries=D7,e.transform=L7,e.tryEach=M7,e.unmemoize=R7,e.until=A7,e.waterfall=O7,e.whilst=Tf,e.all=Ia,e.allLimit=qs,e.allSeries=xa,e.any=_a,e.anyLimit=Gs,e.anySeries=Na,e.find=ya,e.findLimit=zs,e.findSeries=wa,e.forEach=Ba,e.forEachSeries=Us,e.forEachLimit=Vs,e.forEachOf=wo,e.forEachOfSeries=fi,e.forEachOfLimit=ur,e.inject=Bo,e.foldl=Bo,e.foldr=Ra,e.select=Sa,e.selectLimit=Ws,e.selectSeries=Ta,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(Rd,Rd.exports);var P0={exports:{}},Ad=P0.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)?Ad(n,t):i};Ad.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=Ad(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 $0=co,Py=_0,$y=N0,Kl=tn,Od=Rd.exports,Hy=P0.exports,H0=qo.ACTIONS,j0=Pt;function Pt(n,t){if($0.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}$0.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||Hy();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);Od.parallel([function(i){Od.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Od.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?H0.presenceSubscribe:H0.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 Py(this,n)},Pt.prototype._createRemotePresence=function(n){return new $y(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=Kl.callEach(n,t);!e&&t&&this.emit("error",t)};var Yi=_0,F0=Wl,jy=tn,z0=F0.CODES,Fy=nn;function nn(n,t){Yi.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()}nn.prototype=Object.create(Yi.prototype),nn.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:z0.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,Yi.prototype.submit.call(this,n,t)},nn.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),Yi.prototype.destroy.call(this,n)},nn.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={})})}},nn.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)},nn.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)}},nn.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},nn.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},nn.prototype._message=function(){var n=Yi.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},nn.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!jy.supportsPresence(o))throw new F0(z0.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var V0={};(function(n){var t=Wi,e=Wl,o=tn,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,w=0;w<C.length;w++){var E=C[w];Object.prototype.toString.call(v)=="[object Array]"?C[w]=+E:v.constructor===Object&&(C[w]=E.toString()),v=v[E]}f<a.length-1&&(u=t.defaultType.apply(u,[m]))}}}}})(V0);var Qi=N0,zy=V0,Vy=Pe;function Pe(n,t){Qi.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(Qi.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),Qi.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()},Qi.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Qi.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++):zy.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 U0=j0,Uy=Fy,qy=Vy;function Ar(n,t,e){var o=Ar.channel(t,e);U0.call(this,n,o),this.collection=t,this.id=e}var Wy=Ar;Ar.prototype=Object.create(U0.prototype),Ar.channel=function(n,t){return n+"."+t},Ar.prototype._createLocalPresence=function(n){return new Uy(this,n)},Ar.prototype._createRemotePresence=function(n){return new qy(this,n)};var Gy=Zy;function Zy(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var Yy=Gy,q0=co,W0=Ki;function Ki(n,t,e,o,r){if(q0.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}q0.mixin(Ki),Ki.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ki.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ki.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new Yy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var G0=W0,Qy=tn,Ky=qo.ACTIONS,Jy=_d;function _d(n,t,e,o,r,i){if(G0.call(this,n,t,e,o,i),!Qy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}_d.prototype=Object.create(G0.prototype),_d.prototype._message=function(){return{a:Ky.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Z0=W0,Xy=tn,tw=qo.ACTIONS,ew=Nd;function Nd(n,t,e,o,r,i){if(Z0.call(this,n,t,e,o,i),!Xy.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Nd.prototype=Object.create(Z0.prototype),Nd.prototype._message=function(){return{a:tw.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var nw=Ty,ow=Ay,rw=j0,Y0=Wy,iw=Jy,sw=ew,Q0=co,Or=Wl,pt=qo.ACTIONS,K0=Wi,on=tn,Ji=x0,Xi=Or.CODES;function J0(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var lw=J;function J(n){Q0.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=J0(n),this.bindToSocket(n)}Q0.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=J0(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{Ji.warn("Failed to parse message",o);return}e.debug&&Ji.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){on.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=X0(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:Ji.warn("Ignoring unrecognized message",n)}};function X0(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](X0(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 Ji.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 Or(Xi.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&&Ji.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},J.prototype.ping=function(){if(!this.canSend)throw new Or(Xi.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 nw(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},J.prototype._destroyDoc=function(n){!n._wantsDestroy||(on.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 ow(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(cw)};function cw(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}on.nextTick(n)},J.prototype._nothingPendingRetry=function(n){var t=this;return function(){on.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 iw(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 sw(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 Or(Xi.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(K0.map[n.type]!==K0.defaultType)return this.emit("error",new Or(Xi.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Or(Xi.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=on.digOrCreate(this._presences,n,function(){return new rw(t,n)});return e._wantsDestroy=!1,e},J.prototype.getDocPresence=function(n,t){var e=Y0.channel(n,t),o=this,r=on.digOrCreate(this._presences,e,function(){return new Y0(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){on.digOrCreate(this._presences,n.channel,function(){return n})},J.prototype._handlePresenceSubscribe=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},J.prototype._handlePresenceUnsubscribe=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},J.prototype._handlePresence=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},J.prototype._handlePresenceRequest=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var t5=lw,aw=Wi;const Xl={err:1001,msg:"user auth error",name:"AuthError"},dw={err:1002,msg:"you don't have required permission",name:"PermissionError"},Pd={err:1003,msg:"Too many user connected",name:"MaxUserError"},ts={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},uw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},hw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},es="x-live-editor-token",tc="x-live-editor-base-url",ae=y("auth-connection");function fw(n){try{n()}catch(t){ae.error(t)}}class mw{constructor(t,e){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new Mf.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 Lo(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:{[es]: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]:Lo(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new a8.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(t5.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);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l);return}throw l}}},t5.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(ts.msg);t.code=ts.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t){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===Pd.err)ae.warn(Pd.msg),this.emitMaxUsersError();else if(o===ts.err){ae.warn(ts.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(),fw(()=>{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()}}y("utils/file");function gw(){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}gw();async function pw(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new d8.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 Lo(i)}const vn=y("sharedb-doc/client");class Cw{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(vn,!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),vn.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;aw.register(Ys.type),this.connection=new mw(r,o),this.reAuthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(vn,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,{[es]: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=>{vn.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await pw(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 vn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(vn,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[es]:this.connection.token},e,o);return d(vn,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(vn,o,"no token"),c.headers={...c.headers,[es]:o,[tc]:this.connection.getBase64BaseURL()};try{return await l8.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(vn,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=c8.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(vn,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/${Lo(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 bw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const $d=y("block-ids");class vw{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($d,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($d,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 kw{constructor(){h(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new vw,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($d,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class e5{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=y("op-parser");function _r(n){return n==="blocks"?"root":n}class yw{constructor(t,e){h(this,"updatingBlockDataDeltaMap",new Map);h(this,"blockIds",new kw);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 e5,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 e5,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 n5{}class Hd{constructor(t){h(this,"key");this.key=t}}function ww(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 jd(n,t,e,o){if(e==="upsert"&&ww(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 Hd(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 n5),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 Hd(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof n5?o.onDeleteBlock(n,i):l instanceof Hd?o.onDeleteBlockData(n,i,l.key):d(Nt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function Bw(n,t,e,o){Nt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Ew(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 Fd(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Fd(l,t,e,o)});return}const i=r;if(d(Nt,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){Bw(n);return}if(i==="comments"){Ew(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{jd(s,l,t,e)}):n.slice(1).forEach(l=>{jd(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)}`),jd(s,n.slice(1),t,e)}function o5(n,t,e){const o=new yw(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=>{Fd(c,i,o,t)}):Fd(s,i,o,t)}o.executeUpdateBlockDataActions()}const Iw=y("sharedb-comments");function xw(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(Iw,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 Sw(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 r5(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const Dt=y("sharedb-doc/doc-container"),i5="ot-json1";Ys.type.registerSubtype(dy.type),Ys.type.name=i5,Ys.type.invert=null;class ec extends ki{constructor(e,o){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new cy);h(this,"batching",0);h(this,"status","clean");h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.callbacks.forEach(e=>{var o;return(o=e.onRequestReload)==null?void 0:o.call(e,"doc created")})});h(this,"handleDel",()=>{});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(!Zs.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)=>{this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(Dt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i)):o()}),d(Dt,this.doc.data,"no data after submit op, may be the submitted op is invalid")}));h(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,i5,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)=>{o5(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(Dt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new Cw(e.auth,e.serverUrl,e.reAuthFunc),r=await o.getDoc(),i=new ec(o,r);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||bw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw Dt.error(o),Dt.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)}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 Ui(this.data())}getContainerBlocks(e){const o=this.data();d(Dt,o,"no doc data");const r=o[lo(e)];return d(Dt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=lo(e),i=this.getContainerBlocks(r);d(Dt,i,`no container data: ${r}`);const s=i[o];return d(Dt,s,`no block data: ${o}`),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(Dt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=ne.apply(s,r);return d(Dt,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=>Sw(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return xw(o)}localCreateComment(e,o){const r=r5(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=r5(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!1),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){d(Dt,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(Dt,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(Dt,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(Dt,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(Dt,this.callbacks.length>0,"no callbacks"),d(Dt,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(Dt,this.callbacks.length>0,"no callbacks"),d(Dt,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(Dt,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(Dt,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(Dt,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 Ui(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Ui(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:Ui(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Ui(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){o5(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}y("remote-cursor");class s5{constructor(t){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",ie.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 l5=y("remote-cursor-decorator");class zd{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(l5,typeof s=="string","invalid path containerId"),d(l5,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(w=>({id:N(),type:"remote-cursor",name:w.user.displayName,time:w.time,rainbowIndex:w.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class c5 extends Wt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Ct(br(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 Tw(n,t){n.addCustom("child-block-tracker",()=>new c5(n)).addListener("change",t)}function Dw(n,t){n.addCustom("child-block-tracker",()=>new c5(n)).removeListener("change",t)}const dF="",Lw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Mw={colorPalette:{colorDesc:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};S.mergeLang({"zh-CN":Lw,"en-US":Mw});const uF="",Rw=y("button");function Aw(n){const t=n.getAttribute("data-button-id");return t||d(Rw,!1,"unknown button id"),t}function Ow(n){var e;if(!(n instanceof Node))return null;const t=n.parentElement;return t?n instanceof HTMLButtonElement&&n.classList.contains("editor-button")?n:(e=t.closest("button.editor-button"))!=null?e:null:null}function kn(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 Vd(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}function _w(n){return b("span",["editor-separator",n],null)}const uo=y("filterable-list");function Nw(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 a5(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Nw(e))}),t}function d5(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Pw(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=a5(d5(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function u5(n,t,e){const o=n.querySelector(".list");d(uo,o,"no list root");const r=a5(d5(t,e)),i=o.querySelector(".list-root");if(d(uo,i,"no exists menu"),xi(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(uo,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class h5{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=Pw(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,u5(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)),u5(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 f5 extends h5{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=za.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 hF="",fF="";function m5(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 mF="",Nr=y("ui-command-bar-base"),$w={itemElementTag:"div",tippyArrow:!1},df=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){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)}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id)}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),um(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.emit("show",this),this.options.disablePageScroll&&dm(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=Nn(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={...$w,...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)}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=df.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){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),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 ho=df;h(ho,"commandBarCreators",new Map),y("ui-command-bar");class nc extends ho{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=za.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]}),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 Hw(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const g5={"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"},...Hw()};function Ud(n){var t,e,o;return(o=(e=n.shortcut)!=null?e:(t=g5[n.id])==null?void 0:t.shortcut)!=null?o:""}function jw(n){var t,e;return(e=(t=g5[n.id])==null?void 0:t.markdown)!=null?e:""}const qd=`<?xml version="1.0" ?>
26
+ `)}function sd(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Lo(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function ld(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=ev(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function nv(n,t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData||n.selection.range.isCollapsed())return;const e=jl(n);ld(n,e);const o=rd(n,e),r=id(n,e),i=sd(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 ov(n){if(n.selection.range.isCollapsed())return;const t=jl(n);ld(n,t);const e=rd(n,t),o=sd(e,t),r=new Blob([o],{type:"text/html"});il([{type:"text/html",data:r}])}async function cd(n,t){const e=nd(n,t,!1);ld(n,e);const o=rd(n,e),r=id(n,e),i=sd(o,e);return il([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}const ad=y("editor-input");class rv{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)&&!Ti(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=>{nv(this.editor,t)});h(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}ad.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(),It.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(ad,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(ad,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function iv(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 dd=y("editor-caret");class sv{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 Vt))return!1;const e=this.editor.getBlockById(t.blockId);return!!j(this.editor,e)}update(){if(Vf(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",iv(this.editor);return}const{range:e}=this.editor.selection;d(dd,e.isCollapsed,"range is not collapsed");const o=e.start;d(dd,o instanceof Vt,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(dd,j(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=xo(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Oe(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`,It.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`)}}function lv(n){Wm(n),n.selection.range.getSelectedBlocks().forEach(t=>Gm(n,t.block,t.start,t.end))}function L2(n){return Nn(n.rootContainer).clientHeight}function cv(n){return n.getFirstBlock().getBoundingClientRect().top}function av(n){return n.getLastBlock().getBoundingClientRect().bottom}function ud(n){const t=Nn(n.rootContainer);return new DOMRect(t.clientLeft,t.clientTop,t.clientWidth,t.clientHeight)}function dv(n,t){const e=ud(n),o=n.getBlockById(t.blockId),i=Ge(n,o,t);return To(e,i.x,i.y)&&To(e,i.right,i.bottom)}function uv(n,t){const e=ud(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function hv(n,t){const e=ud(n),o=t.getBoundingClientRect();return To(e,o.x,o.y)||To(e,o.right,o.bottom)}function fv(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,u=n.getContainerById(a.childContainerId);hv(n,u)||u.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(Te(a)&&uv(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(dv(n,o))return;const i=Ge(n,r,o),s=r.getBoundingClientRect(),l=At(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,Ei(c),setTimeout(()=>{c.remove()})}function mv(n,t){if(t.isCollapsed())return!1;const e=Qt(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=y("editor-selection");class gv{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(h2(e,i)){Fl.debug("adjust selection because remote deleted current block");const s=f2(t,e);this.setRange(s)}});this.editor=t;const e=t.getFirstBlock(),o=G(e);this.caret=new sv(t);const r=$(o,0,"normal");this._range=Ut(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=Ut(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()||!mv(this.editor,r))&&F(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t){return this.setSelection(t.anchor,t.focus)}updateSelection(){this.caret.update(),lv(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(!kr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ge(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){fv(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=H(t);for(;qe(e);){const o=z(e);d(Fl,o,"parent block not found"),M(o,"child-focused"),e=H(o)}return!0}}const M2=y("line-offset");function hd(n){const t=n.selection.range.focus;d(M2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!j(n,e))return $(e,0,"home");let r=vg(e,t).start;const{next:i}=gl(e,r);return i&&Me(i)&&Si(i)==="br"&&(r+=1),$(e,r,"home")}function fd(n){const t=n.selection.range.focus;d(M2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===Z(n,e)||!j(n,e))return $(e,0,"end");const o=vg(e,t);return $(e,o.end,"end")}function pv(n){if(!n.selection.range.focus.isSimple())return;const e=hd(n),o=fd(n);!e||!o||n.selection.setSelection(e,o)}const Ne=y("block-text");function R2(n,t,e){d(Ne,j(n,t),"not a text kind block"),d(Ne,fe(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=ke(n,t),{middle:s}=Kt(i,o,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return E1(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:o,length:l.insert.length}}function A2(n,t,e){d(Ne,j(n,t),"not a text kind block"),d(Ne,fe(t,e),"not a valid offset"),d(Ne,e>=0&&e<Z(n,t),`invalid offset: ${e}`);const r=Ir(t,e)-e;r===0&&d(Ne,!1,`no text after offset: ${e}`);const i=ke(n,t),{middle:s}=Kt(i,e,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return E1(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:e,length:l.insert.length}}function O2(n,t,e,o){let r=e;for(;r>0;){const i=R2(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function _2(n,t,e,o){const r=Z(n,t);let i=e;for(;i<r;){const s=A2(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function N2(n,t,e){if(d(Ne,j(n,t),"invalid blok type"),wt(n,t))return 0;const o=R2(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=O2(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=O2(n,t,r,"text");return i?i.offset+i.length:0}function P2(n,t,e){if(d(Ne,j(n,t),"invalid blok type"),wt(n,t))return 0;const o=A2(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=_2(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=_2(n,t,r,"text");return i?i.offset:Z(n,t)}const $2=y("word-offset");function md(n,t){const e=n.selection.range.focus;d($2,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(wt(n,o))return $(o,0,"home");if(e.offset===0||!j(n,o)){const s=gt(o);if(!s)return null;const l=$(s,Z(n,s),"end");if(t==="select"&&j(n,s)){const c=N2(n,s,l.offset);return $(s,c,"normal")}return l}const r=N2(n,o,e.offset);return $(o,r,"normal")}function gd(n,t){const e=n.selection.range.focus;d($2,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(wt(n,o))return $(o,0,"end");if(e.offset===Z(n,o)||!j(n,o)){const s=ht(o);if(!s)return null;const l=$(s,0,"home");if(t==="select"&&j(n,s)){const c=P2(n,s,l.offset);return $(s,c,"end")}return l}const r=P2(n,o,e.offset);return $(o,r,"normal")}function Cv(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!j(n,e))return;const o=md(n,"select"),r=gd(n,"select");!o||!r||n.selection.setSelection(o,r)}const me=y("adjust-selection-pos");function H2(n){const t=[];for(;n;){const e=H(n);if(t.unshift(e),Ct(e))return t;const o=z(e);d(me,o,"child container has not parent container"),n=o}d(me,!1,"should not come here: getParentContainers")}function j2(n,t){for(;t;){const e=H(t);if(e===n)return t;const o=z(e);d(me,o,"could not find parent block for a child container"),t=o}d(me,!1,"no parent block in specified container")}function bv(n,t){const e=H2(n),o=H2(t);d(me,e.length>0&&o.length>0,"block has not parent container"),d(me,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=j2(r,n),s=j2(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function F2(n,t){let e=z(t);for(d(me,e,"element is not in a block");e;){const o=H(e);d(me,qe(o),"not a child container");const r=z(o);if(d(me,r,"child container has not parent block"),r===n)return o;e=r}d(me,!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 Vt&&e instanceof Vt?{anchor:t,focus:e}:(d(me,t instanceof Ze&&e instanceof Ze,"both start and end are not simple or complex"),ml(n,o,t,e));const i=H(o),s=H(r);if(i===s)return t instanceof Ze&&(t=$(o,0,"home")),e instanceof Ze&&(e=$(r,Z(n,r),"end")),d(me,t instanceof Vt,"not valid position type"),d(me,e instanceof Vt,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Vt&&e instanceof Ze){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const w=z(i);if(w&&w===z(v)){const E=bt(w,V(i)),L=bt(w,V(v));return ml(n,w,E,L)}}return null}const l=Xs(o,r)>0,{newBlock1:c,newBlock2:a}=bv(o,r);if(c===a){const v=c,w=F2(v,o),E=F2(v,r);return t=bt(c,V(w)),e=bt(c,V(E)),me.debug(`select in complex block: ${w.id}, ${E.id}`),ml(n,v,t,e)}let u=l?Z(n,c):0;c===o&&t instanceof Vt&&(u=t.offset);let m=l?0:Z(n,a);return a===r&&e instanceof Vt&&(m=e.offset),t=$(c,u,l?"end":"home"),e=$(a,m,l?"home":"end"),{anchor:t,focus:e}}const vv=y("range-from-point");function z2(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 V2(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Qt(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 kv(n,t,e){const o=z2(n,t,e);if(o){if(o instanceof se)return o;d(vv,o instanceof Ye,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return V2(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=>fn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const u=c.getBoundingClientRect(),f=a.getBoundingClientRect();return hn(u,t,e)>hn(f,t,e)?a:c});return V2(n,l,t,e)}class yv{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=kv(this.editor,t.x,t.y);if(e){if(e instanceof Ye)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=z2(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){Cv(this.editor)}handleTripleClick(t){pv(this.editor)}}const wv=y("move-complex-block-position");function Bv(n,t,e){const o=n.getBlockById(t.blockId);d(wv,ct(n,o),"is not a complex block");const r=ve(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?bt(o,V(s)):null}const ji=y("move-simple-block-position");function U2(n,t){const e=Le(n,t);d(ji,e.length>0,"complex block has not any child container");const o=e[0];return Qt(o)}function q2(n,t){const e=Le(n,t);d(ji,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Gt(o)}function W2(n,t,e){const o=e?U2(n,t):q2(n,t);return ct(n,o)?W2(n,o,e):o}function Ev(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===0?U2(n,e):Cr(e)}function Iv(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===1?q2(n,e):pr(e)}function pd(n){return n==="ArrowLeft"||n==="ArrowUp"}function Cd(n,t,e){const o=H(t);if(Ct(o))return null;const r=z(o);d(ji,r,"child container has not parent block"),d(ji,ct(n,r),"is not a complex block");const i=ve(n,r).getNextContainer(n,r,o,e);return i?pd(e)?Gt(i):Qt(i):Cd(n,r,e)}function xv(n,t,e){const o=H(t);if(Ct(o))return null;const r=z(o);if(d(ji,r,"child container has not parent block"),pd(e)){const l=gt(r);if(l)return l}else{const l=ht(r);if(l)return l}const i=Cd(n,r,e);if(i)return i;let s=r;for(;!Ct(H(s));)s=z(H(s));return pd(e)?gt(s):ht(s)}function Sv(n,t,e){return!ct(n,t)||ve(n,t).enableKeyboardSelect?t:W2(n,t,e==="ArrowDown"||e==="ArrowRight")}function Tv(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"?Ev(n,t):Iv(n,t);if(s||(s=Cd(n,o,e),s||(s=xv(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Ct(H(o)))return null;const l=n.insertTextBlock("",V(n.rootContainer),Ve(n.rootContainer));return $(l,0,"home")}return null}if(s=Sv(n,s,e),j(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return ib(n,s,o,t,l);if(e==="ArrowUp")return rb(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?$(s,Z(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?$(s,0,"home"):null}function Dv(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(j(n,r))return o;const i=ht(r);if(i)return $(i,0,"home");if(!Ct(H(r))||n.readonly)return o;const s=n.insertTextBlock("",V(n.rootContainer),Ve(n.rootContainer));return $(s,0,"home")}function Lv(n,t,e){const o=n.selection.range;let r;if(o instanceof se)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=Dv(n,t,o):r=Tv(n,o.getFocusedPos(),t);else if(r=Bv(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=Qt(s);r=$(l,Z(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:zl(n,o.anchor,r):null}function io(n,t,e){const o=Lv(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 Mv(n){return io(n,"ArrowLeft","move"),!0}function Rv(n){return io(n,"ArrowRight","move"),!0}function Av(n){return io(n,"ArrowUp","move"),!0}function Ov(n){if(io(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=H(t);if(Ct(e)||Gt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",V(o),Ve(o)),!0}function _v(n){return io(n,"ArrowDown","select"),!0}function Nv(n){return io(n,"ArrowLeft","select"),!0}function Pv(n){return io(n,"ArrowRight","select"),!0}function $v(n){return io(n,"ArrowUp","select"),!0}function Hv(n){if(!n.selection.range.focus.isSimple())return!1;const e=md(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function jv(n){if(!n.selection.range.focus.isSimple())return!1;const e=gd(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Fv(n){if(!n.selection.range.focus.isSimple())return!1;const e=md(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function zv(n){if(!n.selection.range.focus.isSimple())return!1;const e=gd(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}y("find-block");function bd(n,t){if(!ct(n,t))return t;const o=ve(n,t).getChildContainers(n,t)[0],i=Rt(o)[0];return bd(n,i)}function vd(n,t){if(!ct(n,t))return t;const e=ve(n,t).getChildContainers(n,t),o=e[e.length-1],r=Rt(o),i=r[r.length-1];return vd(n,i)}function Vv(n){const t=vd(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(e),!0}function Uv(n){const t=bd(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(e),!0}function qv(n){const t=bd(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Wv(n){const t=vd(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Gv(n){if(!n.selection.range.focus.isSimple())return!1;const e=hd(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function Zv(n){if(!n.selection.range.focus.isSimple())return!1;const e=fd(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function Yv(n){if(!n.selection.range.focus.isSimple())return!1;const e=hd(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Qv(n){if(!n.selection.range.focus.isSimple())return!1;const e=fd(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const G2=y("find-block-position");function Kv(n,t,e,o){d(G2,ct(n,t),"is not a complex block");const r=ve(n,t).getChildContainers(n,t);d(G2,r.length>0,"complex block has not any child container");const i=Ge(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=ug(n,t,s,l);return kd(n,c,e,o)}function kd(n,t,e,o){if(ct(n,t))return Kv(n,t,e,o);const r=G(t);let i=Number.MAX_SAFE_INTEGER;const s=Ge(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=Ge(n,t,m),v=hn(C,l,c);v<i&&(i=v,a=m)}return a}const Z2=y("page-offset");function Jv(n,t){const e=L2(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<cv(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 Xv(n,t){const e=L2(n)*.9,o=t.getBoundingClientRect(),r=av(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 Y2(n){const t=n.selection.range.focus;d(Z2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Jv(n,e);let r;return o===n.getFirstBlock()?r=$(o,0,"home"):r=kd(n,o,e,t),r}function Q2(n){const t=n.selection.range.focus;d(Z2,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Xv(n,e);let r;return o===n.getLastBlock()?r=$(o,Z(n,o),"end"):r=kd(n,o,e,t),r}function tk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Y2(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ek(n){if(!n.selection.range.focus.isSimple())return!1;const e=Q2(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function nk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Y2(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 ok(n){if(!n.selection.range.focus.isSimple())return!1;const e=Q2(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 Fi=y("select-all");function rk(n,t){const e=t.getEditor(),o=ve(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=G(n);return t.start.blockId===s&&t.start.childContainerId===V(r)&&t.end.blockId===s&&t.end.childContainerId===V(i)}function ik(n,t){d(Fi,t,"no parent block"),d(Fi,ct(n,t),"not a complex block");const e=ve(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Ut(n,{anchor:bt(t,V(o)),focus:bt(t,V(r))}))}function K2(n,t){const e=H(t),o=Rt(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 sk(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&j(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"),K2(n,Qt(n.rootContainer)),!1}return d(Fi,!e.isSimple(),"invalid range type"),rk(t,e)?(K2(n,t),!1):(d(Fi,t,"no parent block"),d(Fi,ct(n,t),"not a complex block"),ik(n,t),!0)}function lk(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function ck(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const J2=y("delete-text");function X2(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Vt||d(J2,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(J2,j(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!fe(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 t0(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const ak=y("handle-backspace");function yd(n,t){if(!wt(n,t))return;const e=H(t);Ve(e)!==1&&n.deleteBlock(t)}function dk(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===0){if(t0(n,o))return;const r=gt(o);if(r)if(j(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ct(n,r)){yd(n,o);const i=wr(n,r);i?n.selection.selectBlock(i,Z(n,i)):n.selection.selectBlock(r,0,Z(n,r))}else yd(n,o),d(ak,Te(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=H(o);if(qe(i)){const s=cg(n,i);s&&(yd(n,o),n.selection.selectBlock(s,Z(n,s)))}}}else X2(n,"backward",1,null);else{const r=K(o),i=H(o);n.insertTextBlock("",V(i),r),n.deleteBlock(o)}}function uk(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===Z(n,o)){const r=ht(o);r&&(j(n,r)?n.mergeTextBlock(o,r,{focus:!0}):wt(n,o)?n.deleteBlock(o,Ot(n,r,0)):n.deleteBlock(r))}else X2(n,"forward",1,null);else{const r=K(o),i=H(o);n.insertTextBlock("",V(i),r),n.deleteBlock(o)}}function hk(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(j(n,e)){if(wt(n,e)&&t0(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 fk(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!j(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 mk=y("input-handler-actions");function gk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(hk(n),!0))}function pk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(uk(n),!0))}function Ck(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(dk(n),!0))}function bk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(fk(n),!0))}function vk(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(mk,o.isSimple(),"not simple position"),n.insertTextToBlock(e,o.offset,t)}),!0)}function kk(n){return ov(n),Y1(n),!0}const Vl={ArrowDown:Ov,ArrowUp:Av,ArrowLeft:Mv,ArrowRight:Rv,"Shift+ArrowDown":_v,"Shift+ArrowUp":$v,"Shift+ArrowLeft":Nv,"Shift+ArrowRight":Pv,"CtrlOrCmd+ArrowLeft":Hv,"CtrlOrCmd+ArrowRight":jv,"CtrlOrCmd+Shift+ArrowLeft":Fv,"CtrlOrCmd+Shift+ArrowRight":zv,"CtrlOrCmd+ArrowUp":Uv,"CtrlOrCmd+ArrowDown":Vv,"CtrlOrCmd+Shift+ArrowUp":qv,"CtrlOrCmd+Shift+ArrowDown":Wv,"CtrlOrCmd+A":sk,Home:Yv,End:Qv,"Shift+Home":Gv,"Shift+End":Zv,PageUp:tk,PageDown:ek,"Shift+PageUp":nk,"Shift+PageDown":ok,"CtrlOrCmd+X":kk,"CtrlOrCmd+Z":lk,"CtrlOrCmd+Shift+Z":ck,Enter:gk,Delete:pk,Backspace:Ck,"Shift+Enter":bk,"CtrlOrCmd+Shift+V":vk};function e0(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function n0(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=>{n0(n,l,e)})})}function o0(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):n0(t,r,e)})}async function yk(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 wk(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 Bk(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(wk(n,t)){const s=Array.from(Object.keys(o));r=await yk(n,s),o0(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&&o0(n,t,i)}async function Ek(n,t){await Bk(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Tr(n);n.insertDoc(e,o,t)})}const Ik=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function xk(n){let t;for(const e of Ik)if(t=n[e],t)break;return t||null}class Sk{constructor(t){h(this,"editor");h(this,"handlers",[]);this.editor=t}onInsertText(t,e){if(!j(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Tr(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}=Tr(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}=Tr(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=xk(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){V1(this.editor,i)}defaultHandleKeydown(t,e){return e0(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 Ek(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 Tk(n,t,e){const o=mr(t,e);return o.remove(),o}const wd=y("copy-dom-attributes"),r0=["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 Dk(n,t){for(let l=0;l<r0.length;l++){const c=r0[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=>{wd.debug(`add attribute: ${l.name}, ${l.value}`),t.setAttribute(l.name,l.value)}),i.forEach(l=>{wd.debug(`copy attribute: ${l.name}, ${l.value}`),t.setAttribute(l.name,l.value)}),s.forEach(l=>{wd.debug(`delete attribute: ${l.name}`),t.removeAttribute(l.name)})}function i0(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function s0(n,t,e){var a;const o=n.getContainerById(t),r=mr(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=i0(u);i0(r),f.forEach(C=>r.appendChild(C));const m=al(u);if(m){const C=al(r);C&&C.remove(),r.appendChild(m)}Dk(u,r)}Ym(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 Lk=y("transform-selection");function l0(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(Lk,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=ne.transformCursor(i.offset,e,o);l=$(t,a,"normal")}let c=s;if(s.blockId===t){const a=ne.transformCursor(s.offset,e,o);c=$(t,a,"normal")}return Ut(n,{anchor:l,focus:c})}const Mk=y("handle-block-text-changed");function Rk(n,t,e,o,r){const i=n.getContainerById(t),s=mr(i,e),l=n.doc.getBlockData(t,e);if(d(Mk,l.text,"no block text"),qm(n,s).setBlockText(n,s,l.text),!r){const c=l0(n,l.id,o,r);n.selection.setRange(c)}}function Ak(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function c0(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 Ok(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{c0(n,i,o,{child:!0})}),c0(n,r,o,{child:!1})}const so=y("editor-doc");class _k extends ki{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){d(so,this.editor.isWritable(),"editor is readonly");const i=this.getBlockData(e,o),s=i.text;d(so,s,`no text, ${e}, ${o}`);const l=l0(this.editor,i.id,r,!0),c=ne.apply(s,r);this.localEvents.forEach(u=>u.onBeforeUpdateBlockText(e,i.id,s,c,l.toDocRange()));const a=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(l),a}localUpdateBlockData(e,o,r,i){d(so,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Ak(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(no(this.editor,i)),c}localInsertBlock(e,o,r,i){d(so,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(l=>l.onBeforeInsertBlock(e,o,r,i));const s=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(no(this.editor,i)),s}localDeleteBlock(e,o,r){d(so,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(no(this.editor,r)),s}localDeleteChildContainers(e){return d(so,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(so,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){so.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})}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)}),Rk(this.editor,e,o,r,i),i&&this.editor.emit("docChanged",this.editor)}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)}),s0(this.editor,e,o),i&&this.editor.emit("docChanged",this.editor)}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);lC(this.editor,s,o,r),i&&this.editor.emit("docChanged",this.editor)}onDeleteBlock(e,o,r){Ok(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);Tk(this.editor,i,o),r&&this.editor.emit("docChanged",this.editor)}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:{}}}function a0(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 Bd=y("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(Bd,t,"no other action"),!1}combine(t){d(Bd,!1,"no other")}setAfterRange(t){this.afterRange&&Bd.warn("after range has already set"),this.afterRange=t}}const Nk=y("block-action");class d0 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(Nk,this.blockIndex===K(i),"invalid block index"),W1(e,i,no(e,o)),!0):!1}insertBlock(e,o){return Dr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Pk extends d0{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class $k extends d0{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class Hk extends Mr{constructor(e){super(e,V(e.rootContainer),e.selection.range.toDocRange());h(this,"actions",[])}addAction(e){a0(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=y("update-block-data-action");class Ul 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,Ul.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,Ul.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const Ed=y("update-block-text-action");class zi 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=zi.calType(i,s)}static calType(e,o){d(Ed,e,"no old data"),d(Ed,o,"no new data");const i=ne.diff(e,o),s=new Set;let l=!1;const c=u=>em(u)?`cjk_${u}`:Xf(u)?"number":tl(u)?"space":tm(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 zi)||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(Ed,e instanceof zi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class u0 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 jk extends u0{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class Fk extends u0{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Je=y("undo");class zk{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):(a0(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(Je,!this.currentGroup,"current group already exists"),this.currentGroup=new Hk(this.editor),this.groupCounter=1):(d(Je,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(Je,this.currentGroup,"current group not exists"),d(Je,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Je.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 Je.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(no(this.editor,t.beforeRange))}catch(e){Je.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(no(this.editor,e)):Je.warn("no after range")}catch(e){Je.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(),ne.diff(o,r).length!==0&&this.addAction(new zi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Ul(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(Je,e>=0,"invalid block index"),d(Je,o,"no block data"),this.addAction(new Pk(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new $k(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new jk(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Fk(this.editor,t,e)))}}class Vk{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 Uk{constructor(){h(this,"converters",[]);this.addConverter(new Vk)}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 qk{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(!j(this.editor,e))return null;const r=rt(e);return o.parentElement===r?o:l1(o)}}const h0="style-color-",f0="style-bg-color-";class Wk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(h0)?i["data-style-color"]=s.substring(h0.length):s.startsWith(f0)?i["data-style-bg-color"]=s.substring(f0.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 Gk(n){n.editorBlocks.registerBlockClass(_i),n.editorBlocks.registerBlockClass(lg),n.editorBoxes.registerBoxClass(Gg),n.editorBoxes.registerBoxClass(Zg),n.editorInsertions.registerInsertionClass(Kg),n.editorBlockRenders.registerRender(new Wk)}function Zk(n,t){Gk(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 m0=y("range-commands");function g0(n,t){n.forEach(e=>{e.source=t,e.children&&g0(e.children,t)})}function p0(n,t,e){const o=G(t);d(m0,o===e.start.blockId,"invalid start range"),d(m0,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);g0(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)&&yr(n,t,e.start,e.end).forEach(l=>{Rt(l).forEach(a=>{const u=Z(n,a),f=Ut(n,{anchor:$(a,0,"home"),focus:$(a,u,"end")}),m=p0(n,a,f);i.push(...m)})}),i}function C0(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ut(t,{anchor:r.start,focus:r.end});p0(t,r.block,i).forEach(l=>{o.push(l)})}),o}function b0(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)&&yr(n,t,e.start,e.end).forEach(m=>{Rt(m).forEach(v=>{const w=Z(n,v),E=Ut(n,{anchor:$(v,0,"home"),focus:$(v,w,"end")});b0(n,v,E,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function v0(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=Ut(o,{anchor:l.start,focus:l.end});b0(o,l.block,c,t,e,r)}),r}const Yk=y("command-providers");class k0{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(Yk,e,`no command provider, id=${t}`),e}getCommands(t){return C0(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>v0(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 Qk(n,t){const e=H(t),o=V(e),r=K(t);s0(n,o,r)}const Kk=y("table-scroll");class y0{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 Jk{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)){Kk.warn(`event has already registered: ${e}`);return}i.push(new y0(this.editor,t,e,o,r))}else{const s=new y0(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 w0=y("update-block-text");function Xk(n,t){const e=n.getBoxById(t.id),o=z(e);d(w0,o,"no parent block"),d(w0,j(n,o),"not a text block");const r=n.getBlockText(o),i=$g(r,"id",t.id,t);b2(n,o,i)}function ty(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 ey(n){return n.readonly?!1:!Qe(n).find(o=>!n.isBlockWritable(o.block))}class ny{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 oy{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(_n(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Fn=y("editor");class ry 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 oy);h(this,"dataConverter",new Uk);h(this,"editorBlocks",new og(this));h(this,"editorBoxes",new Qg(this));h(this,"editorInsertions",new Xg(this));h(this,"editorEmbeds",new ig(this));h(this,"editorDecorators",new t2(this));h(this,"editorCommandProviders",new k0(this));h(this,"editorBlockRenders",new qk(this));h(this,"blockHooks",[]);h(this,"domEvents",new Jk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new Sk(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 ny(this),Zk(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 zk(this),this.doc=new _k(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=zm(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new rv(this,this.inputHandlers),this.selection=new gv(this),this.selectionHandler=new yv(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),It.isMobile&&M(this.rootElement,"mobile"),It.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:Nn(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){Q1(this,e,o)}isWritable(){return ey(this)}isBlockWritable(e){return ty(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 Vm(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,gr(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,s1(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 mr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return K(o)}return K(e)}getContainerById(e){return br(this,e)}getParentContainer(e){return H(e)}reloadBlock(e){Qk(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){const s={blockId:r.id,offset:0},l={anchor:s,focus:s};return Dr(this,e,o,r,i!=null?i:l)}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){G1(this,e,o)}mergeTextBlock(e,o){return g2(this,e,o)}breakTextBlock(e,o,r){return Pi(this,e,o,r).newBlock}getTextPosition(){return Tr(this)}getBlockString(e,o){const r=this.getBlockText(e);return Tt(r,o)}getBlockData(e){return ro(this,e)}getBoxData(e){return r2(this,e)}getBlockText(e){return ke(this,e)}setBlockText(e,o){b2(this,e,o)}deleteTextFromBlock(e,o,r){return U1(this,e,o,r)}insertTextToBlock(e,o,r){return s2(this,e,o,r)}insertBoxToBlock(e,o,r){return l2(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){y2(this,e,o,r,i)}insertDocAt(e,o,r,i){return X1(this,e,o,r,i)}deleteChildContainers(e){m2(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 v2(this,e,o,r)}updateBoxData(e){Xk(this,e)}getSelectedText(){const e=jl(this);return id(this,e)}clearSelectedContents(){Y1(this)}insertTextBlock(e,o,r,i){const s=jn(e!=null?e:"");return u2(this,s,o,r,i==null?void 0:i.newRange)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){a2(this);return}o?(this.compositingText="",Qa()||V1(this,e)):(this.compositingText=e,c2(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Vi(n,t,e){return new ry(n,t,e)}function iy(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=Fa.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const sy=["#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:sy}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&Zs.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&&Sl(r.range)&&zg(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(Sl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=ne.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=ne.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 Jt=y("local-doc");class Id extends ki{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(Jt,r,`no container data: ${e}`);const i=r[o];return d(Jt,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Jt,i.text,"no text for data");const s=ne.apply(i.text,r);return i.text=s,d(Jt,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(Jt,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(Jt,i,`no container data: ${e}`),d(Jt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(Jt,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(Jt,r,`no container data: ${e}`),d(Jt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(Jt,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(Jt,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){Jt.debug(`delete child containers: ${e}`),e.forEach(o=>{d(Jt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(Jt,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(Jt,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(Jt,!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 Vo(n){return Ct(H(n))}class ly{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function xd(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new ly(o)})}const B0=y("remote-cursor");class cy{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"?(B0.debug(`remote caret received: ${e}`),this.handleUpdateCaret(e)):B0.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 ay(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function Ui(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=ay(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 dy={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ee.default(n)},apply(n,t){const e=new ee.default(n),o=new ee.default(t);return e.compose(o).ops},compose(n,t){const e=new ee.default(n),o=new ee.default(t);return e.compose(o).ops},diff(n,t){const e=new ee.default(n),o=new ee.default(t);return e.diff(o).ops},transform(n,t,e){const o=new ee.default(n);return new ee.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 ee.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 qi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},co={},Sd=Af.default.EventEmitter;co.EventEmitter=Sd,co.mixin=uy;function uy(n){for(var t in Sd.prototype)n.prototype[t]=Sd.prototype[t]}var E0=["info","warn","error"];function I0(){var n={};E0.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var hy=I0;I0.prototype.setMethods=function(n){n=n||{};var t=this;E0.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var fy=hy,my=new fy,x0=my;function Uo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Uo):this.stack=new Error().stack}Uo.prototype=Object.create(Error.prototype),Uo.prototype.constructor=Uo,Uo.prototype.name="ShareDBError",Uo.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=Uo,Wi={},S0=gy;function gy(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 w=i(s.slice(m),C),E=0;E<w[0].length;E++)o(f,w[0][E]);for(var L=0;L<w[1].length;L++)o(c,w[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 T0={exports:{}},ao=T0.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||""}},Td=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Dd=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++)Dd(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=Td(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:Td(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:Td(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 Ld=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=Ld(n,t[r],o);return n};var py=ao._tc=function(n,t,e,o){if(Dd(t),Dd(e),t.i!=null)zn(n,{i:t.i,p:Ld(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=Ld(i.p,e),zn(n,i))}return n},Cy=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]=Cy(n[t]);return n},S0(ao,py,Gl,zn);var Zl=function(n){return Object.prototype.toString.call(n)=="[object Array]"},by=function(n){return!!n&&n.constructor===Object},Xe=function(n){return JSON.parse(JSON.stringify(n))},et={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Vn={};et.registerSubtype=function(n){Vn[n.name]=n},et.create=function(n){return n===void 0?null:Xe(n)},et.invertComponent=function(n){var t={p:n.p};return n.t&&Vn[n.t]&&(t.t=n.t,t.o=Vn[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},et.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(et.invertComponent(t[o]));return e},et.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Zl(n[t].p))throw new Error("Missing path")},et.checkList=function(n){if(!Zl(n))throw new Error("Referenced element not a list")},et.checkObj=function(n){if(!by(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Gi(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 Zi(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}et.apply=function(n,t){et.checkValidOp(t),t=Xe(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&Gi(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&&Vn[r.t])s[l]=Vn[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)et.checkList(s),s[l]=r.li;else if(r.li!==void 0)et.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)et.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(et.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)et.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)et.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},et.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},et.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=et.apply(n,r),e(r,n)}return n};var vy=et.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};et.append=function(n,t){if(t=Xe(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)&&(Gi(t),Gi(e)),vy(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Vn[t.t]){if(e.o=Vn[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(),Zi(t),n.push(t);Zi(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)&&(Zi(t),Zi(e)),n.push(t)},et.compose=function(n,t){et.checkValidOp(n),et.checkValidOp(t);for(var e=Xe(n),o=0;o<t.length;o++)et.append(e,t[o]);return e},et.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=[]),et.append(t,o)}return t},et.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},et.canOpAffectPath=function(n,t){return et.commonLengthForOps({p:t},n)!=null},et.transformComponent=function(n,t,e,o){t=Xe(t);var r=et.commonLengthForOps(e,t),i=et.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=Xe(e);c.p=c.p.slice(s),t.ld=et.apply(Xe(t.ld),[c])}else if(t.od!==void 0){var c=Xe(e);c.p=c.p.slice(s),t.od=et.apply(Xe(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)&&(Gi(t),c=Xe(e),Gi(c)),c.t&&Vn[c.t]){if(t.t&&t.t===c.t){var u=Vn[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(),Zi(t),et.append(n,t);else(!Zl(u)||u.length>0)&&(t.o=u,et.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=Xe(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,w=e.p[r],E=e.lm;if(w!==E)if(C===w)if(o==="left")t.p[r]=E,C===v&&(t.lm=E);else return n;else C>w&&t.p[r]--,C>E?t.p[r]++:C===E&&w>E&&(t.p[r]++,C===v&&t.lm++),(v>w||v===w&&v>C)&&t.lm--,v>E?t.lm++:v===E&&(E>w&&v>C||E<w&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===w&&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")et.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 et.append(n,t),n},S0(et,et.transformComponent,et.checkValidOp,et.append);var ky=T0.exports;et.registerSubtype(ky);var yy=et,wy={type:yy};(function(n){n.defaultType=wy.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)})(Wi);var tn={};(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))}})(tn);var D0=Array.isArray,L0=Object.keys,By=Object.prototype.hasOwnProperty,Ey=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=D0(t),r=D0(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=L0(t);if(s=m.length,s!==L0(e).length)return!1;for(i=s;i--!==0;)if(!By.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},M0=co,Iy=x0,ye=Wl,Yl=Wi,en=tn,xy=en.clone,Sy=Ey,ge=ye.CODES,Ty=st;function st(n,t,e){M0.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}M0.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 ye(ge.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 ye(ge.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 ye(ge.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;en.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===ge.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){en.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){en.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===ge.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);Dy(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=Ly([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;en.nextTick(function(){n._handleSubscribe()})}}};function Dy(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function Ly(n){return n=n.filter(en.truthy),n.length?function(t){en.callEach(n,t)}:null}st.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function My(n){delete n.op,delete n.create,delete n.del}function Ql(n,t){if(n.del)return My(t);if(t.del)return new ye(ge.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new ye(ge.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new ye(ge.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 ye(ge.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 ye(ge.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>=en.MAX_SAFE_INTEGER)return this.emit("error",new ye(ge.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 ye(ge.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;en.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&&!Sy(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 ye(ge.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 ye(ge.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:xy(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 Iy.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=en.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=en.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 R0=co,A0=qo.ACTIONS,Ry=tn,Ay=pe;function pe(n,t,e,o,r,i,s){R0.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}R0.mixin(pe),pe.prototype.hasPending=function(){return!this.ready},pe.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}},pe.prototype.destroy=function(n){this.connection.canSend&&this.action===A0.querySubscribe&&this.connection.send({a:A0.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Ry.nextTick(n)},pe.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},pe.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},pe.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},pe.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()},pe.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},pe.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)},pe.prototype._handleError=function(n){this.emit("error",n)},pe.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)},pe.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var O0=co,Oy=qo.ACTIONS,_y=tn,_0=bn;function bn(n,t){if(O0.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={}}O0.mixin(bn),bn.prototype.submit=function(n,t){this.value=n,this.send(t)},bn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},bn.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()})},bn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},bn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},bn.prototype._message=function(){return{a:Oy.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},bn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},bn.prototype._callbackOrEmit=function(n,t){if(t)return _y.nextTick(t,n);n&&this.emit("error",n)};var Ny=tn,N0=Md;function Md(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Md.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Md.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Ny.nextTick(n)};var Rd={exports:{}};(function(n,t){(function(e,o){o(t)})(qi,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(w,I)}}function w(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 A(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 O=typeof qi=="object"&&qi&&qi.Object===Object&&qi,P=typeof self=="object"&&self&&self.Object===Object&&self,U=O||P||Function("return this")(),tt=U.Symbol,ot=Object.prototype,ut=ot.hasOwnProperty,dt=ot.toString,yt=tt?tt.toStringTag:void 0;function oe(p){var k=ut.call(p,yt),B=p[yt];try{p[yt]=void 0;var I=!0}catch{}var D=dt.call(p);return I&&(k?p[yt]=B:delete p[yt]),D}var Jn=Object.prototype,Xt=Jn.toString;function Fe(p){return Xt.call(p)}var vo="[object Null]",ar="[object Undefined]",dr=tt?tt.toStringTag:void 0;function ko(p){return p==null?p===void 0?ar:vo:dr&&dr in Object(p)?oe(p):Fe(p)}var ma="[object AsyncFunction]",$P="[object Function]",HP="[object GeneratorFunction]",jP="[object Proxy]";function FP(p){if(!s(p))return!1;var k=ko(p);return k==$P||k==HP||k==ma||k==jP}var zP=9007199254740991;function B9(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=zP}function $s(p){return p!=null&&B9(p.length)&&!FP(p)}var hf={};function ft(){}function yo(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var ff=typeof Symbol=="function"&&Symbol.iterator,VP=function(p){return ff&&p[ff]&&p[ff]()};function UP(p,k){for(var B=-1,I=Array(p);++B<p;)I[B]=k(B);return I}function ga(p){return p!=null&&typeof p=="object"}var qP="[object Arguments]";function E9(p){return ga(p)&&ko(p)==qP}var I9=Object.prototype,WP=I9.hasOwnProperty,GP=I9.propertyIsEnumerable,ZP=E9(function(){return arguments}())?E9:function(p){return ga(p)&&WP.call(p,"callee")&&!GP.call(p,"callee")},dn=Array.isArray;function YP(){return!1}var x9=typeof e=="object"&&e&&!e.nodeType&&e,S9=x9&&!0&&n&&!n.nodeType&&n,QP=S9&&S9.exports===x9,T9=QP?U.Buffer:void 0,KP=T9?T9.isBuffer:void 0,JP=KP||YP,XP=9007199254740991,t$=/^(?:0|[1-9]\d*)$/;function e$(p,k){var B=typeof p;return k=k==null?XP:k,!!k&&(B=="number"||B!="symbol"&&t$.test(p))&&p>-1&&p%1==0&&p<k}var n$="[object Arguments]",o$="[object Array]",r$="[object Boolean]",i$="[object Date]",s$="[object Error]",l$="[object Function]",c$="[object Map]",a$="[object Number]",d$="[object Object]",u$="[object RegExp]",h$="[object Set]",f$="[object String]",m$="[object WeakMap]",g$="[object ArrayBuffer]",p$="[object DataView]",C$="[object Float32Array]",b$="[object Float64Array]",v$="[object Int8Array]",k$="[object Int16Array]",y$="[object Int32Array]",w$="[object Uint8Array]",B$="[object Uint8ClampedArray]",E$="[object Uint16Array]",I$="[object Uint32Array]",Bt={};Bt[C$]=Bt[b$]=Bt[v$]=Bt[k$]=Bt[y$]=Bt[w$]=Bt[B$]=Bt[E$]=Bt[I$]=!0,Bt[n$]=Bt[o$]=Bt[g$]=Bt[r$]=Bt[p$]=Bt[i$]=Bt[s$]=Bt[l$]=Bt[c$]=Bt[a$]=Bt[d$]=Bt[u$]=Bt[h$]=Bt[f$]=Bt[m$]=!1;function x$(p){return ga(p)&&B9(p.length)&&!!Bt[ko(p)]}function S$(p){return function(k){return p(k)}}var D9=typeof e=="object"&&e&&!e.nodeType&&e,Hs=D9&&!0&&n&&!n.nodeType&&n,T$=Hs&&Hs.exports===D9,mf=T$&&O.process,L9=function(){try{var p=Hs&&Hs.require&&Hs.require("util").types;return p||mf&&mf.binding&&mf.binding("util")}catch{}}(),M9=L9&&L9.isTypedArray,D$=M9?S$(M9):x$,L$=Object.prototype,M$=L$.hasOwnProperty;function R$(p,k){var B=dn(p),I=!B&&ZP(p),D=!B&&!I&&JP(p),T=!B&&!I&&!D&&D$(p),R=B||I||D||T,_=R?UP(p.length,String):[],q=_.length;for(var Q in p)(k||M$.call(p,Q))&&!(R&&(Q=="length"||D&&(Q=="offset"||Q=="parent")||T&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||e$(Q,q)))&&_.push(Q);return _}var A$=Object.prototype;function O$(p){var k=p&&p.constructor,B=typeof k=="function"&&k.prototype||A$;return p===B}function _$(p,k){return function(B){return p(k(B))}}var N$=_$(Object.keys,Object),P$=Object.prototype,$$=P$.hasOwnProperty;function H$(p){if(!O$(p))return N$(p);var k=[];for(var B in Object(p))$$.call(p,B)&&B!="constructor"&&k.push(B);return k}function gf(p){return $s(p)?R$(p):H$(p)}function j$(p){var k=-1,B=p.length;return function(){return++k<B?{value:p[k],key:k}:null}}function F$(p){var k=-1;return function(){var I=p.next();return I.done?null:(k++,{value:I.value,key:k})}}function z$(p){var k=gf(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 V$(p){if($s(p))return j$(p);var k=VP(p);return k?F$(k):z$(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 pa(p){return function(k,B,I){if(I=yo(I||ft),p<=0||!k)return I(null);var D=V$(k),T=!1,R=0,_=!1;function q(W,X){if(R-=1,W)T=!0,I(W);else{if(X===hf||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 ur(p,k,B,I){pa(k)(p,x(B),I)}function te(p,k){return function(B,I,D){return p(B,k,I,D)}}function U$(p,k,B){B=yo(B||ft);var I=0,D=0,T=p.length;T===0&&B(null);function R(_,q){_?B(_):(++D===T||q===hf)&&B(null)}for(;I<T;I++)k(p[I],I,Dn(R))}var q$=te(ur,1/0),wo=function(p,k,B){var I=$s(p)?U$:q$;I(p,x(k),B)};function ai(p){return function(k,B,I){return p(wo,k,x(B),I)}}function R9(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,Et){D[W]=Et,Q(X)})},function(_){I(_,D)})}var Ca=ai(R9),A9=A(Ca);function di(p){return function(k,B,I,D){return p(pa(B),k,x(I),D)}}var ui=di(R9),pf=te(ui,1),O9=A(pf);function ba(p,k){for(var B=-1,I=p==null?0:p.length;++B<I&&k(p[B],B,p)!==!1;);return p}function W$(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 G$=W$();function js(p,k){return p&&G$(p,k,gf)}function Z$(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 Y$(p){return p!==p}function Q$(p,k,B){for(var I=B-1,D=p.length;++I<D;)if(p[I]===k)return I;return-1}function va(p,k,B){return k===k?Q$(p,k,B):Z$(p,Y$,B)}var Cf=function(p,k,B){typeof k=="function"&&(B=k,k=null),B=yo(B||ft);var I=gf(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(xt,St){if(!dn(xt)){Et(St,[xt]),W.push(St);return}var Yt=xt.slice(0,xt.length-1),Xn=Yt.length;if(Xn===0){Et(St,xt),W.push(St);return}X[St]=Xn,ba(Yt,function(gi){if(!p[gi])throw new Error("async.auto task `"+St+"` has a non-existent dependency `"+gi+"` in "+Yt.join(", "));Ln(gi,function(){Xn--,Xn===0&&Et(St,xt)})})}),zH(),re();function Et(xt,St){Q.push(function(){Mn(xt,St)})}function re(){if(Q.length===0&&R===0)return B(null,T);for(;Q.length&&R<k;){var xt=Q.shift();xt()}}function Ln(xt,St){var Yt=q[xt];Yt||(Yt=q[xt]=[]),Yt.push(St)}function ze(xt){var St=q[xt]||[];ba(St,function(Yt){Yt()}),re()}function Mn(xt,St){if(!_){var Yt=Dn(function(gi,Df){if(R--,arguments.length>2&&(Df=o(arguments,1)),gi){var Lf={};js(T,function(UH,qH){Lf[qH]=UH}),Lf[xt]=Df,_=!0,q=Object.create(null),B(gi,Lf)}else T[xt]=Df,ze(xt)});R++;var Xn=x(St[St.length-1]);St.length>1?Xn(T,Yt):Xn(Yt)}}function zH(){for(var xt,St=0;W.length;)xt=W.pop(),St++,ba(VH(xt),function(Yt){--X[Yt]===0&&W.push(Yt)});if(St!==D)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function VH(xt){var St=[];return js(p,function(Yt,Xn){dn(Yt)&&va(Yt,xt,0)>=0&&St.push(Xn)}),St}};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 K$="[object Symbol]";function J$(p){return typeof p=="symbol"||ga(p)&&ko(p)==K$}var X$=1/0,_9=tt?tt.prototype:void 0,N9=_9?_9.toString:void 0;function bf(p){if(typeof p=="string")return p;if(dn(p))return hi(p,bf)+"";if(J$(p))return N9?N9.call(p):"";var k=p+"";return k=="0"&&1/p==-X$?"-0":k}function tH(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 eH(p,k,B){var I=p.length;return B=B===void 0?I:B,!k&&B>=I?p:tH(p,k,B)}function nH(p,k){for(var B=p.length;B--&&va(k,p[B],0)>-1;);return B}function oH(p,k){for(var B=-1,I=p.length;++B<I&&va(k,p[B],0)>-1;);return B}function rH(p){return p.split("")}var iH="\\ud800-\\udfff",sH="\\u0300-\\u036f",lH="\\ufe20-\\ufe2f",cH="\\u20d0-\\u20ff",aH=sH+lH+cH,dH="\\ufe0e\\ufe0f",uH="\\u200d",hH=RegExp("["+uH+iH+aH+dH+"]");function fH(p){return hH.test(p)}var P9="\\ud800-\\udfff",mH="\\u0300-\\u036f",gH="\\ufe20-\\ufe2f",pH="\\u20d0-\\u20ff",CH=mH+gH+pH,bH="\\ufe0e\\ufe0f",vH="["+P9+"]",vf="["+CH+"]",kf="\\ud83c[\\udffb-\\udfff]",kH="(?:"+vf+"|"+kf+")",$9="[^"+P9+"]",H9="(?:\\ud83c[\\udde6-\\uddff]){2}",j9="[\\ud800-\\udbff][\\udc00-\\udfff]",yH="\\u200d",F9=kH+"?",z9="["+bH+"]?",wH="(?:"+yH+"(?:"+[$9,H9,j9].join("|")+")"+z9+F9+")*",BH=z9+F9+wH,EH="(?:"+[$9+vf+"?",vf,H9,j9,vH].join("|")+")",IH=RegExp(kf+"(?="+kf+")|"+EH+BH,"g");function xH(p){return p.match(IH)||[]}function V9(p){return fH(p)?xH(p):rH(p)}function SH(p){return p==null?"":bf(p)}var TH=/^\s+|\s+$/g;function DH(p,k,B){if(p=SH(p),p&&(B||k===void 0))return p.replace(TH,"");if(!p||!(k=bf(k)))return p;var I=V9(p),D=V9(k),T=oH(I,D),R=nH(I,D)+1;return eH(I,T,R).join("")}var LH=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,MH=/,/,RH=/(=.+)?(\s*)$/,AH=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function OH(p){return p=p.toString().replace(AH,""),p=p.match(LH)[2].replace(" ",""),p=p?p.split(MH):[],p=p.map(function(k){return DH(k.replace(RH,""))}),p}function U9(p,k){var B={};js(p,function(I,D){var T,R=L(I),_=!R&&I.length===1||R&&I.length===0;if(dn(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=OH(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(Et){return Q[Et]});X.push(W),x(I).apply(null,X)}}),Cf(B,k)}function un(){this.head=this.tail=null,this.length=0}function q9(p,k){p.length=1,p.head=p.tail=k}un.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},un.prototype.empty=function(){for(;this.head;)this.shift();return this},un.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},un.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},un.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):q9(this,p)},un.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):q9(this,p)},un.prototype.shift=function(){return this.head&&this.removeLink(this.head)},un.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},un.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},un.prototype.remove=function(p){for(var k=this.head;k;){var B=k.next;p(k)&&this.removeLink(k),k=B}return this};function W9(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,Et,re){if(re!=null&&typeof re!="function")throw new Error("task callback must be a function");if(W.started=!0,dn(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:re||ft};Et?W._tasks.unshift(Mn):W._tasks.push(Mn)}R||(R=!0,m(function(){R=!1,W.process()}))}function q(X){return function(Et){D-=1;for(var re=0,Ln=X.length;re<Ln;re++){var ze=X[re],Mn=va(T,ze,0);Mn===0?T.shift():Mn>0&&T.splice(Mn,1),ze.callback.apply(ze,arguments),Et!=null&&W.error(Et,ze.data)}D<=W.concurrency-W.buffer&&W.unsaturated(),W.idle()&&W.drain(),W.process()}}var Q=!1,W={_tasks:new un,concurrency:k,payload:B,saturated:ft,unsaturated:ft,buffer:k/4,empty:ft,drain:ft,error:ft,started:!1,paused:!1,push:function(X,Et){_(X,!1,Et)},kill:function(){W.drain=ft,W._tasks.empty()},unshift:function(X,Et){_(X,!0,Et)},remove:function(X){W._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!W.paused&&D<W.concurrency&&W._tasks.length;){var X=[],Et=[],re=W._tasks.length;W.payload&&(re=Math.min(re,W.payload));for(var Ln=0;Ln<re;Ln++){var ze=W._tasks.shift();X.push(ze),T.push(ze),Et.push(ze.data)}D+=1,W._tasks.length===0&&W.empty(),D===W.concurrency&&W.saturated();var Mn=Dn(q(X));I(Et,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 G9(p,k){return W9(p,1,k)}var fi=te(ur,1);function Bo(p,k,B,I){I=yo(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 yf(){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,Bo(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 Z9=function(){return yf.apply(null,o(arguments).reverse())},_H=Array.prototype.concat,ka=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]&&(_=_H.apply(_,R[q]));return I(T,_)})},Y9=te(ka,1/0),Q9=te(ka,1),K9=function(){var p=o(arguments),k=[null].concat(p);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Fs(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,Et){X?W(X):p(Et)&&!_?(R=!0,_=k(!0,q),W(null,hf)):W()})},function(q){q?T(q):T(null,R?_:k(!1))})}}function J9(p,k){return k}var ya=ai(mi(Fs,J9)),zs=di(mi(Fs,J9)),wa=te(zs,1);function X9(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]&&ba(D,function(T){console[p](T)}))}),x(k).apply(null,B)}}var t7=X9("dir");function e7(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 wf(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 n7(p,k,B){wf(p,function(){return!k.apply(this,arguments)},B)}function o7(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 r7(p){return function(k,B,I){return p(k,I)}}function Ba(p,k,B){wo(p,r7(x(k)),B)}function Vs(p,k,B,I){pa(k)(p,r7(x(B)),I)}var Us=te(Vs,1);function Bf(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 Ea(p){return!p}var Ia=ai(mi(Ea,Ea)),qs=di(mi(Ea,Ea)),xa=te(qs,1);function i7(p){return function(k){return k==null?void 0:k[p]}}function NH(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 PH(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}),i7("value")))})}function Ef(p,k,B,I){var D=$s(k)?NH:PH;D(p,k,x(B),I||ft)}var Sa=ai(Ef),Ws=di(Ef),Ta=te(Ws,1);function s7(p,k){var B=Dn(k||ft),I=x(Bf(p));function D(T){if(T)return B(T);I(D)}D()}var Da=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,_)})},l7=te(Da,1/0),c7=te(Da,1),a7=X9("log");function La(p,k,B,I){I=yo(I||ft);var D={},T=x(B);ur(p,k,function(R,_,q){T(R,_,function(Q,W){if(Q)return q(Q);D[_]=W,q()})},function(R){I(R,D)})}var d7=te(La,1/0),u7=te(La,1);function h7(p,k){return k in p}function f7(p,k){var B=Object.create(null),I=Object.create(null);k=k||Fs;var D=x(p),T=i(function(_,q){var Q=k.apply(null,_);h7(B,Q)?m(function(){q.apply(null,B[Q])}):h7(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 Et=0,re=X.length;Et<re;Et++)X[Et].apply(null,W)})))});return T.memo=B,T.unmemoized=p,T}var Ma;c?Ma=process.nextTick:l?Ma=setImmediate:Ma=a;var m7=u(Ma);function If(p,k,B){B=B||ft;var I=$s(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 g7(p,k){If(wo,p,k)}function p7(p,k,B){If(pa(k),p,B)}var xf=function(p,k){var B=x(p);return W9(function(I,D){B(I[0],D)},k,1)},C7=function(p,k){var B=xf(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,dn(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 b7(p,k){if(k=yo(k||ft),!dn(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 Ra(p,k,B,I){var D=o(p).reverse();Bo(D,k,B,I)}function Aa(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 v7(p){var k;return dn(p)?k=hi(p,Aa):(k={},js(p,function(B,I){k[I]=Aa.call(this,B)})),k}function k7(p,k,B,I){Ef(p,k,function(D,T){B(D,function(R,_){T(R,!_)})},I)}var y7=ai(k7),Sf=di(k7),w7=te(Sf,1);function B7(p){return function(){return p}}function Oa(p,k,B){var I=5,D=0,T={times:I,intervalFunc:B7(D)};function R(W,X){if(typeof X=="object")W.times=+X.times||I,W.intervalFunc=typeof X.interval=="function"?X.interval:B7(+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 E7=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?Oa(p,T,D):Oa(T,D)})};function I7(p,k){If(fi,p,k)}var _a=ai(mi(Boolean,Fs)),Gs=di(mi(Boolean,Fs)),Na=te(Gs,1);function x7(p,k,B){var I=x(k);Ca(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),i7("value")))});function D(T,R){var _=T.criteria,q=R.criteria;return _<q?-1:_>q?1:0}}function S7(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 $H=Math.ceil,HH=Math.max;function jH(p,k,B,I){for(var D=-1,T=HH($H((k-p)/(B||1)),0),R=Array(T);T--;)R[I?T:++D]=p,p+=B;return R}function Pa(p,k,B,I){var D=x(B);ui(jH(0,p,1),k,D,I)}var T7=te(Pa,1/0),D7=te(Pa,1);function L7(p,k,B,I){arguments.length<=3&&(I=B,B=k,k=dn(p)?[]:{}),I=yo(I||ft);var D=x(B);wo(p,function(T,R,_){D(k,T,R,_)},function(T){I(T,k)})}function M7(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 R7(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function Tf(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 A7(p,k,B){Tf(function(){return!p.apply(this,arguments)},k,B)}var O7=function(p,k){if(k=yo(k||ft),!dn(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([])},FH={apply:r,applyEach:A9,applyEachSeries:O9,asyncify:C,auto:Cf,autoInject:U9,cargo:G9,compose:Z9,concat:Y9,concatLimit:ka,concatSeries:Q9,constant:K9,detect:ya,detectLimit:zs,detectSeries:wa,dir:t7,doDuring:e7,doUntil:n7,doWhilst:wf,during:o7,each:Ba,eachLimit:Vs,eachOf:wo,eachOfLimit:ur,eachOfSeries:fi,eachSeries:Us,ensureAsync:Bf,every:Ia,everyLimit:qs,everySeries:xa,filter:Sa,filterLimit:Ws,filterSeries:Ta,forever:s7,groupBy:l7,groupByLimit:Da,groupBySeries:c7,log:a7,map:Ca,mapLimit:ui,mapSeries:pf,mapValues:d7,mapValuesLimit:La,mapValuesSeries:u7,memoize:f7,nextTick:m7,parallel:g7,parallelLimit:p7,priorityQueue:C7,queue:xf,race:b7,reduce:Bo,reduceRight:Ra,reflect:Aa,reflectAll:v7,reject:y7,rejectLimit:Sf,rejectSeries:w7,retry:Oa,retryable:E7,seq:yf,series:I7,setImmediate:m,some:_a,someLimit:Gs,someSeries:Na,sortBy:x7,timeout:S7,times:T7,timesLimit:Pa,timesSeries:D7,transform:L7,tryEach:M7,unmemoize:R7,until:A7,waterfall:O7,whilst:Tf,all:Ia,allLimit:qs,allSeries:xa,any:_a,anyLimit:Gs,anySeries:Na,find:ya,findLimit:zs,findSeries:wa,forEach:Ba,forEachSeries:Us,forEachLimit:Vs,forEachOf:wo,forEachOfSeries:fi,forEachOfLimit:ur,inject:Bo,foldl:Bo,foldr:Ra,select:Sa,selectLimit:Ws,selectSeries:Ta,wrapSync:C};e.default=FH,e.apply=r,e.applyEach=A9,e.applyEachSeries=O9,e.asyncify=C,e.auto=Cf,e.autoInject=U9,e.cargo=G9,e.compose=Z9,e.concat=Y9,e.concatLimit=ka,e.concatSeries=Q9,e.constant=K9,e.detect=ya,e.detectLimit=zs,e.detectSeries=wa,e.dir=t7,e.doDuring=e7,e.doUntil=n7,e.doWhilst=wf,e.during=o7,e.each=Ba,e.eachLimit=Vs,e.eachOf=wo,e.eachOfLimit=ur,e.eachOfSeries=fi,e.eachSeries=Us,e.ensureAsync=Bf,e.every=Ia,e.everyLimit=qs,e.everySeries=xa,e.filter=Sa,e.filterLimit=Ws,e.filterSeries=Ta,e.forever=s7,e.groupBy=l7,e.groupByLimit=Da,e.groupBySeries=c7,e.log=a7,e.map=Ca,e.mapLimit=ui,e.mapSeries=pf,e.mapValues=d7,e.mapValuesLimit=La,e.mapValuesSeries=u7,e.memoize=f7,e.nextTick=m7,e.parallel=g7,e.parallelLimit=p7,e.priorityQueue=C7,e.queue=xf,e.race=b7,e.reduce=Bo,e.reduceRight=Ra,e.reflect=Aa,e.reflectAll=v7,e.reject=y7,e.rejectLimit=Sf,e.rejectSeries=w7,e.retry=Oa,e.retryable=E7,e.seq=yf,e.series=I7,e.setImmediate=m,e.some=_a,e.someLimit=Gs,e.someSeries=Na,e.sortBy=x7,e.timeout=S7,e.times=T7,e.timesLimit=Pa,e.timesSeries=D7,e.transform=L7,e.tryEach=M7,e.unmemoize=R7,e.until=A7,e.waterfall=O7,e.whilst=Tf,e.all=Ia,e.allLimit=qs,e.allSeries=xa,e.any=_a,e.anyLimit=Gs,e.anySeries=Na,e.find=ya,e.findLimit=zs,e.findSeries=wa,e.forEach=Ba,e.forEachSeries=Us,e.forEachLimit=Vs,e.forEachOf=wo,e.forEachOfSeries=fi,e.forEachOfLimit=ur,e.inject=Bo,e.foldl=Bo,e.foldr=Ra,e.select=Sa,e.selectLimit=Ws,e.selectSeries=Ta,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(Rd,Rd.exports);var P0={exports:{}},Ad=P0.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)?Ad(n,t):i};Ad.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=Ad(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 $0=co,Py=_0,$y=N0,Kl=tn,Od=Rd.exports,Hy=P0.exports,H0=qo.ACTIONS,j0=Pt;function Pt(n,t){if($0.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}$0.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||Hy();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);Od.parallel([function(i){Od.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Od.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?H0.presenceSubscribe:H0.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 Py(this,n)},Pt.prototype._createRemotePresence=function(n){return new $y(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=Kl.callEach(n,t);!e&&t&&this.emit("error",t)};var Yi=_0,F0=Wl,jy=tn,z0=F0.CODES,Fy=nn;function nn(n,t){Yi.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()}nn.prototype=Object.create(Yi.prototype),nn.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:z0.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,Yi.prototype.submit.call(this,n,t)},nn.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),Yi.prototype.destroy.call(this,n)},nn.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={})})}},nn.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)},nn.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)}},nn.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},nn.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},nn.prototype._message=function(){var n=Yi.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},nn.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!jy.supportsPresence(o))throw new F0(z0.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var V0={};(function(n){var t=Wi,e=Wl,o=tn,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,w=0;w<C.length;w++){var E=C[w];Object.prototype.toString.call(v)=="[object Array]"?C[w]=+E:v.constructor===Object&&(C[w]=E.toString()),v=v[E]}f<a.length-1&&(u=t.defaultType.apply(u,[m]))}}}}})(V0);var Qi=N0,zy=V0,Vy=Pe;function Pe(n,t){Qi.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(Qi.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),Qi.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()},Qi.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Qi.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++):zy.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 U0=j0,Uy=Fy,qy=Vy;function Ar(n,t,e){var o=Ar.channel(t,e);U0.call(this,n,o),this.collection=t,this.id=e}var Wy=Ar;Ar.prototype=Object.create(U0.prototype),Ar.channel=function(n,t){return n+"."+t},Ar.prototype._createLocalPresence=function(n){return new Uy(this,n)},Ar.prototype._createRemotePresence=function(n){return new qy(this,n)};var Gy=Zy;function Zy(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var Yy=Gy,q0=co,W0=Ki;function Ki(n,t,e,o,r){if(q0.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}q0.mixin(Ki),Ki.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ki.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ki.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new Yy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var G0=W0,Qy=tn,Ky=qo.ACTIONS,Jy=_d;function _d(n,t,e,o,r,i){if(G0.call(this,n,t,e,o,i),!Qy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}_d.prototype=Object.create(G0.prototype),_d.prototype._message=function(){return{a:Ky.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Z0=W0,Xy=tn,tw=qo.ACTIONS,ew=Nd;function Nd(n,t,e,o,r,i){if(Z0.call(this,n,t,e,o,i),!Xy.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Nd.prototype=Object.create(Z0.prototype),Nd.prototype._message=function(){return{a:tw.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var nw=Ty,ow=Ay,rw=j0,Y0=Wy,iw=Jy,sw=ew,Q0=co,Or=Wl,pt=qo.ACTIONS,K0=Wi,on=tn,Ji=x0,Xi=Or.CODES;function J0(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var lw=J;function J(n){Q0.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=J0(n),this.bindToSocket(n)}Q0.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=J0(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{Ji.warn("Failed to parse message",o);return}e.debug&&Ji.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){on.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=X0(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:Ji.warn("Ignoring unrecognized message",n)}};function X0(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](X0(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 Ji.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 Or(Xi.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&&Ji.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},J.prototype.ping=function(){if(!this.canSend)throw new Or(Xi.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 nw(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},J.prototype._destroyDoc=function(n){!n._wantsDestroy||(on.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 ow(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(cw)};function cw(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}on.nextTick(n)},J.prototype._nothingPendingRetry=function(n){var t=this;return function(){on.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 iw(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 sw(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 Or(Xi.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(K0.map[n.type]!==K0.defaultType)return this.emit("error",new Or(Xi.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Or(Xi.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=on.digOrCreate(this._presences,n,function(){return new rw(t,n)});return e._wantsDestroy=!1,e},J.prototype.getDocPresence=function(n,t){var e=Y0.channel(n,t),o=this,r=on.digOrCreate(this._presences,e,function(){return new Y0(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){on.digOrCreate(this._presences,n.channel,function(){return n})},J.prototype._handlePresenceSubscribe=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},J.prototype._handlePresenceUnsubscribe=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},J.prototype._handlePresence=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},J.prototype._handlePresenceRequest=function(n,t){var e=on.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var t5=lw,aw=Wi;const Xl={err:1001,msg:"user auth error",name:"AuthError"},dw={err:1002,msg:"you don't have required permission",name:"PermissionError"},Pd={err:1003,msg:"Too many user connected",name:"MaxUserError"},ts={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},uw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},hw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},es="x-live-editor-token",tc="x-live-editor-base-url",ae=y("auth-connection");function fw(n){try{n()}catch(t){ae.error(t)}}class mw{constructor(t,e){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new Mf.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 Lo(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:{[es]: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]:Lo(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new a8.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(t5.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);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l);return}throw l}}},t5.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(ts.msg);t.code=ts.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t){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===Pd.err)ae.warn(Pd.msg),this.emitMaxUsersError();else if(o===ts.err){ae.warn(ts.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(),fw(()=>{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()}}y("utils/file");function gw(){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}gw();async function pw(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new d8.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 Lo(i)}const vn=y("sharedb-doc/client");class Cw{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(vn,!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),vn.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;aw.register(Ys.type),this.connection=new mw(r,o),this.reAuthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(vn,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,{[es]: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=>{vn.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await pw(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 vn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(vn,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[es]:this.connection.token},e,o);return d(vn,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(vn,o,"no token"),c.headers={...c.headers,[es]:o,[tc]:this.connection.getBase64BaseURL()};try{return await l8.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(vn,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=c8.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(vn,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/${Lo(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 bw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const $d=y("block-ids");class vw{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($d,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($d,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 kw{constructor(){h(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new vw,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($d,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class e5{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=y("op-parser");function _r(n){return n==="blocks"?"root":n}class yw{constructor(t,e){h(this,"updatingBlockDataDeltaMap",new Map);h(this,"blockIds",new kw);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 e5,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 e5,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 n5{}class Hd{constructor(t){h(this,"key");this.key=t}}function ww(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 jd(n,t,e,o){if(e==="upsert"&&ww(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 Hd(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 n5),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 Hd(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof n5?o.onDeleteBlock(n,i):l instanceof Hd?o.onDeleteBlockData(n,i,l.key):d(Nt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function Bw(n,t,e,o){Nt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Ew(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 Fd(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Fd(l,t,e,o)});return}const i=r;if(d(Nt,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){Bw(n);return}if(i==="comments"){Ew(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{jd(s,l,t,e)}):n.slice(1).forEach(l=>{jd(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)}`),jd(s,n.slice(1),t,e)}function o5(n,t,e){const o=new yw(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=>{Fd(c,i,o,t)}):Fd(s,i,o,t)}o.executeUpdateBlockDataActions()}const Iw=y("sharedb-comments");function xw(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(Iw,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 Sw(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 r5(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const Dt=y("sharedb-doc/doc-container"),i5="ot-json1";Ys.type.registerSubtype(dy.type),Ys.type.name=i5,Ys.type.invert=null;class ec extends ki{constructor(e,o){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new cy);h(this,"batching",0);h(this,"status","clean");h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.callbacks.forEach(e=>{var o;return(o=e.onRequestReload)==null?void 0:o.call(e,"doc created")})});h(this,"handleDel",()=>{});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(!Zs.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)=>{this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(Dt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i)):o()}),d(Dt,this.doc.data,"no data after submit op, may be the submitted op is invalid")}));h(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,i5,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)=>{o5(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(Dt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new Cw(e.auth,e.serverUrl,e.reAuthFunc),r=await o.getDoc(),i=new ec(o,r);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||bw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw Dt.error(o),Dt.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)}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 Ui(this.data())}getContainerBlocks(e){const o=this.data();d(Dt,o,"no doc data");const r=o[lo(e)];return d(Dt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=lo(e),i=this.getContainerBlocks(r);d(Dt,i,`no container data: ${r}`);const s=i[o];return d(Dt,s,`no block data: ${o}`),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(Dt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=ne.apply(s,r);return d(Dt,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=>Sw(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return xw(o)}localCreateComment(e,o){const r=r5(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=r5(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!1),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){d(Dt,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(Dt,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(Dt,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(Dt,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(Dt,this.callbacks.length>0,"no callbacks"),d(Dt,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(Dt,this.callbacks.length>0,"no callbacks"),d(Dt,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(Dt,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(Dt,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(Dt,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 Ui(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Ui(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:Ui(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Ui(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){o5(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}y("remote-cursor");class s5{constructor(t){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",ie.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 l5=y("remote-cursor-decorator");class zd{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(l5,typeof s=="string","invalid path containerId"),d(l5,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(w=>({id:N(),type:"remote-cursor",name:w.user.displayName,time:w.time,rainbowIndex:w.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class c5 extends Wt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Ct(br(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 Tw(n,t){n.addCustom("child-block-tracker",()=>new c5(n)).addListener("change",t)}function Dw(n,t){n.addCustom("child-block-tracker",()=>new c5(n)).removeListener("change",t)}const dF="",Lw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Mw={colorPalette:{colorDesc:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};S.mergeLang({"zh-CN":Lw,"en-US":Mw});const uF="",Rw=y("button");function Aw(n){const t=n.getAttribute("data-button-id");return t||d(Rw,!1,"unknown button id"),t}function Ow(n){var e;if(!(n instanceof Node))return null;const t=n.parentElement;return t?n instanceof HTMLButtonElement&&n.classList.contains("editor-button")?n:(e=t.closest("button.editor-button"))!=null?e:null:null}function kn(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 Vd(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}function _w(n){return b("span",["editor-separator",n],null)}const uo=y("filterable-list");function Nw(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 a5(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Nw(e))}),t}function d5(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Pw(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=a5(d5(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function u5(n,t,e){const o=n.querySelector(".list");d(uo,o,"no list root");const r=a5(d5(t,e)),i=o.querySelector(".list-root");if(d(uo,i,"no exists menu"),xi(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(uo,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class h5{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=Pw(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,u5(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)),u5(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 f5 extends h5{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=za.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 hF="",fF="";function m5(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 mF="",Nr=y("ui-command-bar-base"),$w={itemElementTag:"div",tippyArrow:!1},df=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){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)}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id)}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),um(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.emit("show",this),this.options.disablePageScroll&&dm(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=Nn(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={...$w,...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)}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=df.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){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),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 ho=df;h(ho,"commandBarCreators",new Map),y("ui-command-bar");class nc extends ho{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=za.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]}),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 Hw(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const g5={"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"},...Hw()};function Ud(n){var t,e,o;return(o=(e=n.shortcut)!=null?e:(t=g5[n.id])==null?void 0:t.shortcut)!=null?o:""}function jw(n){var t,e;return(e=(t=g5[n.id])==null?void 0:t.markdown)!=null?e:""}const qd=`<?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">
@@ -741,4 +741,4 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
741
741
  </defs>
742
742
  </svg>`,$3={dwg:[],rvt:[],skp:[],img:["image/png","image/jpg","image/jpeg","image/bmp","image/ico","image/icon","image/gif"],txt:["text/plain"],zip:["application/zip","application/x-rar-compressed","application/x-7z-compressed","application/x-tar","application/x-bzip2","application/java-archive"],ppt:["application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation"],excel:["application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],pdf:["application/pdf"],word:["application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"]},Jh={dwg:x_,rvt:S_,skp:T_,img:D_,txt:L_,zip:P3,rar:P3,ppt:M_,excel:R_,pdf:A_,word:O_};function N_(n,t){const e=Object.keys($3);for(let r=0;r<e.length;r+=1){const i=e[r];if($3[i].includes(t))return Jh[i]}const o=mm(n.toLowerCase());return Jh[o]?Jh[o]:__}function P_(n,t){const e=b("div",["card-root","embed-selected-content"],n),o=b("div",["file-icon"],e);o.innerHTML=N_(t.fileName,t.fileType);const r=b("div",["file-details"],e);b("div",["file-name"],r,t.fileName),b("div",["file-size"],r,vm(t.fileSize));const i=b("div",["file-actions"],e),s=b("button",["download"],i);return s.innerHTML=Kh,{card:e,downloadButton:s}}const ez="";function H3(n,t){const o=n.getBlockData(t).embedData,r=n.options.componentsOptions.file;if(r!=null&&r.onDownloadFile){r.onDownloadFile(n,o);return}const i=n.doc.buildResourceUrl(o.src,{downloadFileName:o.fileName});ll(i,o.fileName)}y("webpage-embed");function $_(n,t,e){const{embedData:o}=e,r=o,{card:i,downloadButton:s}=P_(t,r);n.domEvents.addEventListener(s,"click",(l,c)=>{if(!c.target)return;const a=z(c.target);!a||H3(l,a)}),n.domEvents.addEventListener(i,"click",(l,c)=>{if(!c.target)return;const a=z(c.target);if(!a||Bi(c,"button"))return;const u=l.options.componentsOptions.file;if(u!=null&&u.onClick){u.onClick(l,a,c);return}const m=l.getBlockData(a).embedData,C=l.doc.buildResourceUrl(m.src,{downloadFileName:m.fileName});ll(C,m.fileName)})}class H_{constructor(){h(this,"group","file-card");h(this,"commands",[{id:"download",name:"Download",icon:Kh},{id:"sep",name:"",type:"separator"},{id:"to-link",name:"To link",icon:A3},{id:"to-card",name:"To card",icon:O3,states:["checked"]},{id:"sep",name:"",type:"separator"},{id:"add-comment",name:"Add Comment",icon:$r}])}executeCommand(t,e,o){if(o.id==="to-link"){const r=H(e),i=V(r),s=K(e),l=t.getBlockData(e),{embedData:c}=l,a=c,u={id:N(),box:!0,type:"file",created:Date.now(),src:a.src,fileName:a.fileName,fileSize:a.fileSize,fileType:a.fileType};t.undoManager.runInGroup(()=>{t.deleteBlock(e);const f=[Tg(u)];t.insertTextBlock(f,i,s)})}else o.id==="download"?H3(t,e):o.id==="add-comment"&&ah(t,e)}}function j_(n,t){const e=n.getBlockData(t),{embedData:o,id:r}=e,i=o;return{blockCommands:{"hovering-toolbar":new H_},abstract:i.fileName}}const F_={embedType:"office",createEmbedContent:$_,getBlockProperties:j_},nz="",z_={media:{upload:{failed:'<div class="line-1">{name} \u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <a href="" class="retry-upload">\u91CD\u8BD5</a></div>'},load:{failed:'<div class="line-1">{name} \u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <a href="" class="retry-upload">\u91CD\u8BD5</a></div>'},audio:{menuItem:"\u97F3\u9891",abstract:"\u97F3\u9891"},video:{menuItem:"\u89C6\u9891",abstract:"\u89C6\u9891"}}},V_={media:{upload:{failed:'<div class="line-1">{name} upload failed</div><div class="line-2">The network service is abnormal, you can <a href="" class="retry-upload">Try again</a></div>'},load:{failed:'<div class="line-1">{name} loading failed</div><div class="line-2">The network service is abnormal, you can <a href="" class="retry-upload">Try again</a></div>'},audio:{menuItem:"Audio",abstract:"Audio"},video:{menuItem:"Video",abstract:"Video"}}};S.mergeLang({"zh-CN":z_,"en-US":V_});var an=(n=>(n.AUDIO="audio",n.VIDEO="video",n))(an||{}),_s=(n=>(n.Empty="empty",n.Progress="progress",n.Error="error",n))(_s||{});const j3=10*1024*1024,U_=["wav","mp3","aac","ogg","webm","flac"],q_=["ogg","mp4","webm"],W_=()=>{};function F3(n){var u,f,m,C,v,w;const t=(u=n.getComponentOptions("media"))!=null?u:{},{allowedMedias:e,maxSize:o,callbacks:r}=t,i=(f=e==null?void 0:e.audio)!=null?f:U_,s=(m=e==null?void 0:e.video)!=null?m:q_,l=(C=o==null?void 0:o.audio)!=null?C:j3,c=(v=o==null?void 0:o.video)!=null?v:j3,a=(w=r==null?void 0:r.onError)!=null?w:W_;return{allowedMedias:{audio:i,video:s},maxSize:{audio:l,video:c},callbacks:{onError:a}}}const G_=y("file-utils");function Z_(n){d(G_,n instanceof File,`The file: ${n} isn't instance of File`);const{name:t}=n;if(!t)return"";const e=t.lastIndexOf(".");return e===-1?"":t.slice(e+1)}function z3(n,t){const e=i=>i.map(s=>`.${s}`).join(","),{allowedMedias:o}=F3(n),r=o[t];return r?e(r):"*"}function Y_(n,t,e){const{maxSize:o,callbacks:r,allowedMedias:i}=F3(t),{[e]:s}=o,{[e]:l}=i;if(s&&n.size>s){const a=new Error("media is too large");return a.code=`MaxMediaSize-${e}`,r!=null&&r.onError&&(r==null||r.onError(t,a)),a}const c=Z_(n);if(l&&!l.includes(c)){const a=new Error(`media file is not allowed: ${c}`);return a.code="NotAllowedFile",r!=null&&r.onError&&(r==null||r.onError(t,a)),a}return!0}function Q_(n){return n===_s.Empty||n===_s.Error}const ue=y("media");class K_{constructor(t){h(this,"mediaContainer",null);h(this,"media",null);h(this,"abstract",null);h(this,"handleMediaLoadError",(t,e)=>{if(!e.target||!(e.target instanceof Node)||!(e.target instanceof Element?e.target:e.target.parentElement))return;const r=z(e.target);if(!r||!r.contains(this.mediaContainer))return;const i=this.renderError();this.updateMediaContent(i)});h(this,"handleRetry",async t=>{if(t.readonly)return;d(ue,this.abstract,"no abstract");const{mediaType:e}=this.abstract,o=z3(t,e),r=await fr(o);this.handleUploadFile(r)});h(this,"handleUploadFile",async t=>{d(ue,this.abstract,"no abstract"),d(ue,this.mediaContainer,"The media element not exist");const{editor:e}=this.options,{mediaType:o}=this.abstract,r=z(this.mediaContainer);d(ue,r,"The block element not exist");const i=e.getBlockData(r);if(!!Y_(t,e,o))try{const{resourceId:s}=await e.doc.uploadResource(t,{onProgress:f=>{this.renderProgress(f,t)}}),{name:l,type:c,size:a}=t,u={...i,embedData:{...i.embedData,src:s,fileName:l,fileSize:a,fileType:c}};e.updateBlockData(r,u)}catch{this.renderRetry()}});h(this,"destroy",()=>{this.mediaContainer=null});this.options=t}bindMediaEvent(){const{editor:t}=this.options;this.media&&t.domEvents.addEventListener(this.media,"error",this.handleMediaLoadError)}unbindMediaEvent(){const{editor:t}=this.options;this.media&&t.domEvents.removeEventListener(this.media,"error",this.handleMediaLoadError)}updateMediaContent(t){d(ue,this.mediaContainer,"The media element not exist"),this.mediaContainer.innerHTML="",this.mediaContainer.append(t)}renderError(){d(ue,this.abstract,"no abstract");const{editor:t,createMediaElement:e}=this.options,{mediaIcon:o,mediaName:r}=this.abstract;d(ue,this.mediaContainer,"The media element not exist");const i=z(this.mediaContainer);d(ue,i,"The block element not exist");const s=t.getBlockData(i),l=s.embedData.src,c=b("div",["media-error","embed-selected-content","embed-hover-content"],null),a=b("span",["media-error-icon"],c);a.innerHTML=o;const u=b("div",[],c);u.innerHTML=S.t("media.load.failed",{name:r}),c.appendChild(u);const f=u.querySelector("a");return d(ue,f,"The element not exist"),t.domEvents.addEventListener(f,"click",(m,C)=>{if(C.preventDefault(),C.target instanceof HTMLElement&&C.target.tagName==="A"){const v=b("div",["media-element"],null),w=this.getResourceUrl(l),E=e(m,v,s,w);this.unbindMediaEvent(),this.media=E,this.bindMediaEvent(),this.updateMediaContent(v)}}),c}renderRetry(){d(ue,this.abstract,"no abstract");const{editor:t}=this.options,{mediaIcon:e,mediaName:o}=this.abstract,r=b("div",["media-error","embed-selected-content","embed-hover-content"],null),i=b("span",["media-error-icon"],r);i.innerHTML=e;const s=b("div",[],r);s.innerHTML=S.t("media.upload.failed",{name:o}),r.appendChild(s);const l=s.querySelector("a");d(ue,l,"The element not exist"),t.domEvents.addEventListener(l,"click",this.handleRetry),this.updateMediaContent(r)}renderProgress(t,e){d(ue,this.mediaContainer,"The media element not exist");const o=this.mediaContainer.querySelector(":scope .media-progress"),r=t===-1||t===100?100:t;if(o){const{updateProgressElement:i}=this.options;i(o,r)}else{const{createProgressElement:i}=this.options,s=b("div",["media-progress"],null);i(s,r,e),this.updateMediaContent(s)}}renderMediaElement(t){d(ue,this.mediaContainer,"The media element not exist");const e=this.mediaContainer.querySelector(":scope > .media-element"),{createMediaElement:o,updateMediaElement:r,editor:i}=this.options,s=this.getResourceUrl(t.embedData.src);if(e){const l=r(i,e,t,s);this.unbindMediaEvent(),this.media=l,this.bindMediaEvent()}else{const l=b("div",["media-element"],null),c=o(i,l,t,s);this.unbindMediaEvent(),this.media=c,this.bindMediaEvent(),this.updateMediaContent(l)}}renderEmpty(){d(ue,this.abstract,"no abstract"),d(ue,this.mediaContainer,"The media element not exist");const t=b("div",["media-empty","embed-selected-content","embed-hover-content"],this.mediaContainer);t.innerHTML=this.abstract.mediaIcon,this.updateMediaContent(t)}getResourceUrl(t){const{editor:e}=this.options;return e.doc.buildResourceUrl(t)}render(t,e){const{src:o}=t.embedData;(!this.mediaContainer||!e.contains(this.mediaContainer))&&(this.mediaContainer=b("div",["media"],e)),Q_(o)?o===_s.Empty&&this.renderEmpty():this.renderMediaElement(t)}setAbstract(t){this.abstract=t}}y("media-embed");class V3{constructor(){h(this,"handleInsertEmptyEmbed",async(t,e)=>{var u;const{containerId:o,blockIndex:r}=e;let i;(u=e.data)!=null&&u.file&&(i=e.data.file);const s=z3(t,this.embedType);if(i=i!=null?i:await fr(s,{}),!i)return null;const l={id:N(),type:"embed",embedType:this.embedType,embedData:{src:_s.Empty}},c=t.insertBlock(o,r,l);return await this.getMedia(t,l.id).handleUploadFile(i),c})}getMedia(t,e){const o=t.addCustom(`media-${e}`,()=>new K_({editor:t,createMediaElement:this.createMediaElement,updateMediaElement:this.updateMediaElement,createProgressElement:this.createProgressElement,updateProgressElement:this.updateProgressElement}));return o.setAbstract({...this.abstract}),o}getOptions(){const{menuItem:t,mediaIcon:e,mediaName:o,order:r,group:i}=this.abstract;return{name:o,insertEmbedCommandItems:[{id:`insert-${this.embedType}`,name:t,icon:e,order:r,group:i}],handleInsertEmptyEmbed:this.handleInsertEmptyEmbed}}createEmbedContent(t,e,o){const{id:r}=o;this.getMedia(t,r).render(o,e)}handleUpdateBlock(t,e,o){const{id:r}=o,i=this.getMedia(t,r),s=rt(e);return i.render(o,s),!0}handleDeleteBlock(t,e){const o=e.id;this.getMedia(t,o).destroy()}}function U3(n,t){const e=b("div",["uploading-progress-mask"],n),o=b("div",["uploading-progress-bar"],e),r=b("div",["uploading-progress-bar-value"],o);r.style.width=`${t}%`}function q3(n,t){const e=n.querySelector(".uploading-progress-bar-value");e&&(e.style.width=`${t}%`)}const J_=y("media-audio");class X_ extends V3{constructor(){super(...arguments);h(this,"embedType",an.AUDIO);h(this,"abstract",{mediaIcon:F5,mediaName:S.t(`media.${an.AUDIO}.menuItem`),menuItem:S.t(`media.${an.AUDIO}.menuItem`),order:800,mediaType:an.AUDIO,group:"common"});h(this,"updateProgressElement",q3)}getBlockProperties(){return{abstract:`[${S.t(`media.${an.AUDIO}.abstract`)}]`}}createMediaElement(e,o,r,i){const s=b("div",["audio-container","embed-hover-content","embed-selected-content"],o),l=b("audio",[],s);return l.innerHTML="Your browser does not support the <code>audio</code> element.",l.controls=!0,l.src=i,l}updateMediaElement(e,o,r,i){const s=o.querySelector(":scope .audio-container > audio");return d(J_,s,"The media element not exist"),s.src!==i&&(s.src=i),s}createProgressElement(e,o){const r=b("audio",[],e);r.innerHTML="Your browser does not support the <code>audio</code> element.",r.controls=!0,r.src="about:blank",U3(e,o)}}const Xh=new X_;y("video-resizer");function W3(n){return n&&Te(n)&&De(n)==="video"}const tN=50;class eN{constructor(t){h(this,"currentResizableElement",null);h(this,"resizing",!1);h(this,"handleHoveringBlockChange",(t,e)=>{if(!this.resizing&&(e&&W3(e)&&this.disableBlockResize(e),t&&W3(t))){const o=this.getVideoElement(t);if(!o)return;this.enableBlockResize(t,o)}});h(this,"handleResizing",(t,e)=>{if(this.resizing=!0,!this.currentResizableElement)return;const o=t.getBlock();if(!o)return;const r=o.getBoundingClientRect().width,i=Math.min(Math.max(e.width,tN),r);this.currentResizableElement.style.width=`${i}px`});h(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!this.currentResizableElement||!e)return;const o=this.editor.getBlockData(e),{width:r}=this.currentResizableElement.getBoundingClientRect();this.editor.updateBlockData(e,{...o,width:r})});this.editor=t,_t.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentResizableElement=null,_t.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}getVideoElement(t){return rt(t).querySelector(":scope .video-container > video")}disableBlockResize(t){const e=this.editor.findCustom(`${G(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t,e){const o=this.editor.addCustom(`${G(t)}-resizer`,()=>new $c(this.editor,{resize:["top-left","top-right","bottom-left","bottom-right"]}));o.enableResize(t,e),o.removeListener("resizing",this.handleResizing),o.removeListener("resized",this.handleResized),o.addListener("resizing",this.handleResizing),o.addListener("resized",this.handleResized),this.currentResizableElement=e}}const nN=y("video");class oN extends V3{constructor(){super(...arguments);h(this,"embedType",an.VIDEO);h(this,"abstract",{mediaName:S.t(`media.${an.VIDEO}.menuItem`),mediaIcon:z5,menuItem:S.t(`media.${an.VIDEO}.menuItem`),order:700,mediaType:an.VIDEO,group:"common"});h(this,"updateProgressElement",q3);h(this,"createProgressElement",(e,o,r)=>{const i=b("video",["progress-video"],e);i.innerHTML="Your browser does not support the <code>audio</code> element.",i.controls=!0,U3(e,o),nl(r).then(s=>{const l=e.querySelector(".progress-video");l&&d1(e)&&(l.src=s)})})}getBlockProperties(){return{abstract:`[${S.t(`media.${an.VIDEO}.abstract`)}]`}}createMediaElement(e,o,r,i){const s=b("div",["video-container","embed-selected-content","drag-preview-element"],o),l=b("video",[],s);return l.innerHTML="Your browser does not support the <code>video</code> element.",l.controls=!0,l.src=i,e.addCustom("video-resizer",()=>new eN(e)),r.width&&(l.style.width=`${r.width}px`),l}updateMediaElement(e,o,r,i){const s=o.querySelector(":scope .video-container > video");return d(nN,s,"The media element not exist"),s.src!==i&&(s.src=i),s}}const tf=new oN,oz="",rN={version:{latest:"\u5F53\u524D\u7248\u672C",insert:"{name} \u6DFB\u52A0",delete:"{name} \u5220\u9664",goBack:"\u8FD4\u56DE",revertVersion:"\u8FD8\u539F\u5185\u5BB9",play:"\u64AD\u653E\u5386\u53F2\u64CD\u4F5C",versionList:"\u5386\u53F2\u8BB0\u5F55 {count}",unknown:"\u672A\u77E5\u7248\u672C",restoreFrom:"\u56DE\u6EDA\u81EA\u7248\u672C {from}",restoreInfo:"\u56DE\u6EDA\u7684\u7248\u672C\u6682\u4E0D\u652F\u6301\u4E0E\u4E0A\u4E00\u7248\u672C\u5BF9\u6BD4"}},iN={version:{latest:"Latest",insert:"Added by {name}",delete:"Deleted by {name}",goBack:"Back",revertVersion:"Revert",play:"Play",versionList:"Versions ({count})",unknown:"Unknown version",restoreFrom:"Reverted from {from}",restoreInfo:"The rolled back version does not currently support comparison with the previous version."}};S.mergeLang({"zh-CN":rN,"en-US":iN});var G3=(n=>(n.NEW="history-new",n.NEW_CHILD="history-new-child",n.DELETED="history-deleted",n.UPDATED="history-updated",n.HISTORY="history",n))(G3||{});const ri="--op-color",ii="--op-selected-color",rz="";class sN{constructor(t){h(this,"root");this.content=t;const e=b("div",["dialog-root"],null);e.append(t),this.root=e}show(t=document.body){t.append(this.root)}hide(){this.root.remove()}destroy(){}}const{t:si}=S,Z3=y("version-list");class lN{constructor(t){h(this,"activeVersionElement");h(this,"versionsList");h(this,"versionsListHeader");h(this,"handleClickVersionItem",t=>{const o=t.target.closest(".dialog-version-list-item");if(this.isVersionElement(o)){this.toggleActiveVersionElement(o);const r=this.getVersionFromElement(o),{onSelectVersion:i}=this.options;i(r)}});this.options=t;const{versions:e,defaultSelectedIndex:o=0}=t,r=b("div",["version-dialog-list-header"],null,"count");r.innerText=si("version.versionList",{count:`${e.length}`});const i=b("div",["version-dialog-list"],null),s=this.convertVersionsToFragment(e);i.append(s);const l=i.children[o];M(l,"active"),this.activeVersionElement=l,this.versionsList=i,this.versionsListHeader=r,i.onclick=this.handleClickVersionItem}get isSelectedFirstVersion(){return!!this.activeVersionElement&&this.versionsList.firstChild===this.activeVersionElement}get isSelectedLastVersion(){return!!this.activeVersionElement&&this.versionsList.lastChild===this.activeVersionElement}get beforeVersion(){return d(Z3,this.activeVersionElement,"No active version element"),this.activeVersionElement.nextElementSibling?this.activeVersionElement.nextElementSibling.versionData:null}get beforeMajorVersion(){d(Z3,this.activeVersionElement,"No active version element");let t=this.activeVersionElement.nextElementSibling;for(;t;){if(t.versionData.type)return t.versionData;t=t.nextElementSibling}return null}convertVersionsToFragment(t){const e=document.createDocumentFragment(),o=i=>{var l;let s;if(i.version!==-1){const c=new Date((l=i.created)!=null?l:i.version);s=`${c.toLocaleDateString()} ${c.toLocaleTimeString()}`}else s=si("version.latest");return s},r=(i,s,l,c=!1)=>{var C;const a=b("div",["dialog-version-list-item"],e);a.versionData=i,s&&M(a,"child");const u=b("div",["dialog-version-list-item-title"],a);if(b("div",["dialog-version-list-item-date"],u,o(i)),c&&b("div",["dialog-version-list-item-now-ver"],u,si("version.latest")),typeof i.source=="object"&&((C=i.source)==null?void 0:C.restore)){const v=i.source.restore,w=l.find(O=>O.version==v),E=w?o(w):si("version.unknown"),L=si("version.restoreFrom",{from:E}),x=si("version.restoreInfo"),A=b("div",["dialog-version-item-from-container"],a);b("div",["dialog-version-item-from-main"],A,L),b("div",["dialog-version-item-from-info"],A,x)}const f=b("ul",["dialog-version-list-item-authors"],a),m=v=>{const w=b("li",["dialog-version-list-item-author"],f),E=b("span",["dialog-version-list-item-mark-author"],w);E.style.background=this.options.getMarkColor(v),b("span",["dialog-version-list-item-author-name"],w,v.displayName)};if(this.options.useCreatedBy)if(i.createdBy){const v=i.createdBy;m(v)}else i.authors&&i.authors.length>0&&i.authors.forEach(v=>{m(v)});else if(i.authors&&i.authors.length>0)i.authors.forEach(v=>{m(v)});else if(i.createdBy){const v=i.createdBy;m(v)}};return t.forEach((i,s)=>{r(i,!1,t,s===0),i.minorVersions&&i.minorVersions.length>0&&i.minorVersions.forEach(l=>{r(l,!0,t,!1)})}),e}isVersionElement(t){return t?lt(t,"dialog-version-list-item"):!1}getVersionFromElement(t){return t.versionData}get activeVersion(){return this.getVersionFromElement(this.activeVersionElement)}toggleActiveVersionElement(t){this.activeVersionElement!==t&&(F(this.activeVersionElement,"active"),M(t,"active"),this.activeVersionElement=t)}selectVersionByVersionNum(t){const e=Array.from(this.versionsList.children).find(o=>o.versionData.version===t);return this.isVersionElement(e)?(this.toggleActiveVersionElement(e),this.getVersionFromElement(e)):null}render(t){t.innerHTML="",t.append(this.versionsListHeader,this.versionsList)}destroy(){this.versionsList.onclick=null}}class cN{constructor(t,e){this.doc=t,this.user=e}onDeleteBlock(t,e){this.doc.onDeleteBlock(t,e,this.user)}onInsertBlock(t,e,o){this.doc.onInsertBlock(t,e,o,this.user)}onUpdateBlockText(t,e,o){this.doc.onUpdateBlockText(t,e,o,this.user)}onUpdateBlockData(t,e,o){this.doc.onUpdateBlockData(t,e,o,this.user)}onCreateContainer(t,e){this.doc.onCreateContainer(t,e,this.user)}onCreateComment(){}onDeleteComment(){}onDeleteContainer(){}onUpdateComment(){}}function aN(n){return new Promise(t=>{setTimeout(t,n)})}async function dN(n,t,e,o){for(const r of e){const i=new cN(n,r.user);t.parseHistoryData(r,i),o.play&&await aN(o.speed||150)}}const uN=`<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
743
743
  <path d="M0 0h24v24H0z" fill="none"/><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
744
- </svg>`,{t:ef}=S;class hN{constructor(t){h(this,"goBackButton");h(this,"playButton");h(this,"revertButton");this.options=t;const e=b("button",["dialog-text-button"],null),o=b("span",["dialog-button-icon"],e);o.innerHTML=uN,b("span",["dialog-button-text"],e,ef("version.goBack"));const r=b("button",["dialog-version-button"],null,ef("version.play")),i=b("button",["dialog-version-button"],null,ef("version.revertVersion"));this.goBackButton=e,this.playButton=r,this.revertButton=i,this.bindEvent()}bindEvent(){const{onBack:t,onPlay:e,onRevert:o}=this.options;this.playButton.onclick=e,this.goBackButton.onclick=t,this.revertButton.onclick=o}disabledButton(){}render(t,e=!1){e||t.append(this.goBackButton,this.playButton,this.revertButton)}destroy(){this.playButton.onclick=null,this.goBackButton.onclick=null,this.revertButton.onclick=null}}const he=y("split-text-actions");function Y3(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function Q3(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function K3(n){return n.length>2?!1:n.length===1?n[0].insert===void 0&&n[0].delete===void 0&&n[0].attributes!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function fN(n){const t=[],e=Y.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(Q3(n)||Y3(n)||K3(n)))return[n];const o=(i,s)=>i>0?[{retain:i},s]:[s];let r=0;for(;e.length>0;){const i=e[0];if(i.retain!==void 0&&i.attributes===void 0){d(he,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),d(he,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];d(he,s.delete||s.insert!==void 0||s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=i.retain,t.push(o(r,s)),s.delete!==void 0?r-=s.delete:s.insert!==void 0?r+=s.insert.length:(d(he,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),d(he,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else d(he,i.delete||i.insert!==void 0||i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),t.push(o(r,i)),e.shift(),i.retain!==void 0&&(d(he,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function J3(n){if(d(he,n.length===1||n.length===2,`not a single action op: ${JSON.stringify(n)}`),n.length===1)return 0;const t=n[0].retain;return d(he,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let X3=0;function mN(n,t,e){const o=X3;X3+=1;const r=Tt(n);return{insert:" ",attributes:{box:!0,id:N(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function gN(n,t,e){const o=J3(t),r=t.length===1?t[0].delete:t[1].delete;d(he,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=Kt(n,o,r),c=mN(s,o,e);return[...i,c,...l]}function pN(n,t,e){const o=J3(t),r=t.length===1?t[0].insert:t[1].insert;d(he,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=yl([{insert:r,attributes:i}],"insertedBy",e);return xr(n,o,l,null)}function CN(n,t,e){const o=fN(t).reverse();let r=n;for(const i of o)Q3(i)?r=gN(r,i,e):Y3(i)?r=pN(r,i,e):(d(he,K3(i),`unknown op: ${JSON.stringify(i)}`),r=ne.apply(r,i));return r}const bN=y("history-update-block-text");function t9(n){const t=[],e=[];let o=0;return n.forEach(r=>{var i;if((i=r.attributes)!=null&&i.box){const s=r.attributes;if(s.type==="history-deleted-box"){t.push({boxData:s,offset:o});return}}e.push(r),o+=A1(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function vN(n,t,e){let o=n;return t.forEach(r=>{const i=ne.transformCursor(r.offset,e,!1);o=xr(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function kN(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function yN(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{d(bN,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),kN(n);for(let e=n.length-1;e>=1;e--){const o=n[e],r=n[e-1];o.boxData.user.userId===r.boxData.user.userId&&(r.boxData.text+=o.boxData.text,n.splice(e,1))}return n}function wN(n){let{newText:t,deletedBoxes:e}=t9(n);const o=new Map;return e.forEach(i=>{let s=o.get(i.offset);s||(s=[],o.set(i.offset,s)),s.push(i),s.sort((l,c)=>l.boxData.deletedOffset-c.boxData.deletedOffset)}),Array.from(o.values()).sort((i,s)=>s[0].offset-i[0].offset).forEach(i=>{const s=i[0].offset;yN(i).reverse().forEach(l=>{t=xr(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function BN(n,t,e){let{newText:o,deletedBoxes:r}=t9(n);return o=CN(o,t,e),o=vN(o,r,t),o=wN(o),o}const Sn=y("history-doc");function Tn(n){d(Sn,!1,"no local actions for history doc")}class EN extends ki{constructor(e,o){super();h(this,"doc");h(this,"editor");this.doc=Y.default(e),this.editor=o}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(Sn,r,`no container data: ${e}`);const i=r[o];return d(Sn,i,`no block data: ${o}`),i}localUpdateBlockText(){Tn()}localUpdateBlockData(){Tn()}localInsertBlock(){Tn()}localDeleteBlock(){Tn()}localInsertChildContainer(){Tn()}localDeleteChildContainers(){Tn()}uploadResource(){Tn()}async addResources(e){Tn()}getServerMeta(){var e,o,r;return(r=(o=(e=this.editor.doc.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}buildResourceUrl(e){return this.editor.doc.externalDoc.buildResourceUrl(e)}request(){Tn()}broadcastMessage(){Tn()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ql}destroy(){this.clearCallbacks()}transformBlockIndex(e,o,r){const i=this.doc.blocks[e];d(Sn,i,`no container blocks: ${e}`);let s=0;for(let l=0;l<i.length;l++)if(!i[l].deletedBy){if(s===o)return l;s++}return r?(d(Sn,!1,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),-1):(d(Sn,s===o,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),i.length)}onDeleteBlock(e,o,r){const i=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e][i];d(Sn,!l.deleted,`block has already deleted: ${e}/${o}`),l.deletedBy=r,this.callbacks.forEach(c=>{var a;return(a=c.onUpdateBlockData)==null?void 0:a.call(c,e,i,{insert:{},delete:[]},!0)})}onInsertBlock(e,o,r,i){const s=this.transformBlockIndex(e,o,!1),l=this.doc.blocks[e],c=Y.default(r);c.insertedBy=i,l.splice(s,0,c),this.callbacks.forEach(a=>{var u;return(u=a.onInsertBlock)==null?void 0:u.call(a,e,s,c,!0)})}onUpdateBlockText(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),c=this.doc.blocks[e][s];d(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=c.text;d(Sn,a,`no text for block: ${JSON.stringify(c)}`);const u=BN(a,r,i);c.text=u,this.callbacks.forEach(f=>{var m;return(m=f.onUpdateBlockText)==null?void 0:m.call(f,e,o,r,!0)})}onUpdateBlockData(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e],c=l[s];d(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=Y.default(c);a.updatedBy=i,r.delete.forEach(u=>delete a[u]),Object.entries(r.insert).forEach(([u,f])=>{a[u]=f}),l[s]=a,this.callbacks.forEach(u=>{var f;return(f=u.onUpdateBlockData)==null?void 0:f.call(u,e,s,r,!0)})}onCreateContainer(e,o,r){this.doc.blocks[e]=Y.default(o),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,!0)})}}const{t:e9}=S;function li(n,t){return t==="insert"?e9("version.insert",{name:n.displayName}):e9("version.delete",{name:n.displayName})}function sr(n,t){const{userId:e}=t;return["flag","selection"].reduce((r,i)=>{const s=n.doc.getRemoteUsers().getFixedUserColor(e,i);return r[i]=s,r},{})}class IN{renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=sr(t,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=sr(t,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":li(r,"delete")},styles:{[ri]:i,[ii]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=sr(t,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=sr(t,i);M(o,"history-deleted-block"),Wa(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"delete")}),Ga(o,{[ri]:s,[ii]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=sr(t,i);M(o,"history-inserted-block"),Wa(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"insert")}),Ga(o,{[ri]:s,[ii]:l})}}}const n9=y("history-deleted-box");function xN(n,t,e,o){const r=o;d(n9,r.text,`no text for text box data: ${JSON.stringify(o)}`),d(n9,typeof r.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`);const i=b("span",["history-deleted-box"],e,r.text),s=r.user,{flag:l,selection:c}=sr(n,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",li(s,"delete")),i.style.setProperty(ri,l),i.style.setProperty(ii,c)}const SN={boxType:"history-deleted-box",updateBoxContent:xN},Se=y("version-dialog");class TN{constructor(t,e){h(this,"editor");h(this,"dialog",null);h(this,"oldViewer",null);h(this,"versionOptions",{});h(this,"versionList",null);h(this,"actionButtons",null);h(this,"provider");h(this,"components");h(this,"handleClose",()=>{var t;(t=this.dialog)==null||t.hide()});h(this,"handlePlay",()=>{var e;d(Se,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Se,t,`The version: ${t} is invalid`),this.viewVersion(t,{play:!0,speed:150})});h(this,"handleRevert",async()=>{var e,o;d(Se,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Se,t,`The version: ${t} is invalid`),await this.versionHelper.revertVersion(t.version),(o=this.dialog)==null||o.hide()});h(this,"handleSelectVersion",t=>{d(Se,t,`The version: ${t} is invalid`),this.viewVersion(t)});h(this,"viewVersion",async(t,e={play:!1,speed:1e3})=>{this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),d(Se,this.versionList,"The versionList did not render"),d(Se,this.actionButtons,"The actionButtons did not render");const o=t.type==="minor"?this.versionList.beforeVersion:this.versionList.beforeMajorVersion,r=o?o.version:0,i=this.versionList.isSelectedFirstVersion,s=this.versionList.isSelectedLastVersion;this.actionButtons.revertButton.disabled=i,this.actionButtons.playButton.disabled=i;let l=this.versionOptions.hideOps;if(this.versionOptions.onWillChangeVersion){const C=this.versionOptions.onWillChangeVersion(this.editor,t,i,s);C!=null&&C.hideOps&&(l=!0)}let c,a;if(l)c=await this.versionHelper.getVersion(t.version),a=[];else{const C=await this.versionHelper.getHistoryData(t.version,r);c=C.doc,a=C.historyData}const{editorElement:u}=this.components;u.innerHTML="";const f=new EN(c,this.editor),m=this.provider.createHistoryEditor(u,f);m.editorBlockRenders.registerRender(new IN),m.editorBoxes.registerBoxClass(SN),M(m.rootElement,G3.HISTORY);try{await dN(f,this.versionHelper,a,e)}finally{this.oldViewer=m}this.versionOptions.onVersionChanged&&this.versionOptions.onVersionChanged(this.editor,m,t,i,s)});this.editor=t,this.provider=e;const o=b("div",["version-dialog"],null),r=b("div",["version-dialog-note-viewer"],o),i=b("div",["version-dialog-action-container"],r),s=b("div",["version-dialog-editor"],r),l=b("div",["version-dialog-versions-list"],o);this.components={root:o,editorElement:s,actionContainer:i,versionsListContainer:l}}get versionHelper(){d(Se,this.editor.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.editor.doc.getVersionHelper();return d(Se,t,"current doc does not support version"),t}renderContent(t){const{actionContainer:e,versionsListContainer:o}=this.components;e.innerHTML="";const{hideActions:r}=this.versionOptions,i=new hN({onBack:this.handleClose,onPlay:this.handlePlay,onRevert:this.handleRevert});i.render(e,r),this.actionButtons=i,o.innerHTML="";const s=new lN({versions:t,useCreatedBy:this.versionOptions.useCreatedBy,onSelectVersion:this.handleSelectVersion,getMarkColor:l=>{const{flag:c}=sr(this.editor,l);return c}});s.render(o),this.versionList=s}initViewVersion(){if(this.versionOptions.initSelectedVersion){d(Se,this.versionList,"The versionList did not render");const{initSelectedVersion:t}=this.versionOptions,e=this.versionList.selectVersionByVersionNum(t);d(Se,e,`The version: ${e} is invalid`),this.viewVersion(e)}else{d(Se,this.versionList,"The versionList did not render");const t=this.versionList.activeVersion;d(Se,t,`The version: ${t} is invalid`),this.viewVersion(t)}}async show(t={}){this.versionOptions={...this.versionOptions,...t};const e=await this.versionHelper.getVersions();if(this.versionOptions.hideNonVersionedOps&&e.length&&e[0].version===-1&&e.shift(),this.versionOptions.onVersionsLoaded&&this.versionOptions.onVersionsLoaded(this.editor,e),this.renderContent(e),this.initViewVersion(),!this.dialog){const{root:o}=this.components;this.dialog=new sN(o)}this.dialog.show()}destroy(){var t,e,o;(t=this.dialog)==null||t.destroy(),(e=this.versionList)==null||e.destroy(),(o=this.actionButtons)==null||o.destroy()}}function DN(n,t,e){n.addCustom("version-dialog",()=>new TN(n,t)).show(e)}const iz="",LN=y("heading-collapse");function nf(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return d(LN,t,"not a heading block"),t}function je(n){return!!n.getAttribute("data-style-heading")}function MN(n){return!lt(n,"heading-collapsed")}function lr(n){return lt(n,"heading-collapsed")}function o9(n){if(gt(n))return!1;const e=H(n);return Ct(e)}const RN=y("heading-collapse");function of(n){d(RN,je(n),"not a heading block");const t=[],e=nf(n);let o=ht(n);for(;o&&!(je(o)&&nf(o)<=e);)t.push(o),o=ht(o);return t}function r9(n,t){if(!Vo(t))return;n.selection.selectBlock(t,0),of(t).forEach(o=>{Em(o)}),M(t,"heading-collapsed")}function ci(n,t){of(t).forEach(o=>{Im(o)}),F(t,"heading-collapsed")}function AN(n,t){MN(t)?r9(n,t):ci(n,t)}const ON=[Qd,Kd,Jd,Xd,tu,eu,nu,ou];function _N(n){const t=b("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,"Collapse / Expand"),t.innerHTML=oc,t}function i9(n){return Gc(n).querySelector("button.heading-collapse-button")}function s9(n,t){i9(t)||o9(t)||!Vo(t)||yh(t,_N(n),-1)}function NN(n){var t;(t=i9(n))==null||t.remove()}function l9(n,t){Gc(t).querySelector("button.heading-collapse-button")||s9(n,t)}function PN(n){const t=nf(n),e=b("button",["heading-marker"],null);return e.innerHTML=ON[t-1],e}function c9(n){return Gc(n).querySelector("button.heading-marker")}function rf(n){c9(n)||o9(n)||!Vo(n)||yh(n,PN(n),1)}function a9(n){const t=c9(n);t==null||t.remove()}function d9(n){a9(n),je(n)&&rf(n)}class $N{handleDrop(t,e,o,r){if(sl(e)||!je(e)||!lr(e))return;const i=of(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((c,a,u)=>{const f=t.getBlockData(c),m=Fo(t.editorBlocks,t.doc.toJSON(),f),C=t.insertDocAt(o,r,m)[0];a===u.length-1&&(l=C)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(c=>{t.deleteBlock(c)}),t.doc.endBatchUpdate(),l&&r9(t,l),!0}}const HN=y("heading-collapse");class jN{constructor(t){h(this,"handleLoad",()=>{this.showCollapseButtons()});h(this,"handleHoverBlock",(t,e)=>{e&&(F(e,"hovering-heading"),je(e)&&Ct(H(e))&&(rf(e),lr(e)||NN(e))),t&&je(t)&&Ct(H(t))&&(M(t,"hovering-heading"),a9(t),s9(this.editor,t))});h(this,"handleClick",(t,e)=>{const o=Bi(e,"button.heading-collapse-button");if(!o)return;const r=z(o);!r||(d(HN,je(r),"not a heading block"),AN(this.editor,r),l9(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),_t.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{Ts.get(t).addHandler(new $N)})}showCollapseButtons(){const t=Rt(this.editor.rootContainer).filter(je);t.length!==0&&(t[0]===Qt(this.editor.rootContainer)&&t.splice(0,1),t.forEach(rf))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function ua(n){const t=n.selection.range;if(t.isCollapsed()||t.start.blockId===t.end.blockId)return;const e=n.getBlockById(t.start.blockId),o=n.getBlockById(t.end.blockId);lr(e)&&ci(n,e),lr(o)&&ci(n,o)}function FN(n){ua(n);const t=n.getFocusedBlock();!je(t)||lr(t)&&ci(n,t)}function zN(n){ua(n);const t=n.getFocusedBlock();if(!je(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===Z(n,t)&&lr(t)&&ci(n,t)}function VN(n){ua(n);const t=n.getFocusedBlock();if(!je(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&lr(t)&&ci(n,t)}class UN{handleBeforeKeyDown(t,e){return Ka(e.key)&&ua(t),e.key==="Enter"?(FN(t),!1):e.key==="Delete"?(zN(t),!1):(e.key==="Backspace"&&VN(t),!1)}}class qN{constructor(t){this.editor=t}onInsertBlock(t,e,o,r){this.updateBlockIfNeeded(o.id)}onUpdateBlockData(t,e,o,r){const i=this.editor.doc.getBlockData(t,e);this.updateBlockIfNeeded(i.id,o)}updateBlockIfNeeded(t,e){setTimeout(()=>{const o=this.editor.findBlockById(t);if(!!o){if(!je(o)){e&&e.delete.includes("heading")&&d9(o);return}lt(o,"hovering-heading")&&l9(this.editor,o),d9(o)}},100)}}function WN(n){return!!n.heading}function u9(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function h9(n,t){var e;return{parentNode:t,children:[],text:Tt((e=n.text)!=null?e:[]),level:u9(n),block:n}}class Ns{constructor(){h(this,"nodes",[])}appendBlock(t){const e=this.findParent(u9(t),this.nodes);e?e.children.push(h9(t,e)):this.nodes.push(h9(t,null))}findParent(t,e){const o=e[e.length-1];if(!o||t<=1)return null;if(o.level===t-1)return o;const r=this.findParent(t,o.children);return r||(o.level<t?o:null)}static buildToc(t){const e=new Ns,o=t.blocks.root;for(let r=0;r<o.length;r++){const i=o[r];WN(i)&&e.appendBlock(i)}return e}}class cr extends Wt.TypedEmitter{constructor(e){super();h(this,"toc",new Ns);h(this,"updateToc",ie.default(()=>{this.updateTocNow()},500));this.editor=e,e.doc.registerCallback(this),this.updateToc()}destroy(){this.editor.doc.unregisterCallback(this)}isHeadingBlock(e){return!!e.heading}onInsertBlock(e,o,r,i){e==="root"&&this.isHeadingBlock(r)&&this.updateToc()}onDeleteBlock(e,o,r){e==="root"&&this.updateToc()}onUpdateBlockText(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}onUpdateBlockData(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}static register(e){return e.addCustom("editor-toc",()=>new cr(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=Ns.buildToc(this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const sz="";function GN(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function sf(n,t){t.forEach(e=>{const o=b("div",["toc-node"],n),r=b("div",["toc-title"],o);if(b("span",["toc-text"],r,e.text).setAttribute("data-block-id",e.block.id),e.children.length>0){const s=b("div",["toc-children"],o);sf(s,e.children)}})}function ZN(n,t){const e=Bi(t,".toc-text");if(!e)return;const o=e.getAttribute("data-block-id");if(!o)return;const r=n.findBlockById(o);!r||(t.preventDefault(),t.stopPropagation(),n.selection.selectBlock(r,0))}function f9(n,t,e){if(F(t,"loading"),t.innerHTML="",GN(e)){b("div",["toc-empty-message"],t,"No toc");return}e.nodes.length===1?sf(t,e.nodes[0].children):sf(t,e.nodes),xd(n,"toc-click-handler",()=>{n.addListener("click",ZN)})}class YN{constructor(t){h(this,"handleUpdateToc",(t,e)=>{Array.from(t.rootContainer.querySelectorAll('.embed-block[data-type="editor-block"][data-embed-type="toc"]')).forEach(r=>{const i=r.querySelector(".editor-toc-container");i&&f9(t,i,e)})});this.editor=t,cr.register(t).addListener("change",this.handleUpdateToc)}destroy(){cr.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return cr.register(this.editor).toc}}function QN(n,t){const e=b("div",["editor-toc-container"],t),r=n.addCustom("init-editor-toc",()=>new YN(n)).toc;r.nodes.length===0?M(e,"loading"):f9(n,e,r)}function KN(n,t,e,o){return o==="markdown"?"[toc]":""}function JN(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!j(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"toc",embedData:r}}}const m9={embedType:"toc",createEmbedContent:QN,convertTo:KN,convertFrom:JN};function XN(n){return!!n.getAttribute("data-style-heading")}function lf(n,t){return XN(t)&&Z(n,t)>0}function tP(n){const t=Nn(n.rootElement);let e=0,o=0,r=0;if(t===document.documentElement){const i=n.rootContainer.getBoundingClientRect();e=i.left+i.width/2,o=10,r=t.offsetHeight}else{const i=t.getBoundingClientRect();e=i.left+i.width/2,o=i.top+10,r=i.bottom}for(;o<r;){const i=document.elementsFromPoint(e,o);for(let s=0;s<i.length;s++){const l=z(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function cf(n,t){let e=t;for(;e&&!lf(n,e);)e=ht(e);return e}function g9(n){if(gt(n))return!1;const e=H(n);return Ct(e)}function ha(n,t){let e=t;for(;e&&!lf(n,e);)e=gt(e),e&&g9(e)&&(e=null);return e}const eP=.3;class nP extends Wt.TypedEmitter{constructor(e){super();h(this,"scrollContainer");h(this,"scrollEventTarget");h(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});h(this,"handleScroll",ie.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=tP(this.editor);if(o&&(o=ul(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(g9(o)&&(o=ht(o)),!o){this.setStatus(e);return}if(lf(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=ha(this.editor,o),e.nextHeadingBlock=cf(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=cf(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*eP){e.curHeadingBlock=i,e.previousHeadingBlock=ha(this.editor,i),e.nextHeadingBlock=cf(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=ha(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=ha(this.editor,s)),this.setStatus(e)},200));this.editor=e,setTimeout(()=>{this.start()},50)}setStatus(e){this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock&&this.scrollStatus.nextHeadingBlock===e.nextHeadingBlock&&this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock||(this.scrollStatus=e,this.emit("change",this.editor,e))}start(){this.stop(),this.scrollContainer=Nn(this.editor.rootElement),this.scrollEventTarget=this.scrollContainer===document.documentElement?document:this.scrollContainer,this.scrollEventTarget.addEventListener("scroll",this.handleScroll),this.handleScroll()}stop(){this.scrollEventTarget&&this.scrollEventTarget.removeEventListener("scroll",this.handleScroll)}destroy(){this.stop(),this.scrollEventTarget=void 0}}class oP{constructor(t,e){h(this,"suggest");h(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Vo(i)){const s=z(H(i));if(s&&it(s)==="code")return!1}return!0});h(this,"onClickItem",(t,e,o)=>{const r=e.data,i={id:N(),type:"mention",box:!0,created:Date.now(),iconUrl:r.avatarUrl,text:r.displayName,mentionId:r.userId},s=this.editor.selection.range;if(!s.isCollapsed()||!s.isSimple())return;const l=s.focus,c=this.editor.getBlockById(l.blockId);this.editor.insertBoxToBlock(c,l.offset,i)});h(this,"queryItems",async(t,e)=>(await this.options.queryUsers(this.editor,e)).map(i=>({id:i.userId,name:i.displayName,icon:`<img src="${i.avatarUrl}" class="mention-user-avatar">`,element:i.element,data:i})));this.editor=t,this.options=e,this.suggest=new uu(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}destroy(){}}y("mathjax-box");function rP(n,t,e,o){const r=o,i=b("a",["mention-container"],e);b("span",["mention-name"],i,`@${r.text}`),i.setAttribute("data-mention-id",r.mentionId)}function iP(n,t,e){}const p9={boxType:"mention",updateBoxContent:rP,handleClickBox:iP};function sP(n){return kn("list-block-mention",S.t("list.mention.tooltip"),op,[],n.clientId)}class lP{constructor(t){h(this,"mentionButton");h(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?At(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});h(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=z(this.mentionButton);if(!o||!j(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=Z(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=Tt(Ae(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});h(this,"destroy",()=>{_t.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=sP(t),_t.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!j(this.editor,t)||!at(t))return!1;const e=He(t);return!(e==="ordered"||e==="unordered")}}const lz="",cP={templates:{title:"\u9009\u62E9\u6A21\u677F\uFF0C\u5FEB\u901F\u521B\u5EFA",create:"\u65B0\u5EFA\u6A21\u677F",choose:"\u5168\u90E8\u6A21\u677F",customizedMark:"\u81EA\u5B9A\u4E49"}},aP={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}};S.mergeLang({"zh-CN":cP,"en-US":aP});const cz="",az="",dP="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",uP="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",C9=y("templates");function af(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return d(C9,e,"no card container"),{root:t,cardContainer:e}}function hP(n){const t=af(n);if(t)return t.cardContainer.innerHTML="",t;const e=b("div",["editor-templates"],n.rootElement);b("div",["editor-templates-title"],e,S.t("templates.title"));const o=b("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function b9(n,t,e,o,r){var f;const i=(f=n.options.componentsOptions)==null?void 0:f.templates,s=b("div",["editor-template-card",...o],null),l=b("div",["editor-template-thumb-container"],s),c=b("img",["editor-template-thumb"],l);c.src=t,c.style.display="none",c.onerror=()=>{var C;const m=(C=i==null?void 0:i.placeHolderImageSrc)!=null?C:uP;c.src!==m&&(c.src=m)},c.onload=()=>{c.style.display=""};const a=b("div",["editor-template-name"],s),u=b("span",[],a,e);return i!=null&&i.showTemplateTitleAttr&&u.setAttribute("title",e),s.onclick=()=>r(s),s}function fP(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function mP(n,t){const e=fP(n,t);return b9(n,e,t.name,[],async()=>{var r,i;const o=(r=n.options.componentsOptions)==null?void 0:r.templates;(i=o==null?void 0:o.onApplyTemplate)==null||i.call(o,n,t)})}function gP(n,t){return b9(n,t,S.t("templates.choose"),["more"],()=>{var o,r;const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onChooseTemplate)==null||r.call(e,n)})}function pP(n,t){var f,m;const e=(f=n.options.componentsOptions)==null?void 0:f.templates;if(!e)return;const r=Gt(n.rootContainer).getBoundingClientRect().width;let i=1;const s=dP,l=af(n);if(l){if(t!=null&&t.reset){const C=Array.from(l.cardContainer.children),v=l.cardContainer.firstElementChild;if(d(C9,v,"no first card"),lt(v,"new")||lt(v,"more"))return;const w=window.getComputedStyle(v),E=parseFloat(w.marginLeft),L=parseFloat(w.marginRight),x=v.getBoundingClientRect().width+E+L;i=Math.floor(r/x);const O=Math.max(1,i-1-1),P=C.length-2;C.forEach((U,tt)=>{tt>O&&tt<P?U.style.display="none":(tt>=P&&lt(U,"more"),U.style.display="")})}return}const c=e.templates,{cardContainer:a}=hP(n);c.forEach((C,v)=>{const w=mP(n,C);if(v>0&&v>=i&&(w.style.display="none"),a.appendChild(w),v===0){const E=window.getComputedStyle(w),L=parseFloat(E.marginLeft),x=parseFloat(E.marginRight),A=w.getBoundingClientRect().width+L+x;i=Math.floor(r/A)-1}});const u=gP(n,s);a.appendChild(u),(m=e==null?void 0:e.onTemplateChooserStatusChanged)==null||m.call(e,n,a,"visible")}const v9=ie.default(pP,50);function CP(n){var o,r;const t=af(n);if(!t)return;t.root.remove();const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onTemplateChooserStatusChanged)==null||r.call(e,n,null,"hide")}function bP(n){const t=n.blocks.root;if(t.length===0)return!0;if(t.length>5)return!1;const e=[...t];e[0].type==="text"&&e[0].heading&&e.splice(0,1);const o=r=>{var i;return r.type!=="text"&&r.type!=="list"?!1:r.text?((i=r.text)==null?void 0:i.length)===0:!0};return e.every(r=>o(r))}function k9(n,t){bP(n.doc.toJSON())?v9(n,t):(v9.cancel(),CP(n))}class Ps{constructor(t,e){h(this,"_decrypted",!1);this.editor=t,this.blockData=e}get decrypted(){return this._decrypted||this.blockData.owner===this.editor.doc.getUser().userId}setDecrypted(){this._decrypted=!0}destroy(){}static getState(t,e){return t.addCustom(`encrypted-block-${e.id}`,()=>new Ps(t,e))}}const dz="",bo=y("encrypted-block");function vP(n,t,e,o,r){const i=r,s=eo(o,"div"),l=Ps.getState(n,i);if(l.decrypted)n.createChildContainer(t,s,i.children[0]),M(o,"decrypted");else{M(o,"encrypted");const c=At(o),a=b("div",["password-container"],c),u=b("input",[],a);u.type="text",u.onkeydown=f=>{if(f.key==="Enter"){const m=u.value;if(i.password===Ci.default(`${i.owner}-${m}`)){l.setDecrypted(),n.reloadBlock(o);const C=y1(n,n.getBlockById(i.id));C&&(n.selection.selectBlock(C,0),n.focus())}}}}return s}function kP(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!fn(r))return null;const i=r;if(n.getBlockData(t).children[0]!==V(i))return null;const l=bt(t,V(i));return new Ye(n,{anchor:l,focus:l})}function yP(n,t,e,o){if(Ps.getState(n,n.getBlockData(t)).decrypted)return null;if(o==="ArrowDown"||o==="ArrowRight"){const s=ht(t);return s?$(s,Z(n,s),"end"):$(t,1,"end")}const i=gt(t);return $(i||t,0,"home")}function wP(n,t){return n.getBoundingClientRect()}function BP(n,t,e,o){if(e.isSimple()){d(bo,o.isSimple(),"from is simple position but to is not simple position"),bo.debug("full select table"),M(t,"full-selected");return}d(bo,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(bo,r.blockId===i.blockId,"only allow update one table selection"),d(bo,r.childContainerId===i.childContainerId,"only one container");const s=n.getBlockData(t),l=n.getContainerById(s.children[0]);M(l,"selected")}function EP(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="encrypted"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("selected").forEach(e=>{F(e,"selected")})})}function IP(n,t){const e=n.getBlockData(t);return Ps.getState(n,e).decrypted?[n.getContainerById(e.children[0])]:[]}function xP(n,t,e,o,r){return null}function SP(n,t,e,o){d(bo,e.blockId===o.blockId,"only allow select in single block"),d(bo,G(t)===e.blockId,"only allow select in single block");const r=n.getBlockData(t);return d(bo,e.childContainerId===r.children[0],"only one container"),[n.getContainerById(r.children[0])]}function TP(n){return{name:"EncryptedBlock",insertBlockCommandItems:[{id:"insert-encrypted-block",name:"Encrypted Block"}],async handleInsertEmptyBlock(t,e){const o=pn(t.doc),r={id:N(),type:"encrypted",children:[o],owner:t.doc.getUser().userId,ownerDisplayName:t.doc.getUser().displayName,password:Ci.default(`${t.doc.getUser().userId}-1234`)},i=t.doc.getContainerBlocks(o)[0];return t.insertBlock(e.containerId,e.blockIndex,r,Ot(t,i.id,0))}}}const DP={blockType:"encrypted",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:vP,getBlockTextLength:()=>1,getRangeFromPoint:kP,moveCaret:yP,getCaretRect:wP,updateSelection:BP,clearSelection:EP,getChildContainers:IP,getNextContainer:xP,getSelectedContainers:SP,getOptions:TP};function LP(n,t,e){const o=Vi(n,t,{components:{blocks:[Cs,ks,DP],decorators:[new ws],embeds:[Jc,hh,Rh,Ah,Oh,Qu,_h,tf,Xh],boxes:[Lc],options:{...e.componentsOptions}}});return o.readonly=!0,o}class MP{constructor(t){this.createOptions=t}createHistoryEditor(t,e){return LP(t,e,this.createOptions)}}y("create-editor");function RP({root:n,localDoc:t,rootEditorCreateOptions:e,shareDBDoc:o}){t.uploadResource=o.uploadResource.bind(o),t.buildResourceUrl=o.buildResourceUrl.bind(o);const r=Vi(n,t,{shortcuts:[Vl],components:{blocks:[Cs,ks],decorators:[new ws],embeds:[b6,Jc,hh,Rh,Ah,Oh,Qu,_h,tf,Xh],boxes:[Lc,p9],options:{...e.componentsOptions}}});return r.input.addHandler(new Hc),r.input.addHandler(new Nh(r)),r.input.addHandler(new n_(r)),r}function AP(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),o=new Set;e.forEach(r=>{const i=z(r);i&&o.add(i)}),o.forEach(r=>{o_(n,r,t)})}class OP{constructor(t,e){h(this,"listeners",new Set);h(this,"doc");this.editor=t,this.rootEditorCreateOptions=e,this.doc=this.editor.doc.externalDoc,this.doc.registerCallback(this)}getAuth(){return this.doc.client.auth}getComments(){return this.doc.getComments()}getComment(t){return this.doc.getComment(t)}getCommentDoc(t){return this.doc.getCommentDoc(t)}localCreateComment(t,e){this.doc.localCreateComment(t,e)}localDeleteComment(t){const e=this.getComment(t);this.doc.localDeleteComment(t);const o=e.groupId;this.getComments().filter(i=>i.groupId===o).length===0&&AP(this.editor,o)}localUpdateComment(t,e){this.doc.localUpdateComment(t,e)}onCreateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onCreateComment(t,e))}onDeleteComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onDeleteComment(t,e))}onUpdateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onUpdateComment(t,e))}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}createCommentEditor(t,e){return RP({root:t,localDoc:e,rootEditorCreateOptions:this.rootEditorCreateOptions,shareDBDoc:this.doc})}}const y9=y("create-editor"),w9=[Jc,hh,Rh,Ah,Oh,Qu,_h,tf,Xh,b6,m9,F_];async function _P(n,t){var r,i,s,l,c,a,u,f,m;d(y9,n,"app does not exists");const e=await ec.load({auth:{appId:t.appId,docId:t.docId,userId:t.user.userId,permission:t.permission,token:t.token,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl},serverUrl:t.serverUrl}),o=Vi(n,e,{id:t.id,components:{blocks:[Cs,ks,bh,s4],commandProviders:[new yu],decorators:[new ws,new zd],embeds:[...w9,...((r=t.components)==null?void 0:r.embeds)||[]],boxes:[Lc,p9,N3],insertions:[j1],blockHooks:[new d6],textRenders:[new L3,new hx],options:{...t.componentsOptions}},shortcuts:[TD,lM,ih,a3,fx,Xu,Vl]});if(o.editorCommandProviders.registerCommandProvider(new xn(o)),o.input.addHandler(new UN),o.input.addHandler(new Hc),o.input.addHandler(new vs(o,{headingLevel:1,titlePlaceholder:"Document title",addPlaceholderToAllCurrentEmptyBlock:!0})),o.input.addHandler(new Mc(o,(i=t.componentsOptions)==null?void 0:i.quickMenu)),o.input.addHandler(new Nh(o)),o.input.addHandler(new t3(o)),o.doc.registerCallback(new qN(o)),o.addCustom("remote-cursor",()=>new s5(o)),o.addCustom("block-menu",C=>new m6(C)),o.addCustom("editor-tooltip",()=>new Ju(o)),o.addCustom("editor-comments",C=>new JO(C,new OP(C,t))),o.addCustom("create-options",()=>new Pf(o,t)),o.addCustom("drop-target",()=>new Ts(o)),o.addCustom("list-to-mindmap",()=>new Sc(o)),o.addCustom("list-to-mention",()=>new lP(o)),(s=t.componentsOptions)!=null&&s.mention){const C=t.componentsOptions.mention;o.addCustom("mention",()=>new oP(o,C))}if(o.addCustom("heading-collapse",()=>new jN(o)),Gr.register(o),Ts.register(o),cr.register(o),(c=(l=t.componentsOptions)==null?void 0:l.remoteCarets)!=null&&c.onUserChanged){const C=(u=(a=t.componentsOptions)==null?void 0:a.remoteCarets)==null?void 0:u.onUserChanged;o.doc.getRemoteUsers().on("change",v=>{C(o,v)})}return(m=(f=t.componentsOptions)==null?void 0:f.templates)!=null&&m.templates.length&&(o.addListener("docChanged",()=>{k9(o)}),setTimeout(()=>{k9(o)},100)),o}async function NP(n,t,e){var i,s;d(y9,n,"app does not exists");const o=new Id(t),r=Vi(n,o,{id:e.id,components:{blocks:[Cs,ks,bh,s4],commandProviders:[new yu],decorators:[new ws,new zd],embeds:[...w9,...((i=e.components)==null?void 0:i.embeds)||[]],boxes:[Lc,N3],insertions:[j1],blockHooks:[new d6],textRenders:[new L3],options:{...e.componentsOptions}},shortcuts:[ih,a3,Xu,Vl]});return r.editorCommandProviders.registerCommandProvider(new xn(r)),r.input.addHandler(new Hc),r.input.addHandler(new vs(r,{headingLevel:1,titlePlaceholder:"Document title",contentPlaceholder:"Enter some text...",addPlaceholderToAllCurrentEmptyBlock:!0})),r.input.addHandler(new Mc(r,(s=e.componentsOptions)==null?void 0:s.quickMenu)),r.input.addHandler(new Nh(r)),r.input.addHandler(new t3(r)),r.addCustom("block-menu",l=>new m6(l)),r.addCustom("editor-tooltip",()=>new Ju(r)),Gr.register(r),r}function PP(n,t){var l;const e=n.doc;if(!((l=e.getVersionHelper)==null?void 0:l.call(e)))throw new Error("the editor does not support to show versions");const r=n.getCustom("create-options");if(!r)throw new Error("the editor does not support to show versions");const i=r.getData(),s=new MP(i);return DN(n,s,t)}g.AuthError=Xl,g.AuthHeader=es,g.AutoScroll=bm,g.BaseURLHeader=tc,g.BlockResizer=$c,g.BrBox=Zg,g.CodeBlock=ks,g.CodeLineBlock=bh,g.CodeTextDecorator=ws,g.DefaultShortcuts=Vl,g.DocIdError=uw,g.DragDrop=Kf,g.DrawioEmbed=Jc,g.EditorBlocks=og,g.EditorBoxes=Qg,g.EditorCommandProviders=k0,g.EditorComplexBlockPosition=Ze,g.EditorComplexSelectionRange=Ye,g.EditorDecorators=t2,g.EditorEmbeds=ig,g.EditorInsertions=Xg,g.EditorSimpleBlockPosition=Vt,g.EditorSimpleSelectionRange=se,g.EmbedBlock=lg,g.EnforceWithDocumentTitleHandler=vs,g.EventCallbacks=ki,g.FILL_CHAR=Eb,g.FileExtError=hw,g.HeadingBlockScrollListener=nP,g.InputtingInsertion=Kg,g.LocalDoc=Id,g.Logger=vi,g.MIN_DISTANCE_THRESHOLD=Yf,g.MarkdownInputHandler=Hc,g.MaxUserError=Pd,g.OnesEditorCustomDataWrapper=Pf,g.OnesEditorHoveringBlock=_t,g.OnesEditorQuickMenu=Mc,g.OnesEditorToc=Ns,g.OnesEditorTocProvider=cr,g.OnesEditorToolbar=Gr,g.OnesEditorTooltip=Ju,g.PermissionError=dw,g.RemoteCarets=s5,g.RemoteCaretsDecorator=zd,g.RemoteCaretsInsertion=j1,g.RemoteUsers=ql,g.RequestReloadError=ts,g.RichText=ne,g.ShareDBDoc=ec,g.SimpleCache=Hf,g.StandardEmbedBlockCommands=dh,g.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=_1,g.TEXT_STYLE_COLOR_PREFIX=O1,g.TableBlock=Cs,g.TableBlockCommandProvider=yu,g.TableShortcuts=ih,g.TextBlock=_i,g.TextBox=Gg,g.TextStyleShortcuts=Xu,g.TocEmbed=m9,g.ZERO_WIDTH_SPACE_CHAR=yi,g.addAttribute=yl,g.addClass=M,g.addCommentToBlock=ah,g.addDays=tC,g.addMonths=X8,g.animateScrollTo=Ei,g.applyPlaceholderToBlock=jc,g.assert=d,g.blockToDoc=nd,g.blockToHtml=F1,g.blockToMarkdown=e2,g.blockToText=Dl,g.blocksToDoc=tv,g.clearAllSelection=Wm,g.clientType=It,g.cloneBlock=Fo,g.cloneChildContainer=K1,g.cloneDoc=J1,g.cloneText=Pg,g.compareElement=Xs,g.comparePosition=v1,g.complexBlockAdjustSelectionPos=ml,g.complexBlockFindNearestChildBlock=ug,g.complexBlockGeFirstSimpleChild=y1,g.complexBlockGetAllChildContainers=Le,g.complexBlockGetBottomChildContainers=dg,g.complexBlockGetLastSimpleChild=wr,g.complexBlockGetSelectedContainers=yr,g.complexBlockGetTopChildContainers=ag,g.containerToDoc=od,g.continuousScroll=Cm,g.convertBlockFrom=hl,g.copyBlockAttributes=d2,g.createBlockAnchor=_o,g.createBlockContentElement=eo,g.createBlockElement=Sm,g.createBlockSimpleDocRange=Tl,g.createBlockSimpleRange=Ot,g.createBoxContentElement=Lm,g.createBoxElement=Tm,g.createBoxOp=Tg,g.createChildContainer=Vm,g.createComplexBlockPosition=bt,g.createComplexDocPos=Ug,g.createComplexDocRange=xb,g.createContainer=jg,g.createContainerElement=u1,g.createDeleteOps=Eg,g.createEditor=Vi,g.createEditorSelectionRange=Ut,g.createElement=b,g.createEmptyContainer=pn,g.createEmptyDoc=oo,g.createEmptyTextBlockData=Il,g.createExpandedRange=Ks,g.createIconButton=hr,g.createImage=jf,g.createInsertOps=kl,g.createInsertionContentElement=Am,g.createInsertionElement=Mm,g.createLocalEditor=NP,g.createOnesEditor=_P,g.createRange=Ff,g.createRichText=Oi,g.createRootContainer=zm,g.createSimpleBlockPosition=$,g.createSimpleDocPos=Vg,g.createTextBlockData=jn,g.createTextButton=Xo,g.createTextOp=_e,g.createTextWithReplaceSoftReturn=L1,g.daysAfter=n1,g.deleteText=R1,g.diffDays=eC,g.disablePageScroll=dm,g.docToHtml=jb,g.docToHtmlFragment=n2,g.docToMarkdown=Fb,g.docToText=o2,g.downloadObjectToFile=Sh,g.downloadSvgToString=k6,g.editLink=vc,g.editorAddComment=i_,g.editorAddTextAttribute=B2,g.editorAutoInsertBlock=u2,g.editorBreakTextBlock=Pi,g.editorClearCompositionText=a2,g.editorClearSelectedContents=Y1,g.editorCopyBlock=cd,g.editorDeleteBlock=G1,g.editorDeleteBlockText=U1,g.editorDeleteBlockWithoutChildren=W1,g.editorDeleteChildContainer=Yb,g.editorDeleteChildContainers=m2,g.editorFocusToBlock=Q1,g.editorFocusToEnd=S2,g.editorGetBlockData=ro,g.editorGetBlockText=ke,g.editorGetBlockTextEx=Ml,g.editorGetBoxData=r2,g.editorHandleKeyboardEvent=e0,g.editorInsertBlock=Dr,g.editorInsertBoxToBlock=l2,g.editorInsertDoc=y2,g.editorInsertDocAt=X1,g.editorInsertText=V1,g.editorInsertTextToBlock=s2,g.editorInsertTextToBlockEx=z1,g.editorMergeTextBlock=g2,g.editorRangeClearColor=I2,g.editorRangeGetColor=td,g.editorRangeSetColor=E2,g.editorRemoveTextAttribute=Jb,g.editorReplaceBlockText=Nl,g.editorReplaceContainer=w2,g.editorRunOnce=xd,g.editorSelectEnd=x2,g.editorSetTextColor=Lr,g.editorShowFindDialog=aO,g.editorUpdateBlockData=Pl,g.editorUpdateCompositionText=c2,g.editorUpdateEmbedData=v2,g.enablePageScroll=um,g.escapeHtmlText=Wf,g.escapeRegExp=i1,g.escapeSpace=N8,g.executeBlockCommand=ng,g.executeEmbedBlockCommand=eg,g.executeRangeCommand=v0,g.fileToDataUrl=nl,g.findAllText=$1,g.findInsertionById=Rm,g.findPrevSimpleBlockBeforeChildContainer=cg,g.findTarget=Bi,g.format=e1,g.formatBytes=vm,g.formatDate=wm,g.fragmentToHtml=hm,g.fromBase64=el,g.fromBase64ToBlob=cm,g.fromBase64ToUint8Array=Z8,g.fromDocRange=no,g.fromNowString=r1,g.genId=N,g.getAllChildBlocks=B1,g.getAllQuickMenuItems=Ku,g.getAllSelectedBlocks=Qe,g.getAttributesAt=Bl,g.getBlockBackground=xm,g.getBlockByIndex=mr,g.getBlockCaretRect=Ge,g.getBlockClass=kt,g.getBlockClassByType=vr,g.getBlockClientRects=Ao,g.getBlockCommandsWithHook=p1,g.getBlockContent=rt,g.getBlockId=G,g.getBlockIndex=K,g.getBlockKind=We,g.getBlockMinWidth=Zm,g.getBlockOptions=uC,g.getBlockPath=Ro,g.getBlockProperties=Km,g.getBlockStyles=aC,g.getBlockTextLength=Z,g.getBlockTools=At,g.getBlockType=it,g.getBoxContent=c1,g.getBoxId=Dm,g.getBoxTypeFromElement=Si,g.getChildBlockCount=Ve,g.getChildBlocks=Rt,g.getChildOffset=Er,g.getColorFromAttributes=P1,g.getComplexBlockClass=ve,g.getContainerBlockPath=Hm,g.getContainerBlocks=Pm,g.getContainerBlocksElement=dl,g.getContainerById=br,g.getContainerId=V,g.getContainerMinWidth=m1,g.getContainerToolsElement=rC,g.getContainerWidth=Qm,g.getDistanceSquare=hn,g.getElementOffset=wi,g.getEmbedType=De,g.getExistsBlockTools=al,g.getExistsContainerById=_m,g.getFileExt=mm,g.getFirstChildBlock=Qt,g.getFirstClientRect=Js,g.getHeadingMenuOptions=Dc,g.getHorizontalPadding=Ua,g.getInsertionContent=a1,g.getLastChildBlock=Gt,g.getLastClientRect=xo,g.getLogger=y,g.getNextBlock=ht,g.getNextValidOffset=Ir,g.getNextVisibleBlock=Cr,g.getOpAt=Lg,g.getOpLength=A1,g.getParentBlock=z,g.getParentBox=l1,g.getParentContainer=H,g.getPrevBlock=gt,g.getPrevValidOffset=Po,g.getPrevVisibleBlock=pr,g.getRangeCommands=C0,g.getRootBlock=ul,g.getScrollContainer=Nn,g.getSpecialBlockCommands=Jm,g.getStandardEmbedBlockProperties=uh,g.getTextBlockChild=gl,g.getTextBlockClass=qm,g.getTextBlockContentChildTextLength=Re,g.getTextBlockContentChildType=hg,g.getTextBlockContentChildren=Hn,g.getTextLength=ce,g.getTextOpLength=I1,g.getTextWidth=rl,g.getToolbar=bc,g.handleBlockElementUpdated=Ym,g.hasAltOnly=z8,g.hasClass=lt,g.hasCtrlOrCmd=rm,g.hasCtrlOrCmdOnly=F8,g.hideBlock=Em,g.htmlToFragment=ol,g.i18n=S,g.injectStyle=Zf,g.insertEmptyBlock=fC,g.insertEmptyEmbedBlock=tg,g.insertText=xr,g.intersectionCommands=iy,g.isBackspace=sm,g.isBlock=gr,g.isBox=s1,g.isCJK=em,g.isChildContainer=qe,g.isChildNode=vt,g.isCollapsedRange=zg,g.isComplexBlockPosition=b1,g.isComplexKindBlock=ct,g.isContainer=fn,g.isControlEvent=Do,g.isDelete=U8,g.isDraggingFiles=sl,g.isEmbedBlock=Te,g.isEmptyContainer=g1,g.isEmptyDoc=xl,g.isEmptyTextBlock=wt,g.isEmptyTextBlockWithoutCompositionText=bs,g.isEnterOnly=im,g.isEscape=Ja,g.isFirefox=Qa,g.isFirstChildBlockInComplexBlock=jC,g.isHighSurrogate=L8,g.isInBlock=d1,g.isInBlockTools=Ti,g.isLetter=tm,g.isLowSurrogate=Va,g.isMatchShortcut=_n,g.isMoveForward=H8,g.isNavigationEvent=$8,g.isNavigationKey=om,g.isNodeRemoved=Vf,g.isNumber=Xf,g.isPrintableKey=Ka,g.isRootBlock=Vo,g.isRootContainer=Ct,g.isSafari=nm,g.isSameDay=o1,g.isShiftEnter=V8,g.isShiftTab=W8,g.isShortcutEvent=j8,g.isSimpleBlock=dC,g.isSimpleBlockPosition=kr,g.isSimplePos=Fg,g.isSimpleRange=Sl,g.isSpace=tl,g.isTab=q8,g.isTextBlockContentBoxChild=Me,g.isTextBlockContentChild=Li,g.isTextBlockContentInsertionChild=$n,g.isTextBlockContentTextChild=Mi,g.isTextKindBlock=j,g.isTextKindBlockType=Di,g.isToday=km,g.isValidOffset=fe,g.isVisibleBlock=cl,g.isYesterday=ym,g.loadJs=Uf,g.loadJsPromise=So,g.lockers=Rn,g.mergeCommands=Cc,g.mergeDocs=jo,g.mergeOps=M1,g.mergeText=kb,g.multiSplitText=gg,g.parseShortcut=lm,g.patchNode=xi,g.pointInRect=To,g.rangeAddAttribute=wl,g.rangeGetTextColor=Ng,g.rangeRemoveAttribute=Sr,g.rangeSetTextColor=Ag,g.rangeTransformText=Mg,g.registerDragDrop=Za,g.removeAttribute=N1,g.removeClass=F,g.removeLastBr=pb,g.removePlaceholderFromBlock=j4,g.removeStyle=Gf,g.replaceAll=nC,g.replaceAllCaseInsensitive=oC,g.replaceAllText=Hg,g.replaceText=El,g.requestDownload=ll,g.scrollable=pm,g.selectFile=fr,g.selectedBlockToDoc=Hl,g.selectionToDoc=jl,g.setAttributes=Wa,g.setClipboardData=il,g.setClipboardDataByEvent=J8,g.setColorToAttributes=Og,g.setDataset=qa,g.setDefaultCursor=Ii,g.setStyles=Ga,g.shortcutToDisplayText=G8,g.showBlock=Im,g.showDocVersions=PP,g.splitText=Ae,g.splitToThree=Kt,g.stringToDataUrl=am,g.stringToObjectUrl=t1,g.subText=pg,g.textNodeOffsetFromPoint=zf,g.toBase64URL=Lo,g.toPlainText=Tt,g.trimChar=Ya,g.unicodeLength=M8,g.unicodeSubstr=R8,g.updateBlockSelection=Gm,g.updateOpAttributes=$g,g.updateTextBlockContent=Mb,g.updateUrl=Xa,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
744
+ </svg>`,{t:ef}=S;class hN{constructor(t){h(this,"goBackButton");h(this,"playButton");h(this,"revertButton");this.options=t;const e=b("button",["dialog-text-button"],null),o=b("span",["dialog-button-icon"],e);o.innerHTML=uN,b("span",["dialog-button-text"],e,ef("version.goBack"));const r=b("button",["dialog-version-button"],null,ef("version.play")),i=b("button",["dialog-version-button"],null,ef("version.revertVersion"));this.goBackButton=e,this.playButton=r,this.revertButton=i,this.bindEvent()}bindEvent(){const{onBack:t,onPlay:e,onRevert:o}=this.options;this.playButton.onclick=e,this.goBackButton.onclick=t,this.revertButton.onclick=o}disabledButton(){}render(t,e=!1){e||t.append(this.goBackButton,this.playButton,this.revertButton)}destroy(){this.playButton.onclick=null,this.goBackButton.onclick=null,this.revertButton.onclick=null}}const he=y("split-text-actions");function Y3(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function Q3(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function K3(n){return n.length>2?!1:n.length===1?n[0].insert===void 0&&n[0].delete===void 0&&n[0].attributes!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function fN(n){const t=[],e=Y.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(Q3(n)||Y3(n)||K3(n)))return[n];const o=(i,s)=>i>0?[{retain:i},s]:[s];let r=0;for(;e.length>0;){const i=e[0];if(i.retain!==void 0&&i.attributes===void 0){d(he,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),d(he,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];d(he,s.delete||s.insert!==void 0||s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=i.retain,t.push(o(r,s)),s.delete!==void 0?r-=s.delete:s.insert!==void 0?r+=s.insert.length:(d(he,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),d(he,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else d(he,i.delete||i.insert!==void 0||i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),t.push(o(r,i)),e.shift(),i.retain!==void 0&&(d(he,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function J3(n){if(d(he,n.length===1||n.length===2,`not a single action op: ${JSON.stringify(n)}`),n.length===1)return 0;const t=n[0].retain;return d(he,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let X3=0;function mN(n,t,e){const o=X3;X3+=1;const r=Tt(n);return{insert:" ",attributes:{box:!0,id:N(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function gN(n,t,e){const o=J3(t),r=t.length===1?t[0].delete:t[1].delete;d(he,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=Kt(n,o,r),c=mN(s,o,e);return[...i,c,...l]}function pN(n,t,e){const o=J3(t),r=t.length===1?t[0].insert:t[1].insert;d(he,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=yl([{insert:r,attributes:i}],"insertedBy",e);return xr(n,o,l,null)}function CN(n,t,e){const o=fN(t).reverse();let r=n;for(const i of o)Q3(i)?r=gN(r,i,e):Y3(i)?r=pN(r,i,e):(d(he,K3(i),`unknown op: ${JSON.stringify(i)}`),r=ne.apply(r,i));return r}const bN=y("history-update-block-text");function t9(n){const t=[],e=[];let o=0;return n.forEach(r=>{var i;if((i=r.attributes)!=null&&i.box){const s=r.attributes;if(s.type==="history-deleted-box"){t.push({boxData:s,offset:o});return}}e.push(r),o+=A1(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function vN(n,t,e){let o=n;return t.forEach(r=>{const i=ne.transformCursor(r.offset,e,!1);o=xr(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function kN(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function yN(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{d(bN,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),kN(n);for(let e=n.length-1;e>=1;e--){const o=n[e],r=n[e-1];o.boxData.user.userId===r.boxData.user.userId&&(r.boxData.text+=o.boxData.text,n.splice(e,1))}return n}function wN(n){let{newText:t,deletedBoxes:e}=t9(n);const o=new Map;return e.forEach(i=>{let s=o.get(i.offset);s||(s=[],o.set(i.offset,s)),s.push(i),s.sort((l,c)=>l.boxData.deletedOffset-c.boxData.deletedOffset)}),Array.from(o.values()).sort((i,s)=>s[0].offset-i[0].offset).forEach(i=>{const s=i[0].offset;yN(i).reverse().forEach(l=>{t=xr(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function BN(n,t,e){let{newText:o,deletedBoxes:r}=t9(n);return o=CN(o,t,e),o=vN(o,r,t),o=wN(o),o}const Sn=y("history-doc");function Tn(n){d(Sn,!1,"no local actions for history doc")}class EN extends ki{constructor(e,o){super();h(this,"doc");h(this,"editor");this.doc=Y.default(e),this.editor=o}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(Sn,r,`no container data: ${e}`);const i=r[o];return d(Sn,i,`no block data: ${o}`),i}localUpdateBlockText(){Tn()}localUpdateBlockData(){Tn()}localInsertBlock(){Tn()}localDeleteBlock(){Tn()}localInsertChildContainer(){Tn()}localDeleteChildContainers(){Tn()}uploadResource(){Tn()}async addResources(e){Tn()}getServerMeta(){var e,o,r;return(r=(o=(e=this.editor.doc.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}buildResourceUrl(e){return this.editor.doc.externalDoc.buildResourceUrl(e)}request(){Tn()}broadcastMessage(){Tn()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ql}destroy(){this.clearCallbacks()}transformBlockIndex(e,o,r){const i=this.doc.blocks[e];d(Sn,i,`no container blocks: ${e}`);let s=0;for(let l=0;l<i.length;l++)if(!i[l].deletedBy){if(s===o)return l;s++}return r&&d(Sn,!1,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),d(Sn,s===o,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),i.length}onDeleteBlock(e,o,r){const i=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e][i];d(Sn,!l.deleted,`block has already deleted: ${e}/${o}`),l.deletedBy=r,this.callbacks.forEach(c=>{var a;return(a=c.onUpdateBlockData)==null?void 0:a.call(c,e,i,{insert:{},delete:[]},!0)})}onInsertBlock(e,o,r,i){const s=this.transformBlockIndex(e,o,!1),l=this.doc.blocks[e],c=Y.default(r);c.insertedBy=i,l.splice(s,0,c),this.callbacks.forEach(a=>{var u;return(u=a.onInsertBlock)==null?void 0:u.call(a,e,s,c,!0)})}onUpdateBlockText(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),c=this.doc.blocks[e][s];d(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=c.text;d(Sn,a,`no text for block: ${JSON.stringify(c)}`);const u=BN(a,r,i);c.text=u,this.callbacks.forEach(f=>{var m;return(m=f.onUpdateBlockText)==null?void 0:m.call(f,e,o,r,!0)})}onUpdateBlockData(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e],c=l[s];d(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=Y.default(c);a.updatedBy=i,r.delete.forEach(u=>delete a[u]),Object.entries(r.insert).forEach(([u,f])=>{a[u]=f}),l[s]=a,this.callbacks.forEach(u=>{var f;return(f=u.onUpdateBlockData)==null?void 0:f.call(u,e,s,r,!0)})}onCreateContainer(e,o,r){this.doc.blocks[e]=Y.default(o),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,!0)})}}const{t:e9}=S;function li(n,t){return t==="insert"?e9("version.insert",{name:n.displayName}):e9("version.delete",{name:n.displayName})}function sr(n,t){const{userId:e}=t;return["flag","selection"].reduce((r,i)=>{const s=n.doc.getRemoteUsers().getFixedUserColor(e,i);return r[i]=s,r},{})}class IN{renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=sr(t,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=sr(t,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":li(r,"delete")},styles:{[ri]:i,[ii]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=sr(t,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=sr(t,i);M(o,"history-deleted-block"),Wa(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"delete")}),Ga(o,{[ri]:s,[ii]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=sr(t,i);M(o,"history-inserted-block"),Wa(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"insert")}),Ga(o,{[ri]:s,[ii]:l})}}}const n9=y("history-deleted-box");function xN(n,t,e,o){const r=o;d(n9,r.text,`no text for text box data: ${JSON.stringify(o)}`),d(n9,typeof r.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`);const i=b("span",["history-deleted-box"],e,r.text),s=r.user,{flag:l,selection:c}=sr(n,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",li(s,"delete")),i.style.setProperty(ri,l),i.style.setProperty(ii,c)}const SN={boxType:"history-deleted-box",updateBoxContent:xN},Se=y("version-dialog");class TN{constructor(t,e){h(this,"editor");h(this,"dialog",null);h(this,"oldViewer",null);h(this,"versionOptions",{});h(this,"versionList",null);h(this,"actionButtons",null);h(this,"provider");h(this,"components");h(this,"handleClose",()=>{var t;(t=this.dialog)==null||t.hide()});h(this,"handlePlay",()=>{var e;d(Se,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Se,t,`The version: ${t} is invalid`),this.viewVersion(t,{play:!0,speed:150})});h(this,"handleRevert",async()=>{var e,o;d(Se,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Se,t,`The version: ${t} is invalid`),await this.versionHelper.revertVersion(t.version),(o=this.dialog)==null||o.hide()});h(this,"handleSelectVersion",t=>{d(Se,t,`The version: ${t} is invalid`),this.viewVersion(t)});h(this,"viewVersion",async(t,e={play:!1,speed:1e3})=>{this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),d(Se,this.versionList,"The versionList did not render"),d(Se,this.actionButtons,"The actionButtons did not render");const o=t.type==="minor"?this.versionList.beforeVersion:this.versionList.beforeMajorVersion,r=o?o.version:0,i=this.versionList.isSelectedFirstVersion,s=this.versionList.isSelectedLastVersion;this.actionButtons.revertButton.disabled=i,this.actionButtons.playButton.disabled=i;let l=this.versionOptions.hideOps;if(this.versionOptions.onWillChangeVersion){const C=this.versionOptions.onWillChangeVersion(this.editor,t,i,s);C!=null&&C.hideOps&&(l=!0)}let c,a;if(l)c=await this.versionHelper.getVersion(t.version),a=[];else{const C=await this.versionHelper.getHistoryData(t.version,r);c=C.doc,a=C.historyData}const{editorElement:u}=this.components;u.innerHTML="";const f=new EN(c,this.editor),m=this.provider.createHistoryEditor(u,f);m.editorBlockRenders.registerRender(new IN),m.editorBoxes.registerBoxClass(SN),M(m.rootElement,G3.HISTORY);try{await dN(f,this.versionHelper,a,e)}finally{this.oldViewer=m}this.versionOptions.onVersionChanged&&this.versionOptions.onVersionChanged(this.editor,m,t,i,s)});this.editor=t,this.provider=e;const o=b("div",["version-dialog"],null),r=b("div",["version-dialog-note-viewer"],o),i=b("div",["version-dialog-action-container"],r),s=b("div",["version-dialog-editor"],r),l=b("div",["version-dialog-versions-list"],o);this.components={root:o,editorElement:s,actionContainer:i,versionsListContainer:l}}get versionHelper(){d(Se,this.editor.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.editor.doc.getVersionHelper();return d(Se,t,"current doc does not support version"),t}renderContent(t){const{actionContainer:e,versionsListContainer:o}=this.components;e.innerHTML="";const{hideActions:r}=this.versionOptions,i=new hN({onBack:this.handleClose,onPlay:this.handlePlay,onRevert:this.handleRevert});i.render(e,r),this.actionButtons=i,o.innerHTML="";const s=new lN({versions:t,useCreatedBy:this.versionOptions.useCreatedBy,onSelectVersion:this.handleSelectVersion,getMarkColor:l=>{const{flag:c}=sr(this.editor,l);return c}});s.render(o),this.versionList=s}initViewVersion(){if(this.versionOptions.initSelectedVersion){d(Se,this.versionList,"The versionList did not render");const{initSelectedVersion:t}=this.versionOptions,e=this.versionList.selectVersionByVersionNum(t);d(Se,e,`The version: ${e} is invalid`),this.viewVersion(e)}else{d(Se,this.versionList,"The versionList did not render");const t=this.versionList.activeVersion;d(Se,t,`The version: ${t} is invalid`),this.viewVersion(t)}}async show(t={}){this.versionOptions={...this.versionOptions,...t};const e=await this.versionHelper.getVersions();if(this.versionOptions.hideNonVersionedOps&&e.length&&e[0].version===-1&&e.shift(),this.versionOptions.onVersionsLoaded&&this.versionOptions.onVersionsLoaded(this.editor,e),this.renderContent(e),this.initViewVersion(),!this.dialog){const{root:o}=this.components;this.dialog=new sN(o)}this.dialog.show()}destroy(){var t,e,o;(t=this.dialog)==null||t.destroy(),(e=this.versionList)==null||e.destroy(),(o=this.actionButtons)==null||o.destroy()}}function DN(n,t,e){n.addCustom("version-dialog",()=>new TN(n,t)).show(e)}const iz="",LN=y("heading-collapse");function nf(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return d(LN,t,"not a heading block"),t}function je(n){return!!n.getAttribute("data-style-heading")}function MN(n){return!lt(n,"heading-collapsed")}function lr(n){return lt(n,"heading-collapsed")}function o9(n){if(gt(n))return!1;const e=H(n);return Ct(e)}const RN=y("heading-collapse");function of(n){d(RN,je(n),"not a heading block");const t=[],e=nf(n);let o=ht(n);for(;o&&!(je(o)&&nf(o)<=e);)t.push(o),o=ht(o);return t}function r9(n,t){if(!Vo(t))return;n.selection.selectBlock(t,0),of(t).forEach(o=>{Em(o)}),M(t,"heading-collapsed")}function ci(n,t){of(t).forEach(o=>{Im(o)}),F(t,"heading-collapsed")}function AN(n,t){MN(t)?r9(n,t):ci(n,t)}const ON=[Qd,Kd,Jd,Xd,tu,eu,nu,ou];function _N(n){const t=b("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,"Collapse / Expand"),t.innerHTML=oc,t}function i9(n){return Gc(n).querySelector("button.heading-collapse-button")}function s9(n,t){i9(t)||o9(t)||!Vo(t)||yh(t,_N(n),-1)}function NN(n){var t;(t=i9(n))==null||t.remove()}function l9(n,t){Gc(t).querySelector("button.heading-collapse-button")||s9(n,t)}function PN(n){const t=nf(n),e=b("button",["heading-marker"],null);return e.innerHTML=ON[t-1],e}function c9(n){return Gc(n).querySelector("button.heading-marker")}function rf(n){c9(n)||o9(n)||!Vo(n)||yh(n,PN(n),1)}function a9(n){const t=c9(n);t==null||t.remove()}function d9(n){a9(n),je(n)&&rf(n)}class $N{handleDrop(t,e,o,r){if(sl(e)||!je(e)||!lr(e))return;const i=of(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((c,a,u)=>{const f=t.getBlockData(c),m=Fo(t.editorBlocks,t.doc.toJSON(),f),C=t.insertDocAt(o,r,m)[0];a===u.length-1&&(l=C)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(c=>{t.deleteBlock(c)}),t.doc.endBatchUpdate(),l&&r9(t,l),!0}}const HN=y("heading-collapse");class jN{constructor(t){h(this,"handleLoad",()=>{this.showCollapseButtons()});h(this,"handleHoverBlock",(t,e)=>{e&&(F(e,"hovering-heading"),je(e)&&Ct(H(e))&&(rf(e),lr(e)||NN(e))),t&&je(t)&&Ct(H(t))&&(M(t,"hovering-heading"),a9(t),s9(this.editor,t))});h(this,"handleClick",(t,e)=>{const o=Bi(e,"button.heading-collapse-button");if(!o)return;const r=z(o);!r||(d(HN,je(r),"not a heading block"),AN(this.editor,r),l9(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),_t.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{Ts.get(t).addHandler(new $N)})}showCollapseButtons(){const t=Rt(this.editor.rootContainer).filter(je);t.length!==0&&(t[0]===Qt(this.editor.rootContainer)&&t.splice(0,1),t.forEach(rf))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function ua(n){const t=n.selection.range;if(t.isCollapsed()||t.start.blockId===t.end.blockId)return;const e=n.getBlockById(t.start.blockId),o=n.getBlockById(t.end.blockId);lr(e)&&ci(n,e),lr(o)&&ci(n,o)}function FN(n){ua(n);const t=n.getFocusedBlock();!je(t)||lr(t)&&ci(n,t)}function zN(n){ua(n);const t=n.getFocusedBlock();if(!je(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===Z(n,t)&&lr(t)&&ci(n,t)}function VN(n){ua(n);const t=n.getFocusedBlock();if(!je(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&lr(t)&&ci(n,t)}class UN{handleBeforeKeyDown(t,e){return Ka(e.key)&&ua(t),e.key==="Enter"?(FN(t),!1):e.key==="Delete"?(zN(t),!1):(e.key==="Backspace"&&VN(t),!1)}}class qN{constructor(t){this.editor=t}onInsertBlock(t,e,o,r){this.updateBlockIfNeeded(o.id)}onUpdateBlockData(t,e,o,r){const i=this.editor.doc.getBlockData(t,e);this.updateBlockIfNeeded(i.id,o)}updateBlockIfNeeded(t,e){setTimeout(()=>{const o=this.editor.findBlockById(t);if(!!o){if(!je(o)){e&&e.delete.includes("heading")&&d9(o);return}lt(o,"hovering-heading")&&l9(this.editor,o),d9(o)}},100)}}function WN(n){return!!n.heading}function u9(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function h9(n,t){var e;return{parentNode:t,children:[],text:Tt((e=n.text)!=null?e:[]),level:u9(n),block:n}}class Ns{constructor(){h(this,"nodes",[])}appendBlock(t){const e=this.findParent(u9(t),this.nodes);e?e.children.push(h9(t,e)):this.nodes.push(h9(t,null))}findParent(t,e){const o=e[e.length-1];if(!o||t<=1)return null;if(o.level===t-1)return o;const r=this.findParent(t,o.children);return r||(o.level<t?o:null)}static buildToc(t){const e=new Ns,o=t.blocks.root;for(let r=0;r<o.length;r++){const i=o[r];WN(i)&&e.appendBlock(i)}return e}}class cr extends Wt.TypedEmitter{constructor(e){super();h(this,"toc",new Ns);h(this,"updateToc",ie.default(()=>{this.updateTocNow()},500));this.editor=e,e.doc.registerCallback(this),this.updateToc()}destroy(){this.editor.doc.unregisterCallback(this)}isHeadingBlock(e){return!!e.heading}onInsertBlock(e,o,r,i){e==="root"&&this.isHeadingBlock(r)&&this.updateToc()}onDeleteBlock(e,o,r){e==="root"&&this.updateToc()}onUpdateBlockText(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}onUpdateBlockData(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}static register(e){return e.addCustom("editor-toc",()=>new cr(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=Ns.buildToc(this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const sz="";function GN(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function sf(n,t){t.forEach(e=>{const o=b("div",["toc-node"],n),r=b("div",["toc-title"],o);if(b("span",["toc-text"],r,e.text).setAttribute("data-block-id",e.block.id),e.children.length>0){const s=b("div",["toc-children"],o);sf(s,e.children)}})}function ZN(n,t){const e=Bi(t,".toc-text");if(!e)return;const o=e.getAttribute("data-block-id");if(!o)return;const r=n.findBlockById(o);!r||(t.preventDefault(),t.stopPropagation(),n.selection.selectBlock(r,0))}function f9(n,t,e){if(F(t,"loading"),t.innerHTML="",GN(e)){b("div",["toc-empty-message"],t,"No toc");return}e.nodes.length===1?sf(t,e.nodes[0].children):sf(t,e.nodes),xd(n,"toc-click-handler",()=>{n.addListener("click",ZN)})}class YN{constructor(t){h(this,"handleUpdateToc",(t,e)=>{Array.from(t.rootContainer.querySelectorAll('.embed-block[data-type="editor-block"][data-embed-type="toc"]')).forEach(r=>{const i=r.querySelector(".editor-toc-container");i&&f9(t,i,e)})});this.editor=t,cr.register(t).addListener("change",this.handleUpdateToc)}destroy(){cr.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return cr.register(this.editor).toc}}function QN(n,t){const e=b("div",["editor-toc-container"],t),r=n.addCustom("init-editor-toc",()=>new YN(n)).toc;r.nodes.length===0?M(e,"loading"):f9(n,e,r)}function KN(n,t,e,o){return o==="markdown"?"[toc]":""}function JN(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!j(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"toc",embedData:r}}}const m9={embedType:"toc",createEmbedContent:QN,convertTo:KN,convertFrom:JN};function XN(n){return!!n.getAttribute("data-style-heading")}function lf(n,t){return XN(t)&&Z(n,t)>0}function tP(n){const t=Nn(n.rootElement);let e=0,o=0,r=0;if(t===document.documentElement){const i=n.rootContainer.getBoundingClientRect();e=i.left+i.width/2,o=10,r=t.offsetHeight}else{const i=t.getBoundingClientRect();e=i.left+i.width/2,o=i.top+10,r=i.bottom}for(;o<r;){const i=document.elementsFromPoint(e,o);for(let s=0;s<i.length;s++){const l=z(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function cf(n,t){let e=t;for(;e&&!lf(n,e);)e=ht(e);return e}function g9(n){if(gt(n))return!1;const e=H(n);return Ct(e)}function ha(n,t){let e=t;for(;e&&!lf(n,e);)e=gt(e),e&&g9(e)&&(e=null);return e}const eP=.3;class nP extends Wt.TypedEmitter{constructor(e){super();h(this,"scrollContainer");h(this,"scrollEventTarget");h(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});h(this,"handleScroll",ie.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=tP(this.editor);if(o&&(o=ul(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(g9(o)&&(o=ht(o)),!o){this.setStatus(e);return}if(lf(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=ha(this.editor,o),e.nextHeadingBlock=cf(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=cf(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*eP){e.curHeadingBlock=i,e.previousHeadingBlock=ha(this.editor,i),e.nextHeadingBlock=cf(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=ha(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=ha(this.editor,s)),this.setStatus(e)},200));this.editor=e,setTimeout(()=>{this.start()},50)}setStatus(e){this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock&&this.scrollStatus.nextHeadingBlock===e.nextHeadingBlock&&this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock||(this.scrollStatus=e,this.emit("change",this.editor,e))}start(){this.stop(),this.scrollContainer=Nn(this.editor.rootElement),this.scrollEventTarget=this.scrollContainer===document.documentElement?document:this.scrollContainer,this.scrollEventTarget.addEventListener("scroll",this.handleScroll),this.handleScroll()}stop(){this.scrollEventTarget&&this.scrollEventTarget.removeEventListener("scroll",this.handleScroll)}destroy(){this.stop(),this.scrollEventTarget=void 0}}class oP{constructor(t,e){h(this,"suggest");h(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Vo(i)){const s=z(H(i));if(s&&it(s)==="code")return!1}return!0});h(this,"onClickItem",(t,e,o)=>{const r=e.data,i={id:N(),type:"mention",box:!0,created:Date.now(),iconUrl:r.avatarUrl,text:r.displayName,mentionId:r.userId},s=this.editor.selection.range;if(!s.isCollapsed()||!s.isSimple())return;const l=s.focus,c=this.editor.getBlockById(l.blockId);this.editor.insertBoxToBlock(c,l.offset,i)});h(this,"queryItems",async(t,e)=>(await this.options.queryUsers(this.editor,e)).map(i=>({id:i.userId,name:i.displayName,icon:`<img src="${i.avatarUrl}" class="mention-user-avatar">`,element:i.element,data:i})));this.editor=t,this.options=e,this.suggest=new uu(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}destroy(){}}y("mathjax-box");function rP(n,t,e,o){const r=o,i=b("a",["mention-container"],e);b("span",["mention-name"],i,`@${r.text}`),i.setAttribute("data-mention-id",r.mentionId)}function iP(n,t,e){}const p9={boxType:"mention",updateBoxContent:rP,handleClickBox:iP};function sP(n){return kn("list-block-mention",S.t("list.mention.tooltip"),op,[],n.clientId)}class lP{constructor(t){h(this,"mentionButton");h(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?At(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});h(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=z(this.mentionButton);if(!o||!j(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=Z(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=Tt(Ae(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});h(this,"destroy",()=>{_t.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=sP(t),_t.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!j(this.editor,t)||!at(t))return!1;const e=He(t);return!(e==="ordered"||e==="unordered")}}const lz="",cP={templates:{title:"\u9009\u62E9\u6A21\u677F\uFF0C\u5FEB\u901F\u521B\u5EFA",create:"\u65B0\u5EFA\u6A21\u677F",choose:"\u5168\u90E8\u6A21\u677F",customizedMark:"\u81EA\u5B9A\u4E49"}},aP={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}};S.mergeLang({"zh-CN":cP,"en-US":aP});const cz="",az="",dP="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",uP="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",C9=y("templates");function af(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return d(C9,e,"no card container"),{root:t,cardContainer:e}}function hP(n){const t=af(n);if(t)return t.cardContainer.innerHTML="",t;const e=b("div",["editor-templates"],n.rootElement);b("div",["editor-templates-title"],e,S.t("templates.title"));const o=b("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function b9(n,t,e,o,r){var f;const i=(f=n.options.componentsOptions)==null?void 0:f.templates,s=b("div",["editor-template-card",...o],null),l=b("div",["editor-template-thumb-container"],s),c=b("img",["editor-template-thumb"],l);c.src=t,c.style.display="none",c.onerror=()=>{var C;const m=(C=i==null?void 0:i.placeHolderImageSrc)!=null?C:uP;c.src!==m&&(c.src=m)},c.onload=()=>{c.style.display=""};const a=b("div",["editor-template-name"],s),u=b("span",[],a,e);return i!=null&&i.showTemplateTitleAttr&&u.setAttribute("title",e),s.onclick=()=>r(s),s}function fP(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function mP(n,t){const e=fP(n,t);return b9(n,e,t.name,[],async()=>{var r,i;const o=(r=n.options.componentsOptions)==null?void 0:r.templates;(i=o==null?void 0:o.onApplyTemplate)==null||i.call(o,n,t)})}function gP(n,t){return b9(n,t,S.t("templates.choose"),["more"],()=>{var o,r;const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onChooseTemplate)==null||r.call(e,n)})}function pP(n,t){var f,m;const e=(f=n.options.componentsOptions)==null?void 0:f.templates;if(!e)return;const r=Gt(n.rootContainer).getBoundingClientRect().width;let i=1;const s=dP,l=af(n);if(l){if(t!=null&&t.reset){const C=Array.from(l.cardContainer.children),v=l.cardContainer.firstElementChild;if(d(C9,v,"no first card"),lt(v,"new")||lt(v,"more"))return;const w=window.getComputedStyle(v),E=parseFloat(w.marginLeft),L=parseFloat(w.marginRight),x=v.getBoundingClientRect().width+E+L;i=Math.floor(r/x);const O=Math.max(1,i-1-1),P=C.length-2;C.forEach((U,tt)=>{tt>O&&tt<P?U.style.display="none":(tt>=P&&lt(U,"more"),U.style.display="")})}return}const c=e.templates,{cardContainer:a}=hP(n);c.forEach((C,v)=>{const w=mP(n,C);if(v>0&&v>=i&&(w.style.display="none"),a.appendChild(w),v===0){const E=window.getComputedStyle(w),L=parseFloat(E.marginLeft),x=parseFloat(E.marginRight),A=w.getBoundingClientRect().width+L+x;i=Math.floor(r/A)-1}});const u=gP(n,s);a.appendChild(u),(m=e==null?void 0:e.onTemplateChooserStatusChanged)==null||m.call(e,n,a,"visible")}const v9=ie.default(pP,50);function CP(n){var o,r;const t=af(n);if(!t)return;t.root.remove();const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onTemplateChooserStatusChanged)==null||r.call(e,n,null,"hide")}function bP(n){const t=n.blocks.root;if(t.length===0)return!0;if(t.length>5)return!1;const e=[...t];e[0].type==="text"&&e[0].heading&&e.splice(0,1);const o=r=>{var i;return r.type!=="text"&&r.type!=="list"?!1:r.text?((i=r.text)==null?void 0:i.length)===0:!0};return e.every(r=>o(r))}function k9(n,t){bP(n.doc.toJSON())?v9(n,t):(v9.cancel(),CP(n))}class Ps{constructor(t,e){h(this,"_decrypted",!1);this.editor=t,this.blockData=e}get decrypted(){return this._decrypted||this.blockData.owner===this.editor.doc.getUser().userId}setDecrypted(){this._decrypted=!0}destroy(){}static getState(t,e){return t.addCustom(`encrypted-block-${e.id}`,()=>new Ps(t,e))}}const dz="",bo=y("encrypted-block");function vP(n,t,e,o,r){const i=r,s=eo(o,"div"),l=Ps.getState(n,i);if(l.decrypted)n.createChildContainer(t,s,i.children[0]),M(o,"decrypted");else{M(o,"encrypted");const c=At(o),a=b("div",["password-container"],c),u=b("input",[],a);u.type="text",u.onkeydown=f=>{if(f.key==="Enter"){const m=u.value;if(i.password===Ci.default(`${i.owner}-${m}`)){l.setDecrypted(),n.reloadBlock(o);const C=y1(n,n.getBlockById(i.id));C&&(n.selection.selectBlock(C,0),n.focus())}}}}return s}function kP(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!fn(r))return null;const i=r;if(n.getBlockData(t).children[0]!==V(i))return null;const l=bt(t,V(i));return new Ye(n,{anchor:l,focus:l})}function yP(n,t,e,o){if(Ps.getState(n,n.getBlockData(t)).decrypted)return null;if(o==="ArrowDown"||o==="ArrowRight"){const s=ht(t);return s?$(s,Z(n,s),"end"):$(t,1,"end")}const i=gt(t);return $(i||t,0,"home")}function wP(n,t){return n.getBoundingClientRect()}function BP(n,t,e,o){if(e.isSimple()){d(bo,o.isSimple(),"from is simple position but to is not simple position"),bo.debug("full select table"),M(t,"full-selected");return}d(bo,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(bo,r.blockId===i.blockId,"only allow update one table selection"),d(bo,r.childContainerId===i.childContainerId,"only one container");const s=n.getBlockData(t),l=n.getContainerById(s.children[0]);M(l,"selected")}function EP(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="encrypted"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("selected").forEach(e=>{F(e,"selected")})})}function IP(n,t){const e=n.getBlockData(t);return Ps.getState(n,e).decrypted?[n.getContainerById(e.children[0])]:[]}function xP(n,t,e,o,r){return null}function SP(n,t,e,o){d(bo,e.blockId===o.blockId,"only allow select in single block"),d(bo,G(t)===e.blockId,"only allow select in single block");const r=n.getBlockData(t);return d(bo,e.childContainerId===r.children[0],"only one container"),[n.getContainerById(r.children[0])]}function TP(n){return{name:"EncryptedBlock",insertBlockCommandItems:[{id:"insert-encrypted-block",name:"Encrypted Block"}],async handleInsertEmptyBlock(t,e){const o=pn(t.doc),r={id:N(),type:"encrypted",children:[o],owner:t.doc.getUser().userId,ownerDisplayName:t.doc.getUser().displayName,password:Ci.default(`${t.doc.getUser().userId}-1234`)},i=t.doc.getContainerBlocks(o)[0];return t.insertBlock(e.containerId,e.blockIndex,r,Ot(t,i.id,0))}}}const DP={blockType:"encrypted",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:vP,getBlockTextLength:()=>1,getRangeFromPoint:kP,moveCaret:yP,getCaretRect:wP,updateSelection:BP,clearSelection:EP,getChildContainers:IP,getNextContainer:xP,getSelectedContainers:SP,getOptions:TP};function LP(n,t,e){const o=Vi(n,t,{components:{blocks:[Cs,ks,DP],decorators:[new ws],embeds:[Jc,hh,Rh,Ah,Oh,Qu,_h,tf,Xh],boxes:[Lc],options:{...e.componentsOptions}}});return o.readonly=!0,o}class MP{constructor(t){this.createOptions=t}createHistoryEditor(t,e){return LP(t,e,this.createOptions)}}y("create-editor");function RP({root:n,localDoc:t,rootEditorCreateOptions:e,shareDBDoc:o}){t.uploadResource=o.uploadResource.bind(o),t.buildResourceUrl=o.buildResourceUrl.bind(o);const r=Vi(n,t,{shortcuts:[Vl],components:{blocks:[Cs,ks],decorators:[new ws],embeds:[b6,Jc,hh,Rh,Ah,Oh,Qu,_h,tf,Xh],boxes:[Lc,p9],options:{...e.componentsOptions}}});return r.input.addHandler(new Hc),r.input.addHandler(new Nh(r)),r.input.addHandler(new n_(r)),r}function AP(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),o=new Set;e.forEach(r=>{const i=z(r);i&&o.add(i)}),o.forEach(r=>{o_(n,r,t)})}class OP{constructor(t,e){h(this,"listeners",new Set);h(this,"doc");this.editor=t,this.rootEditorCreateOptions=e,this.doc=this.editor.doc.externalDoc,this.doc.registerCallback(this)}getAuth(){return this.doc.client.auth}getComments(){return this.doc.getComments()}getComment(t){return this.doc.getComment(t)}getCommentDoc(t){return this.doc.getCommentDoc(t)}localCreateComment(t,e){this.doc.localCreateComment(t,e)}localDeleteComment(t){const e=this.getComment(t);this.doc.localDeleteComment(t);const o=e.groupId;this.getComments().filter(i=>i.groupId===o).length===0&&AP(this.editor,o)}localUpdateComment(t,e){this.doc.localUpdateComment(t,e)}onCreateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onCreateComment(t,e))}onDeleteComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onDeleteComment(t,e))}onUpdateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onUpdateComment(t,e))}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}createCommentEditor(t,e){return RP({root:t,localDoc:e,rootEditorCreateOptions:this.rootEditorCreateOptions,shareDBDoc:this.doc})}}const y9=y("create-editor"),w9=[Jc,hh,Rh,Ah,Oh,Qu,_h,tf,Xh,b6,m9,F_];async function _P(n,t){var r,i,s,l,c,a,u,f,m;d(y9,n,"app does not exists");const e=await ec.load({auth:{appId:t.appId,docId:t.docId,userId:t.user.userId,permission:t.permission,token:t.token,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl},serverUrl:t.serverUrl}),o=Vi(n,e,{id:t.id,components:{blocks:[Cs,ks,bh,s4],commandProviders:[new yu],decorators:[new ws,new zd],embeds:[...w9,...((r=t.components)==null?void 0:r.embeds)||[]],boxes:[Lc,p9,N3],insertions:[j1],blockHooks:[new d6],textRenders:[new L3,new hx],options:{...t.componentsOptions}},shortcuts:[TD,lM,ih,a3,fx,Xu,Vl]});if(o.editorCommandProviders.registerCommandProvider(new xn(o)),o.input.addHandler(new UN),o.input.addHandler(new Hc),o.input.addHandler(new vs(o,{headingLevel:1,titlePlaceholder:"Document title",addPlaceholderToAllCurrentEmptyBlock:!0})),o.input.addHandler(new Mc(o,(i=t.componentsOptions)==null?void 0:i.quickMenu)),o.input.addHandler(new Nh(o)),o.input.addHandler(new t3(o)),o.doc.registerCallback(new qN(o)),o.addCustom("remote-cursor",()=>new s5(o)),o.addCustom("block-menu",C=>new m6(C)),o.addCustom("editor-tooltip",()=>new Ju(o)),o.addCustom("editor-comments",C=>new JO(C,new OP(C,t))),o.addCustom("create-options",()=>new Pf(o,t)),o.addCustom("drop-target",()=>new Ts(o)),o.addCustom("list-to-mindmap",()=>new Sc(o)),o.addCustom("list-to-mention",()=>new lP(o)),(s=t.componentsOptions)!=null&&s.mention){const C=t.componentsOptions.mention;o.addCustom("mention",()=>new oP(o,C))}if(o.addCustom("heading-collapse",()=>new jN(o)),Gr.register(o),Ts.register(o),cr.register(o),(c=(l=t.componentsOptions)==null?void 0:l.remoteCarets)!=null&&c.onUserChanged){const C=(u=(a=t.componentsOptions)==null?void 0:a.remoteCarets)==null?void 0:u.onUserChanged;o.doc.getRemoteUsers().on("change",v=>{C(o,v)})}return(m=(f=t.componentsOptions)==null?void 0:f.templates)!=null&&m.templates.length&&(o.addListener("docChanged",()=>{k9(o)}),setTimeout(()=>{k9(o)},100)),o}async function NP(n,t,e){var i,s;d(y9,n,"app does not exists");const o=new Id(t),r=Vi(n,o,{id:e.id,components:{blocks:[Cs,ks,bh,s4],commandProviders:[new yu],decorators:[new ws,new zd],embeds:[...w9,...((i=e.components)==null?void 0:i.embeds)||[]],boxes:[Lc,N3],insertions:[j1],blockHooks:[new d6],textRenders:[new L3],options:{...e.componentsOptions}},shortcuts:[ih,a3,Xu,Vl]});return r.editorCommandProviders.registerCommandProvider(new xn(r)),r.input.addHandler(new Hc),r.input.addHandler(new vs(r,{headingLevel:1,titlePlaceholder:"Document title",contentPlaceholder:"Enter some text...",addPlaceholderToAllCurrentEmptyBlock:!0})),r.input.addHandler(new Mc(r,(s=e.componentsOptions)==null?void 0:s.quickMenu)),r.input.addHandler(new Nh(r)),r.input.addHandler(new t3(r)),r.addCustom("block-menu",l=>new m6(l)),r.addCustom("editor-tooltip",()=>new Ju(r)),Gr.register(r),r}function PP(n,t){var l;const e=n.doc;if(!((l=e.getVersionHelper)==null?void 0:l.call(e)))throw new Error("the editor does not support to show versions");const r=n.getCustom("create-options");if(!r)throw new Error("the editor does not support to show versions");const i=r.getData(),s=new MP(i);return DN(n,s,t)}g.AuthError=Xl,g.AuthHeader=es,g.AutoScroll=bm,g.BaseURLHeader=tc,g.BlockResizer=$c,g.BrBox=Zg,g.CodeBlock=ks,g.CodeLineBlock=bh,g.CodeTextDecorator=ws,g.DefaultShortcuts=Vl,g.DocIdError=uw,g.DragDrop=Kf,g.DrawioEmbed=Jc,g.EditorBlocks=og,g.EditorBoxes=Qg,g.EditorCommandProviders=k0,g.EditorComplexBlockPosition=Ze,g.EditorComplexSelectionRange=Ye,g.EditorDecorators=t2,g.EditorEmbeds=ig,g.EditorInsertions=Xg,g.EditorSimpleBlockPosition=Vt,g.EditorSimpleSelectionRange=se,g.EmbedBlock=lg,g.EnforceWithDocumentTitleHandler=vs,g.EventCallbacks=ki,g.FILL_CHAR=Eb,g.FileExtError=hw,g.HeadingBlockScrollListener=nP,g.InputtingInsertion=Kg,g.LocalDoc=Id,g.Logger=vi,g.MIN_DISTANCE_THRESHOLD=Yf,g.MarkdownInputHandler=Hc,g.MaxUserError=Pd,g.OnesEditorCustomDataWrapper=Pf,g.OnesEditorHoveringBlock=_t,g.OnesEditorQuickMenu=Mc,g.OnesEditorToc=Ns,g.OnesEditorTocProvider=cr,g.OnesEditorToolbar=Gr,g.OnesEditorTooltip=Ju,g.PermissionError=dw,g.RemoteCarets=s5,g.RemoteCaretsDecorator=zd,g.RemoteCaretsInsertion=j1,g.RemoteUsers=ql,g.RequestReloadError=ts,g.RichText=ne,g.ShareDBDoc=ec,g.SimpleCache=Hf,g.StandardEmbedBlockCommands=dh,g.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=_1,g.TEXT_STYLE_COLOR_PREFIX=O1,g.TableBlock=Cs,g.TableBlockCommandProvider=yu,g.TableShortcuts=ih,g.TextBlock=_i,g.TextBox=Gg,g.TextStyleShortcuts=Xu,g.TocEmbed=m9,g.ZERO_WIDTH_SPACE_CHAR=yi,g.addAttribute=yl,g.addClass=M,g.addCommentToBlock=ah,g.addDays=tC,g.addMonths=X8,g.animateScrollTo=Ei,g.applyPlaceholderToBlock=jc,g.assert=d,g.blockToDoc=nd,g.blockToHtml=F1,g.blockToMarkdown=e2,g.blockToText=Dl,g.blocksToDoc=tv,g.clearAllSelection=Wm,g.clientType=It,g.cloneBlock=Fo,g.cloneChildContainer=K1,g.cloneDoc=J1,g.cloneText=Pg,g.compareElement=Xs,g.comparePosition=v1,g.complexBlockAdjustSelectionPos=ml,g.complexBlockFindNearestChildBlock=ug,g.complexBlockGeFirstSimpleChild=y1,g.complexBlockGetAllChildContainers=Le,g.complexBlockGetBottomChildContainers=dg,g.complexBlockGetLastSimpleChild=wr,g.complexBlockGetSelectedContainers=yr,g.complexBlockGetTopChildContainers=ag,g.containerToDoc=od,g.continuousScroll=Cm,g.convertBlockFrom=hl,g.copyBlockAttributes=d2,g.createBlockAnchor=_o,g.createBlockContentElement=eo,g.createBlockElement=Sm,g.createBlockSimpleDocRange=Tl,g.createBlockSimpleRange=Ot,g.createBoxContentElement=Lm,g.createBoxElement=Tm,g.createBoxOp=Tg,g.createChildContainer=Vm,g.createComplexBlockPosition=bt,g.createComplexDocPos=Ug,g.createComplexDocRange=xb,g.createContainer=jg,g.createContainerElement=u1,g.createDeleteOps=Eg,g.createEditor=Vi,g.createEditorSelectionRange=Ut,g.createElement=b,g.createEmptyContainer=pn,g.createEmptyDoc=oo,g.createEmptyTextBlockData=Il,g.createExpandedRange=Ks,g.createIconButton=hr,g.createImage=jf,g.createInsertOps=kl,g.createInsertionContentElement=Am,g.createInsertionElement=Mm,g.createLocalEditor=NP,g.createOnesEditor=_P,g.createRange=Ff,g.createRichText=Oi,g.createRootContainer=zm,g.createSimpleBlockPosition=$,g.createSimpleDocPos=Vg,g.createTextBlockData=jn,g.createTextButton=Xo,g.createTextOp=_e,g.createTextWithReplaceSoftReturn=L1,g.daysAfter=n1,g.deleteText=R1,g.diffDays=eC,g.disablePageScroll=dm,g.docToHtml=jb,g.docToHtmlFragment=n2,g.docToMarkdown=Fb,g.docToText=o2,g.downloadObjectToFile=Sh,g.downloadSvgToString=k6,g.editLink=vc,g.editorAddComment=i_,g.editorAddTextAttribute=B2,g.editorAutoInsertBlock=u2,g.editorBreakTextBlock=Pi,g.editorClearCompositionText=a2,g.editorClearSelectedContents=Y1,g.editorCopyBlock=cd,g.editorDeleteBlock=G1,g.editorDeleteBlockText=U1,g.editorDeleteBlockWithoutChildren=W1,g.editorDeleteChildContainer=Yb,g.editorDeleteChildContainers=m2,g.editorFocusToBlock=Q1,g.editorFocusToEnd=S2,g.editorGetBlockData=ro,g.editorGetBlockText=ke,g.editorGetBlockTextEx=Ml,g.editorGetBoxData=r2,g.editorHandleKeyboardEvent=e0,g.editorInsertBlock=Dr,g.editorInsertBoxToBlock=l2,g.editorInsertDoc=y2,g.editorInsertDocAt=X1,g.editorInsertText=V1,g.editorInsertTextToBlock=s2,g.editorInsertTextToBlockEx=z1,g.editorMergeTextBlock=g2,g.editorRangeClearColor=I2,g.editorRangeGetColor=td,g.editorRangeSetColor=E2,g.editorRemoveTextAttribute=Jb,g.editorReplaceBlockText=Nl,g.editorReplaceContainer=w2,g.editorRunOnce=xd,g.editorSelectEnd=x2,g.editorSetTextColor=Lr,g.editorShowFindDialog=aO,g.editorUpdateBlockData=Pl,g.editorUpdateCompositionText=c2,g.editorUpdateEmbedData=v2,g.enablePageScroll=um,g.escapeHtmlText=Wf,g.escapeRegExp=i1,g.escapeSpace=N8,g.executeBlockCommand=ng,g.executeEmbedBlockCommand=eg,g.executeRangeCommand=v0,g.fileToDataUrl=nl,g.findAllText=$1,g.findInsertionById=Rm,g.findPrevSimpleBlockBeforeChildContainer=cg,g.findTarget=Bi,g.format=e1,g.formatBytes=vm,g.formatDate=wm,g.fragmentToHtml=hm,g.fromBase64=el,g.fromBase64ToBlob=cm,g.fromBase64ToUint8Array=Z8,g.fromDocRange=no,g.fromNowString=r1,g.genId=N,g.getAllChildBlocks=B1,g.getAllQuickMenuItems=Ku,g.getAllSelectedBlocks=Qe,g.getAttributesAt=Bl,g.getBlockBackground=xm,g.getBlockByIndex=mr,g.getBlockCaretRect=Ge,g.getBlockClass=kt,g.getBlockClassByType=vr,g.getBlockClientRects=Ao,g.getBlockCommandsWithHook=p1,g.getBlockContent=rt,g.getBlockId=G,g.getBlockIndex=K,g.getBlockKind=We,g.getBlockMinWidth=Zm,g.getBlockOptions=uC,g.getBlockPath=Ro,g.getBlockProperties=Km,g.getBlockStyles=aC,g.getBlockTextLength=Z,g.getBlockTools=At,g.getBlockType=it,g.getBoxContent=c1,g.getBoxId=Dm,g.getBoxTypeFromElement=Si,g.getChildBlockCount=Ve,g.getChildBlocks=Rt,g.getChildOffset=Er,g.getColorFromAttributes=P1,g.getComplexBlockClass=ve,g.getContainerBlockPath=Hm,g.getContainerBlocks=Pm,g.getContainerBlocksElement=dl,g.getContainerById=br,g.getContainerId=V,g.getContainerMinWidth=m1,g.getContainerToolsElement=rC,g.getContainerWidth=Qm,g.getDistanceSquare=hn,g.getElementOffset=wi,g.getEmbedType=De,g.getExistsBlockTools=al,g.getExistsContainerById=_m,g.getFileExt=mm,g.getFirstChildBlock=Qt,g.getFirstClientRect=Js,g.getHeadingMenuOptions=Dc,g.getHorizontalPadding=Ua,g.getInsertionContent=a1,g.getLastChildBlock=Gt,g.getLastClientRect=xo,g.getLogger=y,g.getNextBlock=ht,g.getNextValidOffset=Ir,g.getNextVisibleBlock=Cr,g.getOpAt=Lg,g.getOpLength=A1,g.getParentBlock=z,g.getParentBox=l1,g.getParentContainer=H,g.getPrevBlock=gt,g.getPrevValidOffset=Po,g.getPrevVisibleBlock=pr,g.getRangeCommands=C0,g.getRootBlock=ul,g.getScrollContainer=Nn,g.getSpecialBlockCommands=Jm,g.getStandardEmbedBlockProperties=uh,g.getTextBlockChild=gl,g.getTextBlockClass=qm,g.getTextBlockContentChildTextLength=Re,g.getTextBlockContentChildType=hg,g.getTextBlockContentChildren=Hn,g.getTextLength=ce,g.getTextOpLength=I1,g.getTextWidth=rl,g.getToolbar=bc,g.handleBlockElementUpdated=Ym,g.hasAltOnly=z8,g.hasClass=lt,g.hasCtrlOrCmd=rm,g.hasCtrlOrCmdOnly=F8,g.hideBlock=Em,g.htmlToFragment=ol,g.i18n=S,g.injectStyle=Zf,g.insertEmptyBlock=fC,g.insertEmptyEmbedBlock=tg,g.insertText=xr,g.intersectionCommands=iy,g.isBackspace=sm,g.isBlock=gr,g.isBox=s1,g.isCJK=em,g.isChildContainer=qe,g.isChildNode=vt,g.isCollapsedRange=zg,g.isComplexBlockPosition=b1,g.isComplexKindBlock=ct,g.isContainer=fn,g.isControlEvent=Do,g.isDelete=U8,g.isDraggingFiles=sl,g.isEmbedBlock=Te,g.isEmptyContainer=g1,g.isEmptyDoc=xl,g.isEmptyTextBlock=wt,g.isEmptyTextBlockWithoutCompositionText=bs,g.isEnterOnly=im,g.isEscape=Ja,g.isFirefox=Qa,g.isFirstChildBlockInComplexBlock=jC,g.isHighSurrogate=L8,g.isInBlock=d1,g.isInBlockTools=Ti,g.isLetter=tm,g.isLowSurrogate=Va,g.isMatchShortcut=_n,g.isMoveForward=H8,g.isNavigationEvent=$8,g.isNavigationKey=om,g.isNodeRemoved=Vf,g.isNumber=Xf,g.isPrintableKey=Ka,g.isRootBlock=Vo,g.isRootContainer=Ct,g.isSafari=nm,g.isSameDay=o1,g.isShiftEnter=V8,g.isShiftTab=W8,g.isShortcutEvent=j8,g.isSimpleBlock=dC,g.isSimpleBlockPosition=kr,g.isSimplePos=Fg,g.isSimpleRange=Sl,g.isSpace=tl,g.isTab=q8,g.isTextBlockContentBoxChild=Me,g.isTextBlockContentChild=Li,g.isTextBlockContentInsertionChild=$n,g.isTextBlockContentTextChild=Mi,g.isTextKindBlock=j,g.isTextKindBlockType=Di,g.isToday=km,g.isValidOffset=fe,g.isVisibleBlock=cl,g.isYesterday=ym,g.loadJs=Uf,g.loadJsPromise=So,g.lockers=Rn,g.mergeCommands=Cc,g.mergeDocs=jo,g.mergeOps=M1,g.mergeText=kb,g.multiSplitText=gg,g.parseShortcut=lm,g.patchNode=xi,g.pointInRect=To,g.rangeAddAttribute=wl,g.rangeGetTextColor=Ng,g.rangeRemoveAttribute=Sr,g.rangeSetTextColor=Ag,g.rangeTransformText=Mg,g.registerDragDrop=Za,g.removeAttribute=N1,g.removeClass=F,g.removeLastBr=pb,g.removePlaceholderFromBlock=j4,g.removeStyle=Gf,g.replaceAll=nC,g.replaceAllCaseInsensitive=oC,g.replaceAllText=Hg,g.replaceText=El,g.requestDownload=ll,g.scrollable=pm,g.selectFile=fr,g.selectedBlockToDoc=Hl,g.selectionToDoc=jl,g.setAttributes=Wa,g.setClipboardData=il,g.setClipboardDataByEvent=J8,g.setColorToAttributes=Og,g.setDataset=qa,g.setDefaultCursor=Ii,g.setStyles=Ga,g.shortcutToDisplayText=G8,g.showBlock=Im,g.showDocVersions=PP,g.splitText=Ae,g.splitToThree=Kt,g.stringToDataUrl=am,g.stringToObjectUrl=t1,g.subText=pg,g.textNodeOffsetFromPoint=zf,g.toBase64URL=Lo,g.toPlainText=Tt,g.trimChar=Ya,g.unicodeLength=M8,g.unicodeSubstr=R8,g.updateBlockSelection=Gm,g.updateOpAttributes=$g,g.updateTextBlockContent=Mb,g.updateUrl=Xa,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});